Skip to main content

mid_tools/egraph/
congr.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    fmt,
4    hash::Hash,
5    mem,
6};
7
8use hashbrown::{HashMap, HashSet};
9
10use super::{
11    prelude::*,
12    test_tools::EGraphParts,
13    trace::{self, SnapshotEGraph, SnapshotEquivClass},
14    ClassNodes, EGraphTrace, EGraphWriteTrace, ENode,
15};
16use crate::{
17    dot,
18    union_find::{ClassId, NoNode, UnionFind, Unioned},
19};
20
21struct EClassData<F, C> {
22    parents: BTreeMap<ClassId<ENode<F, C>>, ClassId<C>>,
23}
24
25impl<F: fmt::Debug, C> fmt::Debug for EClassData<F, C> {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        let Self { parents } = self;
28        f.debug_struct("EClassData")
29            .field("parents", parents)
30            .finish()
31    }
32}
33
34impl<F, C> Clone for EClassData<F, C> {
35    fn clone(&self) -> Self {
36        Self {
37            parents: self.parents.clone(),
38        }
39    }
40}
41
42impl<F, C> EClassData<F, C> {
43    #[inline]
44    fn new() -> Self {
45        Self {
46            parents: BTreeMap::new(),
47        }
48    }
49}
50
51struct NodeData<F, C> {
52    node: ENode<F, C>,
53    class: ClassId<C>,
54}
55
56impl<F: fmt::Debug, C> fmt::Debug for NodeData<F, C> {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        let Self { node, class } = self;
59        f.debug_struct("NodeData")
60            .field("node", node)
61            .field("class", class)
62            .finish()
63    }
64}
65
66impl<F, C> Clone for NodeData<F, C> {
67    fn clone(&self) -> Self {
68        Self {
69            node: self.node.clone(),
70            class: self.class,
71        }
72    }
73}
74
75impl<F, C> NodeData<F, C> {
76    #[inline]
77    fn new(node: ENode<F, C>, class: ClassId<C>) -> Self { Self { node, class } }
78}
79
80pub struct EGraph<F, C> {
81    eq_uf: UnionFind<C>,
82    congr_uf: UnionFind<ENode<F, C>>,
83    class_data: BTreeMap<ClassId<C>, EClassData<F, C>>,
84    node_data: BTreeMap<ClassId<ENode<F, C>>, NodeData<F, C>>,
85    node_congr_classes: BTreeMap<ENode<F, C>, ClassId<ENode<F, C>>>,
86}
87
88impl<F: fmt::Debug, C> fmt::Debug for EGraph<F, C> {
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        } = self;
97        f.debug_struct("EGraph")
98            .field("eq_uf", eq_uf)
99            .field("congr_uf", congr_uf)
100            .field("class_data", class_data)
101            .field("node_data", node_data)
102            .field("node_congr_classes", node_congr_classes)
103            .finish()
104    }
105}
106
107impl<F, C> Clone for EGraph<F, C> {
108    fn clone(&self) -> Self {
109        Self {
110            eq_uf: self.eq_uf.clone(),
111            congr_uf: self.congr_uf.clone(),
112            class_data: self.class_data.clone(),
113            node_data: self.node_data.clone(),
114            node_congr_classes: self.node_congr_classes.clone(),
115        }
116    }
117}
118
119impl<F, C> Default for EGraph<F, C> {
120    #[inline]
121    fn default() -> Self { Self::new() }
122}
123
124impl<F, C> EGraph<F, C> {
125    #[must_use]
126    pub fn new() -> Self {
127        Self {
128            eq_uf: UnionFind::new(),
129            congr_uf: UnionFind::new(),
130            class_data: BTreeMap::new(),
131            node_data: BTreeMap::new(),
132            node_congr_classes: BTreeMap::new(),
133        }
134    }
135}
136
137impl<F: Eq + Hash, C> From<EGraph<F, C>> for EGraphParts<F, C> {
138    fn from(eg: EGraph<F, C>) -> Self {
139        let EGraph {
140            eq_uf,
141            congr_uf: _,
142            class_data: _,
143            mut node_data,
144            node_congr_classes,
145        } = eg;
146
147        assert_eq!(node_congr_classes.len(), node_data.len());
148
149        let node_classes = node_congr_classes
150            .into_iter()
151            .map(|(k, v)| (k, eq_uf.find(node_data.remove(&v).unwrap().class).unwrap()))
152            .collect();
153
154        EGraphParts {
155            uf: eq_uf,
156            node_classes,
157        }
158    }
159}
160
161impl<F: Ord, C> EGraphCore for EGraph<F, C> {
162    type Class = C;
163    type FuncSymbol = F;
164
165    fn add(&mut self, mut node: ENode<F, C>) -> Result<ClassId<C>, NoNode> {
166        node.canonicalize_classes(&self.eq_uf)?;
167
168        if let Some(c) = self.node_congr_classes.get(&node) {
169            return Ok(self.node_data.get(c).unwrap().class);
170        }
171
172        let eq_class = self.eq_uf.add();
173        let congr_class = self.congr_uf.add();
174
175        assert!(self
176            .node_data
177            .insert(congr_class, NodeData::new(node.clone(), eq_class))
178            .is_none());
179        assert!(self
180            .class_data
181            .insert(eq_class, EClassData::new())
182            .is_none());
183
184        for &arg in node.args() {
185            assert!(self
186                .class_data
187                .get_mut(&arg)
188                .unwrap()
189                .parents
190                .insert(congr_class, eq_class)
191                .is_none_or(|c| eq_class == c));
192        }
193
194        assert!(self.node_congr_classes.insert(node, congr_class).is_none());
195
196        Ok(eq_class)
197    }
198}
199
200impl<F: Ord + Hash, C> EGraphRead for EGraph<F, C> {
201    type Hasher = hashbrown::DefaultHashBuilder;
202
203    #[inline]
204    fn find(&self, class: ClassId<C>) -> Result<ClassId<C>, NoNode> { self.eq_uf.find(class) }
205
206    #[inline]
207    fn canonicalize(&self, node: &mut ENode<F, C>) -> Result<bool, NoNode> {
208        node.canonicalize_classes(&self.eq_uf)
209    }
210
211    #[inline]
212    fn is_canonical(&self, node: &ENode<F, C>) -> Result<bool, NoNode> {
213        node.classes_canonical(&self.eq_uf)
214    }
215
216    fn class_nodes(&self) -> ClassNodes<'_, Self> {
217        self.node_data.values().fold(HashMap::new(), |mut m, d| {
218            assert!(m
219                .entry(self.eq_uf.find(d.class).unwrap())
220                .or_default()
221                .insert(&d.node));
222            m
223        })
224    }
225
226    #[inline]
227    fn dot<M: trace::dot::Formatter<F>>(&self, f: M) -> dot::Graph<'static> {
228        trace::dot_graph(f, self.class_nodes())
229    }
230}
231
232impl<F: Ord + Hash, C> EGraphWriteTrace for EGraph<F, C> {
233    fn merge_trace<T: EGraphTrace<F, C>>(
234        &mut self,
235        a: ClassId<C>,
236        b: ClassId<C>,
237        t: &mut T,
238    ) -> Result<Unioned<C>, NoNode> {
239        let ret = self.merge_impl(a, b, t);
240        self.assert_invariants(true);
241        ret
242    }
243}
244
245impl<F: Ord + Hash, C> EGraph<F, C> {
246    #[inline]
247    fn trace<T: EGraphTrace<F, C>, G: FnOnce() -> I, I: IntoIterator<Item = ClassId<C>>>(
248        &self,
249        t: &mut T,
250        current: G,
251    ) {
252        t.graph(|g| {
253            let mut nodes = trace::snapshot_graph(
254                g,
255                self.node_data.values().fold(
256                    BTreeMap::new(),
257                    |mut m: BTreeMap<ClassId<C>, BTreeSet<_>>, d| {
258                        assert!(m
259                            .entry(self.eq_uf.find(d.class).unwrap())
260                            .or_default()
261                            .insert(&d.node));
262                        m
263                    },
264                ),
265            );
266
267            let mut seen = HashSet::new();
268            for class in current() {
269                let data = self.class_data.get(&class).unwrap();
270                for (&parent, &par_id) in &data.parents {
271                    let parent = self.congr_uf.find(parent).unwrap();
272                    let par_id = self.eq_uf.find(par_id).unwrap();
273
274                    if !seen.insert((class, parent, par_id)) {
275                        continue;
276                    }
277
278                    for class in [class, par_id] {
279                        nodes
280                            .class_reps
281                            .entry(class)
282                            .or_insert_with(|| g.equiv_class(class).id().clone());
283                    }
284
285                    g.parent_edge(
286                        nodes.class_reps.get(&class).unwrap(),
287                        nodes
288                            .node_ids
289                            .get(&self.node_data.get(&parent).unwrap().node)
290                            .unwrap(),
291                        Some(nodes.class_reps.get(&par_id).unwrap()),
292                        Some(&format!("{}-{}", class.id(), parent.id())),
293                    );
294                }
295            }
296
297            // let mut uf = g.union_find("congruence");
298            // let mut congr_ids = BTreeMap::new();
299
300            // for id in self.congr_uf.classes() {
301            //     let class = uf.class(format_args!("{}", id.id()));
302            //     congr_ids.insert(id, class.id().clone());
303            // }
304
305            // for class in self.congr_uf.classes() {
306            //     uf.parent(
307            //         congr_ids.get(&class).unwrap(),
308            //         congr_ids
309            //             .get(&self.congr_uf.parent(class).unwrap())
310            //             .unwrap(),
311            //     );
312            // }
313
314            // for (node, class) in &self.node_congr_classes {
315            //     uf.link_to_node(
316            //         congr_ids.get(class).unwrap(),
317            //         nodes.node_ids.get(&node).unwrap(),
318            //     );
319            // }
320
321            // for class in current() {
322            //     let data = self.class_data.get(&class).unwrap();
323            //     for (parent, par_id) in &data.parents {
324            //         uf.link_from_graph_class(
325            //             nodes.class_reps.get(&class).unwrap(),
326            //             congr_ids.get(parent).unwrap(),
327            //         );
328            //     }
329            // }
330        });
331    }
332
333    fn merge_impl<T: EGraphTrace<F, C>>(
334        &mut self,
335        a: ClassId<C>,
336        b: ClassId<C>,
337        t: &mut T,
338    ) -> Result<Unioned<C>, NoNode> {
339        use std::collections::btree_map::Entry;
340
341        self.trace(t, || {
342            [self.eq_uf.find(a).unwrap(), self.eq_uf.find(b).unwrap()]
343        });
344
345        let union = self.eq_uf.union(a, b)?;
346        let Unioned { root, unioned } = union;
347        t.hl_class(root);
348
349        if let Some(unioned) = unioned {
350            t.hl_class(unioned);
351
352            let EClassData { parents } = self.class_data.remove(&unioned).unwrap();
353            let root_data = self.class_data.get_mut(&root).unwrap();
354
355            let mut new_parents = BTreeMap::new();
356            let mut to_merge = vec![];
357            for (old_congr_class, old_eq_class) in
358                parents.into_iter().chain(mem::take(&mut root_data.parents))
359            {
360                let old_congr_class = self.congr_uf.find(old_congr_class).unwrap();
361                let Entry::Occupied(mut old_par) = self.node_data.entry(old_congr_class) else {
362                    panic!("Missing node_data entry for old node parent");
363                };
364
365                let mut new_par = old_par.get().node.clone();
366                let was_not_canon = new_par.canonicalize_classes(&self.eq_uf).unwrap();
367
368                let new_congr_class;
369                let new_par_data;
370                if was_not_canon {
371                    let old_par = old_par.remove();
372
373                    new_congr_class =
374                        if let Some(other_congr_class) = self.node_congr_classes.remove(&new_par) {
375                            assert!(self
376                                .node_data
377                                .remove(&self.congr_uf.find(other_congr_class).unwrap())
378                                .is_some());
379
380                            let Unioned { root, unioned } = self
381                                .congr_uf
382                                .union(other_congr_class, old_congr_class)
383                                .unwrap();
384
385                            if let Some(unioned) = unioned
386                                && let Some(class) = new_parents.remove(&unioned)
387                            {
388                                new_parents.insert(root, class);
389                            }
390
391                            root
392                        } else {
393                            old_congr_class
394                        };
395
396                    assert!(self.node_congr_classes.remove(&old_par.node).is_some());
397                    assert!(self
398                        .node_congr_classes
399                        .insert(new_par.clone(), new_congr_class)
400                        .is_none());
401
402                    let Entry::Vacant(v) = self.node_data.entry(new_congr_class) else {
403                        panic!("Entry exists in node_data for new congruence class");
404                    };
405
406                    new_par_data = v.insert(NodeData::new(new_par.clone(), old_eq_class));
407                } else {
408                    new_congr_class = old_congr_class;
409                    new_par_data = old_par.get_mut();
410                }
411
412                let new_eq_class = self.eq_uf.find(old_eq_class).unwrap();
413
414                match new_parents.entry(new_congr_class) {
415                    Entry::Vacant(v) => {
416                        v.insert(new_eq_class);
417                        new_par_data.class = new_eq_class;
418                    },
419                    Entry::Occupied(mut o) => {
420                        to_merge.push((o.insert(new_eq_class), new_eq_class));
421                        assert!(self.node_data.contains_key(&new_congr_class));
422                    },
423                }
424            }
425
426            assert!(mem::replace(&mut root_data.parents, new_parents).is_empty());
427
428            self.trace(t, || [root]);
429            t.hl_class(root);
430            t.hl_merges(to_merge.iter().copied());
431
432            self.assert_invariants(false);
433
434            for (a, b) in to_merge {
435                self.merge_impl(a, b, t).unwrap();
436            }
437        } else {
438            self.assert_invariants(false);
439        }
440
441        Ok(union)
442    }
443
444    #[cfg(not(any(test, feature = "test")))]
445    #[inline]
446    fn assert_invariants(&self, _: bool) { let _ = self; }
447
448    #[cfg(any(test, feature = "test"))]
449    fn assert_invariants(&self, merged: bool) {
450        assert_eq!(
451            self.node_data.len(),
452            self.node_congr_classes.len(),
453            "Length mismatch between node_data vs. node_congr_classes"
454        );
455
456        for (node, &congr_class) in &self.node_congr_classes {
457            assert!(*node == self.node_data.get(&congr_class).unwrap().node);
458            assert!(node.classes_canonical(&self.eq_uf).unwrap());
459
460            let root = self.congr_uf.find(congr_class).unwrap();
461            for arg in node.args() {
462                assert!(self
463                    .class_data
464                    .get(arg)
465                    .unwrap()
466                    .parents
467                    .keys()
468                    .any(|&c| self.congr_uf.find(c).unwrap() == root));
469            }
470        }
471
472        for &congr_class in self.node_data.keys() {
473            assert_eq!(
474                congr_class,
475                self.congr_uf.find(congr_class).unwrap(),
476                "Congruence class was not canonical"
477            );
478        }
479
480        for congr_root in self.congr_uf.roots() {
481            assert!(self.node_data.contains_key(&congr_root));
482        }
483
484        for eq_root in self.eq_uf.roots() {
485            assert!(self.class_data.contains_key(&eq_root));
486        }
487
488        for (&eq_class, EClassData { parents }) in &self.class_data {
489            assert_eq!(
490                eq_class,
491                self.eq_uf.find(eq_class).unwrap(),
492                "Equivalence class was not canonical"
493            );
494
495            if merged {
496                let mut seen = BTreeMap::new();
497                for (&congr_class, &eq_class) in parents {
498                    let congr_class = self.congr_uf.find(congr_class).unwrap();
499                    let eq_class = self.eq_uf.find(eq_class).unwrap();
500
501                    assert_eq!(
502                        eq_class,
503                        self.eq_uf
504                            .find(self.node_data.get(&congr_class).unwrap().class)
505                            .unwrap(),
506                        "Node parent class is different than registered node class"
507                    );
508
509                    if let Some(&other_eq_class) = seen.get(&congr_class) {
510                        assert_eq!(
511                            other_eq_class, eq_class,
512                            "Class referents canonicalize to multiple duplicate classes"
513                        );
514                    } else {
515                        seen.insert(congr_class, eq_class);
516                    }
517                }
518            }
519        }
520    }
521}