1use std::{fmt, hash::Hash};
2
3use hashbrown::HashMap;
4
5use super::ENode;
6use crate::union_find::ClassId;
7
8pub trait EGraphTrace<F: ?Sized, C: ?Sized> {
9 type Graph: SnapshotEGraph<F, C>;
10
11 fn graph<G: FnOnce(&mut Self::Graph)>(&mut self, f: G);
12
13 fn hl_class(&mut self, root: ClassId<C>);
14
15 fn hl_classes<I: IntoIterator<Item = ClassId<C>>>(&mut self, it: I);
16
17 fn hl_merges<I: IntoIterator<Item = (ClassId<C>, ClassId<C>)>>(&mut self, it: I);
18}
19
20impl<T: EGraphTrace<F, C>, F, C> EGraphTrace<F, C> for &mut T {
21 type Graph = T::Graph;
22
23 #[inline]
24 fn graph<G: FnOnce(&mut Self::Graph)>(&mut self, f: G) { T::graph(self, f) }
25
26 #[inline]
27 fn hl_class(&mut self, root: ClassId<C>) { T::hl_class(self, root) }
28
29 #[inline]
30 fn hl_classes<I: IntoIterator<Item = ClassId<C>>>(&mut self, it: I) { T::hl_classes(self, it) }
31
32 #[inline]
33 fn hl_merges<I: IntoIterator<Item = (ClassId<C>, ClassId<C>)>>(&mut self, it: I) {
34 T::hl_merges(self, it);
35 }
36}
37
38pub trait SnapshotEGraph<F: ?Sized, C: ?Sized> {
39 type UnionFind<'a>: SnapshotUnionFind<GraphClassId = Self::ClassId, NodeId = Self::NodeId>
40 where Self: 'a;
41 type EquivClass<'a>: SnapshotEquivClass<
42 F,
43 C,
44 Id = Self::ClassId,
45 Node: SnapshotNode<Id = Self::NodeId>,
46 >
47 where Self: 'a;
48 type ClassId: Clone;
49 type NodeId: Clone;
50
51 fn union_find(&mut self, name: &'static str) -> Self::UnionFind<'_>;
52
53 fn equiv_class(&mut self, root: ClassId<C>) -> Self::EquivClass<'_>;
54
55 fn edge(&mut self, node: &Self::NodeId, class: &Self::ClassId, op: &F, arg_idx: usize);
56
57 fn parent_edge(
58 &mut self,
59 class: &Self::ClassId,
60 parent: &Self::NodeId,
61 parent_class: Option<&Self::ClassId>,
62 label: Option<&str>,
63 );
64}
65
66pub trait SnapshotEquivClass<F: ?Sized, C: ?Sized> {
67 type Id: Clone;
68 type Node: SnapshotNode;
69
70 fn id(&self) -> &Self::Id;
71
72 fn node(&mut self, node: &ENode<F, C>) -> Self::Node;
73}
74
75pub trait SnapshotNode {
76 type Id: Clone;
77
78 fn id(&self) -> &Self::Id;
79}
80
81pub trait SnapshotUnionFind {
82 type Class: SnapshotUfClass<Id = Self::ClassId>;
83 type GraphClassId: Clone;
84 type ClassId: Clone;
85 type NodeId: Clone;
86
87 fn class(&mut self, fmt: fmt::Arguments) -> Self::Class;
88
89 fn parent(&mut self, class: &Self::ClassId, parent: &Self::ClassId);
90
91 fn link_from_graph_class(&mut self, from: &Self::GraphClassId, to: &Self::ClassId);
92
93 fn link_to_node(&mut self, class: &Self::ClassId, node: &Self::NodeId);
94}
95
96pub trait SnapshotUfClass {
97 type Id;
98
99 fn id(&self) -> &Self::Id;
100}
101
102impl<F: ?Sized, C: ?Sized> EGraphTrace<F, C> for () {
103 type Graph = ();
104
105 #[inline]
106 fn graph<G: FnOnce(&mut Self::Graph)>(&mut self, _: G) {}
107
108 #[inline]
109 fn hl_class(&mut self, _: ClassId<C>) {}
110
111 #[inline]
112 fn hl_classes<I: IntoIterator<Item = ClassId<C>>>(&mut self, _: I) {}
113
114 #[inline]
115 fn hl_merges<I: IntoIterator<Item = (ClassId<C>, ClassId<C>)>>(&mut self, _: I) {}
116}
117
118impl<F: ?Sized, C: ?Sized> SnapshotEGraph<F, C> for () {
119 type ClassId = ();
120 type EquivClass<'a> = ();
121 type NodeId = ();
122 type UnionFind<'a> = ();
123
124 #[inline]
125 fn union_find(&mut self, _: &str) -> Self::UnionFind<'_> {}
126
127 #[inline]
128 fn equiv_class(&mut self, _: ClassId<C>) -> Self::EquivClass<'_> {}
129
130 #[inline]
131 fn edge(&mut self, (): &Self::NodeId, (): &Self::ClassId, _: &F, _: usize) {}
132
133 #[inline]
134 fn parent_edge(
135 &mut self,
136 (): &Self::ClassId,
137 (): &Self::NodeId,
138 parent_class: Option<&Self::ClassId>,
139 _: Option<&str>,
140 ) {
141 let () = parent_class.unwrap_or(&());
142 }
143}
144
145impl<F: ?Sized, C: ?Sized> SnapshotEquivClass<F, C> for () {
146 type Id = ();
147 type Node = ();
148
149 #[inline]
150 fn id(&self) -> &Self::Id { self }
151
152 #[inline]
153 fn node(&mut self, _: &ENode<F, C>) -> Self::Node {}
154}
155
156impl SnapshotNode for () {
157 type Id = ();
158
159 #[inline]
160 fn id(&self) -> &Self::Id { self }
161}
162
163impl SnapshotUnionFind for () {
164 type Class = ();
165 type ClassId = ();
166 type GraphClassId = ();
167 type NodeId = ();
168
169 #[inline]
170 fn class(&mut self, _: fmt::Arguments) -> Self::Class {}
171
172 #[inline]
173 fn parent(&mut self, (): &Self::ClassId, (): &Self::ClassId) {}
174
175 #[inline]
176 fn link_from_graph_class(&mut self, (): &Self::GraphClassId, (): &Self::ClassId) {}
177
178 #[inline]
179 fn link_to_node(&mut self, (): &Self::ClassId, (): &Self::NodeId) {}
180}
181
182impl SnapshotUfClass for () {
183 type Id = ();
184
185 #[inline]
186 fn id(&self) -> &Self::Id { self }
187}
188
189pub mod dot {
190 use std::{borrow::Cow, fmt, marker::PhantomData};
191
192 use super::{
193 SnapshotEGraph, SnapshotEquivClass, SnapshotNode, SnapshotUfClass, SnapshotUnionFind,
194 };
195 use crate::{
196 dot::{Graph as DotGraph, GraphType},
197 egraph::ENode,
198 union_find::ClassId,
199 };
200
201 pub trait Formatter<F: ?Sized>: Copy {
202 fn fmt_node(&self, op: &F, f: &mut fmt::Formatter) -> fmt::Result;
203
204 fn fmt_edge(&self, op: &F, idx: usize, f: &mut fmt::Formatter) -> fmt::Result;
205 }
206
207 pub trait Format {
208 fn fmt_node(&self, f: &mut fmt::Formatter) -> fmt::Result;
209
210 fn fmt_edge(&self, idx: usize, f: &mut fmt::Formatter) -> fmt::Result;
211 }
212
213 #[derive(Debug, Clone, Copy)]
214 pub struct DebugFormatter;
215
216 impl<F: ?Sized + fmt::Debug> Formatter<F> for DebugFormatter {
217 #[inline]
218 fn fmt_node(&self, op: &F, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(op, f) }
219
220 #[inline]
221 fn fmt_edge(&self, _: &F, _: usize, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
222 }
223
224 #[derive(Debug, Clone, Copy)]
225 pub struct RichFormatter;
226
227 impl<F: ?Sized + Format> Formatter<F> for RichFormatter {
228 #[inline]
229 fn fmt_node(&self, op: &F, f: &mut fmt::Formatter) -> fmt::Result { op.fmt_node(f) }
230
231 #[inline]
232 fn fmt_edge(&self, op: &F, idx: usize, f: &mut fmt::Formatter) -> fmt::Result {
233 op.fmt_edge(idx, f)
234 }
235 }
236
237 pub struct ClosureFormatter<F, N, E>(N, E, PhantomData<fn(&F)>);
238
239 impl<F, N: fmt::Debug, E: fmt::Debug> fmt::Debug for ClosureFormatter<F, N, E> {
240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241 f.debug_tuple("ClosureFormatter")
242 .field(&self.0)
243 .field(&self.1)
244 .finish()
245 }
246 }
247
248 impl<F, N: Clone, E: Clone> Clone for ClosureFormatter<F, N, E> {
249 fn clone(&self) -> Self { Self(self.0.clone(), self.1.clone(), PhantomData) }
250 }
251
252 impl<F, N: Copy, E: Copy> Copy for ClosureFormatter<F, N, E> {}
253
254 impl<
255 F,
256 N: Fn(&F, &mut fmt::Formatter) -> fmt::Result + Copy,
257 E: Fn(&F, usize, &mut fmt::Formatter) -> fmt::Result + Copy,
258 > ClosureFormatter<F, N, E>
259 {
260 #[inline]
261 #[must_use]
262 pub const fn new(fmt_node: N, fmt_edge: E) -> Self { Self(fmt_node, fmt_edge, PhantomData) }
263 }
264
265 impl<
266 F,
267 N: Fn(&F, &mut fmt::Formatter) -> fmt::Result + Copy,
268 E: Fn(&F, usize, &mut fmt::Formatter) -> fmt::Result + Copy,
269 > Formatter<F> for ClosureFormatter<F, N, E>
270 {
271 #[inline]
272 fn fmt_node(&self, op: &F, f: &mut fmt::Formatter) -> fmt::Result { self.0(op, f) }
273
274 #[inline]
275 fn fmt_edge(&self, op: &F, idx: usize, f: &mut fmt::Formatter) -> fmt::Result {
276 self.1(op, idx, f)
277 }
278 }
279
280 #[derive(Debug)]
281 pub struct Snapshot {
282 pub graph: DotGraph<'static>,
283 }
284
285 #[derive(Debug)]
286 pub struct Graph<M>(pub(super) DotGraph<'static>, M);
287 #[derive(Debug)]
288 pub struct EquivClass<'a, M>(Cow<'static, str>, &'a mut DotGraph<'static>, M);
289 #[derive(Debug)]
290 pub struct Node(Cow<'static, str>);
291
292 #[derive(Debug)]
293 pub struct UnionFind<'a, M>(Cow<'static, str>, &'a mut DotGraph<'static>, M);
294 #[derive(Debug)]
295 pub struct UfClass(Cow<'static, str>);
296
297 impl<M> Graph<M> {
298 #[inline]
299 pub fn new(f: M) -> Self { Self(DotGraph::new(GraphType::Directed), f) }
300
301 pub fn from_parts(graph: DotGraph<'static>, f: M) -> Self { Self(graph, f) }
302 }
303
304 impl<F: ?Sized, C: ?Sized, M: Formatter<F>> SnapshotEGraph<F, C> for Graph<M> {
305 type ClassId = Cow<'static, str>;
306 type EquivClass<'a>
307 = EquivClass<'a, M>
308 where M: 'a;
309 type NodeId = Cow<'static, str>;
310 type UnionFind<'a>
311 = UnionFind<'a, M>
312 where M: 'a;
313
314 fn union_find(&mut self, name: &'static str) -> Self::UnionFind<'_> {
315 let id = Cow::from(format!("cluster_uf_{name}"));
316 let sg = self.0.subgraph(id.clone());
317 sg.style("solid");
318 sg.label(name);
319
320 UnionFind(id, sg, self.1)
321 }
322
323 fn equiv_class(&mut self, root: ClassId<C>) -> Self::EquivClass<'_> {
324 let sg = self.0.subgraph(format!("cluster_{}", root.id()));
325 sg.style("filled");
326 sg.label(format!("{}", root.id()));
327
328 let rep_id = Cow::from(format!("class_{}", root.id()));
329 let class_node = sg.node(rep_id.clone());
330 class_node.style("invis");
331 class_node.shape("point");
332 class_node.label("");
333
334 EquivClass(rep_id, sg, self.1)
335 }
336
337 fn edge(&mut self, node: &Self::NodeId, class: &Self::ClassId, op: &F, arg_idx: usize) {
338 struct Fmt<'a, F: ?Sized, M: ?Sized>(&'a F, usize, &'a M);
339
340 impl<F: ?Sized, M: Formatter<F>> fmt::Display for Fmt<'_, F, M> {
341 #[inline]
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 self.2.fmt_edge(self.0, self.1, f)
344 }
345 }
346
347 let edge = self.0.edge(node.clone(), class.clone());
348
349 let s = format!("{}", Fmt(op, arg_idx, &self.1));
350 if !s.is_empty() {
351 edge.label(s);
352 }
353 }
354
355 fn parent_edge(
356 &mut self,
357 class: &Self::ClassId,
358 parent: &Self::NodeId,
359 parent_class: Option<&Self::ClassId>,
360 label: Option<&str>,
361 ) {
362 let parent_edge = self.0.edge(class.clone(), parent.clone());
363
364 parent_edge.constraint("false");
365 parent_edge.color("blue");
366 parent_edge.style("dashed");
367
368 if let Some(label) = label {
369 parent_edge.label(label.to_owned());
370 }
371
372 if let Some(parent_class) = parent_class {
373 let class_edge = self.0.edge(parent.clone(), parent_class.clone());
374
375 class_edge.constraint("false");
376 class_edge.color("blue");
377 class_edge.style("dotted");
378
379 if let Some(label) = label {
380 class_edge.label(label.to_owned());
381 }
382 }
383 }
384 }
385
386 impl<F: ?Sized, C: ?Sized, M: Formatter<F>> SnapshotEquivClass<F, C> for EquivClass<'_, M> {
387 type Id = Cow<'static, str>;
388 type Node = Node;
389
390 #[inline]
391 fn id(&self) -> &Self::Id { &self.0 }
392
393 fn node(&mut self, node: &ENode<F, C>) -> Self::Node {
394 struct Fmt<'a, F: ?Sized, M: ?Sized>(&'a F, &'a M);
395
396 impl<F: ?Sized, M: Formatter<F>> fmt::Display for Fmt<'_, F, M> {
397 #[inline]
398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399 self.1.fmt_node(self.0, f)
400 }
401 }
402
403 let mut label = format!("{}(", Fmt(node.op(), &self.2));
404 for (i, arg) in node.args().iter().enumerate() {
405 if i > 0 {
406 label.push(',');
407 }
408
409 label.push_str(&arg.id().to_string());
410 }
411 label.push(')');
412 let id = Cow::from(format!("{}_node_{label}", self.0));
413
414 let node = self.1.node(id.clone());
415 node.label(label);
416 node.edge_ordering("out");
417 let edge = self.1.edge(self.0.clone(), id.clone());
418 edge.style("invis");
419
420 Node(id)
421 }
422 }
423
424 impl SnapshotNode for Node {
425 type Id = Cow<'static, str>;
426
427 #[inline]
428 fn id(&self) -> &Self::Id { &self.0 }
429 }
430
431 impl<M> SnapshotUnionFind for UnionFind<'_, M> {
432 type Class = UfClass;
433 type ClassId = Cow<'static, str>;
434 type GraphClassId = Cow<'static, str>;
435 type NodeId = Cow<'static, str>;
436
437 fn class(&mut self, fmt: fmt::Arguments) -> Self::Class {
438 let label = fmt.to_string();
439 let id = Cow::from(format!("{}_node_{label}", self.0));
440 let node = self.1.node(id.clone());
441 node.label(label);
442
443 UfClass(id)
444 }
445
446 fn parent(&mut self, class: &Self::ClassId, parent: &Self::ClassId) {
447 self.1.edge(class.clone(), parent.clone());
448 }
449
450 fn link_from_graph_class(&mut self, from: &Self::GraphClassId, to: &Self::ClassId) {
451 let edge = self.1.edge(from.clone(), to.clone());
452 edge.style("dashed");
453 edge.constraint("false");
454 edge.concentrate("false");
455 edge.color("red");
456 }
457
458 fn link_to_node(&mut self, class: &Self::ClassId, node: &Self::NodeId) {
459 let edge = self.1.edge(class.clone(), node.clone());
460 edge.style("dashed");
461 edge.color("blue");
462 }
463 }
464
465 impl SnapshotUfClass for UfClass {
466 type Id = Cow<'static, str>;
467
468 #[inline]
469 fn id(&self) -> &Self::Id { &self.0 }
470 }
471}
472
473#[derive(Debug)]
474pub struct DotTracer<M, F>(Option<dot::Snapshot>, M, F);
475
476impl<
477 F,
478 N: Fn(&F, &mut fmt::Formatter) -> fmt::Result + Copy,
479 E: Fn(&F, usize, &mut fmt::Formatter) -> fmt::Result + Copy,
480 G,
481 > DotTracer<dot::ClosureFormatter<F, N, E>, G>
482{
483 #[must_use]
484 pub fn new(fmt_node: N, fmt_edge: E, f: G) -> Self {
485 Self(None, dot::ClosureFormatter::new(fmt_node, fmt_edge), f)
486 }
487}
488
489impl<M, F: FnMut(dot::Snapshot)> DotTracer<M, F> {
490 pub fn flush(&mut self) {
491 if let Some(snap) = self.0.take() {
492 self.2(snap);
493 }
494 }
495}
496
497impl<F> DotTracer<dot::DebugFormatter, F> {
498 #[inline]
499 #[must_use]
500 pub fn debug(f: F) -> Self { Self(None, dot::DebugFormatter, f) }
501}
502
503impl<F> DotTracer<dot::RichFormatter, F> {
504 #[inline]
505 #[must_use]
506 pub fn rich(f: F) -> Self { Self(None, dot::RichFormatter, f) }
507}
508
509impl<F: ?Sized, C: ?Sized, M: dot::Formatter<F>, G: FnMut(dot::Snapshot)> EGraphTrace<F, C>
510 for DotTracer<M, G>
511{
512 type Graph = dot::Graph<M>;
513
514 #[inline]
515 fn graph<H: FnOnce(&mut Self::Graph)>(&mut self, f: H) {
516 let mut graph = dot::Graph::new(self.1);
517 f(&mut graph);
518 if let Some(snap) = self.0.replace(dot::Snapshot { graph: graph.0 }) {
519 self.2(snap);
520 }
521 }
522
523 fn hl_class(&mut self, root: ClassId<C>) {
524 self.0
525 .as_mut()
526 .unwrap()
527 .graph
528 .subgraph(format!("cluster_{}", root.id()))
529 .penwidth("4.0");
530 }
531
532 #[inline]
533 fn hl_classes<I: IntoIterator<Item = ClassId<C>>>(&mut self, it: I) {
534 it.into_iter().for_each(|c| self.hl_class(c));
535 }
536
537 fn hl_merges<I: IntoIterator<Item = (ClassId<C>, ClassId<C>)>>(&mut self, it: I) {
538 let graph = &mut self.0.as_mut().unwrap().graph;
539
540 for (a, b) in it {
541 let edge = graph.edge(format!("class_{}", a.id()), format!("class_{}", b.id()));
542
543 edge.style("dashed");
544 edge.constraint("false");
545 }
546 }
547}
548
549pub fn dot_graph<
550 'a,
551 'b,
552 F: Eq + Hash + 'b,
553 C: 'b,
554 M: dot::Formatter<F>,
555 IR: IntoIterator<Item = (ClassId<C>, IN)> + Clone,
556 IN: IntoIterator<Item = &'b crate::egraph::ENode<F, C>>,
557>(
558 f: M,
559 roots: IR,
560) -> crate::dot::Graph<'static> {
561 let mut graph = dot::Graph::new(f);
562 snapshot_graph(&mut graph, roots);
563 graph.0
564}
565
566#[derive(Debug)]
567pub struct SnapshotGraphNodes<'a, F, C, IC, IN> {
568 pub class_reps: HashMap<ClassId<C>, IC>,
569 pub node_ids: HashMap<&'a ENode<F, C>, IN>,
570}
571
572pub fn snapshot_graph<
573 'a,
574 'b,
575 F: Eq + Hash + 'b,
576 C: 'b,
577 S: SnapshotEGraph<F, C>,
578 IR: IntoIterator<Item = (ClassId<C>, IN)> + Clone,
579 IN: IntoIterator<Item = &'b ENode<F, C>>,
580>(
581 graph: &mut S,
582 roots: IR,
583) -> SnapshotGraphNodes<'b, F, C, S::ClassId, S::NodeId> {
584 let mut class_reps = HashMap::new();
585 let mut node_ids = HashMap::new();
586
587 for (root, enodes) in roots.clone() {
588 let mut cls = graph.equiv_class(root);
589 assert!(class_reps.insert(root, cls.id().clone()).is_none());
590
591 for enode in enodes {
592 let node = cls.node(enode);
593 assert!(node_ids.insert(enode, node.id().clone()).is_none());
594 }
595 }
596
597 for (_, enodes) in roots {
598 for enode in enodes {
599 for (i, &edge) in enode.args().iter().enumerate() {
600 let class = class_reps
601 .entry(edge)
602 .or_insert_with(|| graph.equiv_class(edge).id().clone());
603
604 graph.edge(node_ids.get(enode).unwrap(), class, enode.op(), i);
605 }
606 }
607 }
608
609 SnapshotGraphNodes {
610 class_reps,
611 node_ids,
612 }
613}