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},
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<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: Ord, C> EClassData<F, C> {
43 fn new() -> Self {
44 Self {
45 parents: BTreeMap::new(),
46 }
47 }
48}
49
50pub struct EGraph<F, C> {
51 uf: UnionFind<C>,
52 class_data: BTreeMap<ClassId<C>, EClassData<F, C>>,
53 node_classes: BTreeMap<ENode<F, C>, ClassId<C>>,
54}
55
56impl<F: fmt::Debug, C> fmt::Debug for EGraph<F, C> {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 let Self {
59 uf,
60 class_data,
61 node_classes,
62 } = self;
63 f.debug_struct("EGraph")
64 .field("uf", uf)
65 .field("class_data", class_data)
66 .field("node_classes", node_classes)
67 .finish()
68 }
69}
70
71impl<F, C> Clone for EGraph<F, C> {
72 fn clone(&self) -> Self {
73 Self {
74 uf: self.uf.clone(),
75 class_data: self.class_data.clone(),
76 node_classes: self.node_classes.clone(),
77 }
78 }
79}
80
81impl<F, C> Default for EGraph<F, C> {
82 fn default() -> Self { Self::new() }
83}
84
85impl<F, C> EGraph<F, C> {
86 #[must_use]
87 pub fn new() -> Self {
88 Self {
89 uf: UnionFind::new(),
90 class_data: BTreeMap::new(),
91 node_classes: BTreeMap::new(),
92 }
93 }
94}
95
96impl<F: Ord + Hash, C> From<EGraph<F, C>> for EGraphParts<F, C> {
97 fn from(eg: EGraph<F, C>) -> Self {
98 let EGraph {
99 uf,
100 class_data: _,
101 node_classes,
102 } = eg;
103
104 let node_classes = node_classes
105 .into_iter()
106 .map(|(n, c)| (n, uf.find(c).unwrap()))
107 .collect();
108
109 EGraphParts { uf, node_classes }
110 }
111}
112
113impl<F: Ord, C> EGraphCore for EGraph<F, C> {
114 type Class = C;
115 type FuncSymbol = F;
116
117 fn add(&mut self, mut node: ENode<F, C>) -> Result<ClassId<C>, NoNode> {
118 node.canonicalize_classes(&self.uf)?;
119 Ok(if let Some(&class) = self.node_classes.get(&node) {
120 assert_eq!(class, self.uf.find(class).unwrap());
121 class
122 } else {
123 let class = self.uf.add();
124 assert!(self.class_data.insert(class, EClassData::new()).is_none());
125
126 for &arg in node.args() {
127 assert!(self
128 .class_data
129 .get_mut(&arg)
130 .unwrap()
131 .parents
132 .insert(node.clone(), class)
133 .is_none_or(|c| class == c));
134 }
135
136 assert!(self.node_classes.insert(node, class).is_none());
137
138 class
139 })
140 }
141}
142
143impl<F: Ord + Hash, C> EGraphRead for EGraph<F, C> {
144 type Hasher = hashbrown::DefaultHashBuilder;
145
146 #[inline]
147 fn find(&self, class: ClassId<C>) -> Result<ClassId<C>, NoNode> { self.uf.find(class) }
148
149 #[inline]
150 fn canonicalize(&self, node: &mut ENode<F, C>) -> Result<bool, NoNode> {
151 node.canonicalize_classes(&self.uf)
152 }
153
154 #[inline]
155 fn is_canonical(&self, node: &ENode<F, C>) -> Result<bool, NoNode> {
156 node.classes_canonical(&self.uf)
157 }
158
159 fn class_nodes(&self) -> ClassNodes<'_, Self, Self::Hasher> {
160 self.node_classes
161 .iter()
162 .fold(HashMap::new(), |mut m: HashMap<_, HashSet<_>>, (n, &c)| {
163 assert!(n.is_canonical(self).unwrap());
164 assert!(m.entry(self.uf.find(c).unwrap()).or_default().insert(n));
165 m
166 })
167 }
168
169 #[inline]
170 fn dot<M: trace::dot::Formatter<Self::FuncSymbol>>(&self, f: M) -> dot::Graph<'static> {
171 trace::dot_graph(f, self.class_nodes())
172 }
173}
174
175impl<F: Ord + Hash, C> EGraphWriteTrace for EGraph<F, C> {
176 fn merge_trace<T: EGraphTrace<F, C>>(
177 &mut self,
178 a: ClassId<C>,
179 b: ClassId<C>,
180 t: &mut T,
181 ) -> Result<Unioned<C>, NoNode> {
182 let ret = self.merge_impl(a, b, &mut self.uf.clone(), t);
183 self.assert_invariants(true);
184 ret
185 }
186}
187
188impl<F: Ord + Hash, C> EGraph<F, C> {
189 #[inline]
190 fn trace<T: EGraphTrace<F, C>, G: FnOnce() -> I, I: IntoIterator<Item = ClassId<C>>>(
191 &self,
192 t: &mut T,
193 current: G,
194 ) {
195 t.graph(|g| {
196 let nodes = trace::snapshot_graph(
197 g,
198 self.node_classes.iter().fold(
199 BTreeMap::new(),
200 |mut m: BTreeMap<_, BTreeSet<_>>, (n, &c)| {
201 assert!(m.entry(self.uf.find(c).unwrap()).or_default().insert(n));
202 m
203 },
204 ),
205 );
206
207 let mut seen = BTreeSet::new();
208 for class in current() {
209 let data = self.class_data.get(&class).unwrap();
210 for (parent, par_id) in &data.parents {
211 let parent = parent.to_canonical(self).unwrap();
212
213 if !seen.insert((class, parent.clone(), par_id)) {
214 continue;
215 }
216
217 g.parent_edge(
218 nodes.class_reps.get(&class).unwrap(),
219 nodes.node_ids.get(&parent).unwrap(),
220 nodes.class_reps.get(par_id),
221 None,
222 );
223 }
224 }
225 });
226 }
227
228 fn merge_impl<T: EGraphTrace<F, C>>(
229 &mut self,
230 a: ClassId<C>,
231 b: ClassId<C>,
232 old_uf: &mut UnionFind<C>,
233 t: &mut T,
234 ) -> Result<Unioned<C>, NoNode> {
235 self.trace(t, || [self.uf.find(a).unwrap(), self.uf.find(b).unwrap()]);
236
237 old_uf.clone_from(&self.uf);
238 let union = self.uf.union(a, b)?;
239 let Unioned { root, unioned } = union;
240 t.hl_class(root);
241
242 if let Some(unioned) = unioned {
243 t.hl_class(unioned);
244
245 let EClassData { parents } = self.class_data.remove(&unioned).unwrap();
246 let root_data = self.class_data.get_mut(&root).unwrap();
247
248 let mut to_merge = vec![];
249 let mut new_parents = BTreeMap::new();
252 let mut new_nodes = BTreeMap::new();
253 for (mut old_par, par_class) in
254 parents.into_iter().chain(mem::take(&mut root_data.parents))
255 {
256 use std::collections::btree_map::Entry;
257
258 assert!(old_par.args().iter().any(|&c| c == unioned || c == root));
259 old_par.canonicalize_classes(old_uf).unwrap();
260
261 let par_class = self.uf.find(par_class).unwrap();
262 let _old = self.node_classes.remove(&old_par);
263
264 old_par.canonicalize_classes(&self.uf).unwrap();
265 let new_par = old_par;
266
267 match new_parents.entry(new_par.clone()) {
268 Entry::Occupied(mut o) => {
269 let other_par_class = o.insert(par_class);
270 to_merge.push((par_class, other_par_class));
271
272 assert!(
273 new_nodes.contains_key(&new_par)
274 || self.node_classes.contains_key(&new_par)
275 );
276 },
277 Entry::Vacant(v) => {
278 v.insert(par_class);
279
280 assert!(new_nodes.insert(new_par, par_class).is_none());
281 },
282 }
283 }
284
285 assert!(mem::replace(&mut root_data.parents, new_parents).is_empty());
286 let expected_len = self.node_classes.len() + new_nodes.len();
287 self.node_classes.extend(new_nodes);
288 assert_eq!(self.node_classes.len(), expected_len);
289
290 self.assert_invariants(false);
291
292 self.trace(t, || [root]);
293 t.hl_class(root);
294 t.hl_merges(to_merge.iter().copied());
295
296 for (a, b) in to_merge {
297 self.merge_impl(a, b, old_uf, t).unwrap();
298 }
299 } else {
300 self.assert_invariants(false);
301 }
302
303 Ok(union)
304 }
305
306 #[cfg(not(any(test, feature = "test")))]
307 #[inline]
308 fn assert_invariants(&self, _: bool) { let _ = self; }
309
310 #[cfg(any(test, feature = "test"))]
311 fn assert_invariants(&self, merged: bool) {
312 for node in self.node_classes.keys() {
313 assert!(node.classes_canonical(&self.uf).unwrap());
314 }
315
316 for (&class, EClassData { parents }) in &self.class_data {
317 assert_eq!(class, self.uf.find(class).unwrap());
318
319 if merged {
320 let mut seen = BTreeMap::new();
321 for (par, &class) in parents {
322 let canon = par.to_canonical(self).unwrap();
323 let class = self.uf.find(class).unwrap();
324
325 assert_eq!(
326 class,
327 self.uf
328 .find(*self.node_classes.get(&canon).unwrap())
329 .unwrap(),
330 "Node parent class is different than registered node class"
331 );
332
333 if let Some(&other) = seen.get(&canon) {
334 assert_eq!(
335 other, class,
336 "Class referents canonicalize to multiple duplicate classes"
337 );
338 } else {
339 seen.insert(canon, class);
340 }
341 }
342 }
343 }
344 }
345}