Skip to main content

semi_persistent_egraph/
viz.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! E-graph visualization: export to GraphViz DOT.
4
5use crate::canon::{MSetCanon, VarCanon};
6use crate::config::EGraphConfig;
7use crate::containers::DenseId;
8use crate::egraph::EGraph;
9use crate::literal::LitVal;
10use crate::multiplicity::MultiplicityLike;
11use std::fmt::Write;
12
13impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
14    EGraph<Cfg, L, TRACK, PROOFS>
15where
16    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
17{
18    /// Emit GraphViz DOT representation.
19    pub fn to_dot(&self) -> String {
20        let mut out = String::from("digraph egraph {\n  compound=true\n  clusterrank=local\n\n");
21
22        // Typed ids on both sides of the grouping. Holding raw `usize` copies here meant
23        // re-minting each member twice below — once per pass — to recover an id the scan
24        // had already produced.
25        let mut classes: std::collections::BTreeMap<Cfg::G, Vec<Cfg::G>> =
26            std::collections::BTreeMap::new();
27        for gid in self.node_ids() {
28            classes.entry(self.class_repr(gid)).or_default().push(gid);
29        }
30
31        for (repr, members) in &classes {
32            let repr = repr.to_usize();
33            let _ = write!(out, "  subgraph cluster_{repr} {{\n    style=dotted\n");
34            for (idx, &gid) in members.iter().enumerate() {
35                let op = self.node_op_name(gid);
36                let label = match self.node_lit(gid) {
37                    Some(lit) => format!("{op}({v})", v = self.lits().get(lit)),
38                    None => op.to_string(),
39                };
40                let _ = writeln!(out, "    {repr}.{idx}[label = \"{label}\"]");
41            }
42            let _ = writeln!(out, "  }}");
43        }
44
45        for (&class_id, members) in &classes {
46            let class_repr = class_id.to_usize();
47            for (idx, &gid) in members.iter().enumerate() {
48                let mut arg_i = 0usize;
49                let arity = self.node_arity(gid);
50                self.for_each_child(gid, |child, mult| {
51                    let anchor = Self::anchor(arg_i, arity);
52                    let child_id = self.class_repr(child);
53                    let child_repr = child_id.to_usize();
54                    let ml = if mult > Cfg::M::ONE { format!(", label=\"×{mult}\"") } else { String::new() };
55                    if child_id == class_id {
56                        // self-edge: point to self with lhead
57                        let _ = writeln!(out, "  {class_repr}.{idx}{anchor} -> {class_repr}.{idx}:n [lhead=cluster_{class_repr}{ml}]");
58                    } else {
59                        let _ = writeln!(out, "  {class_repr}.{idx}{anchor} -> {child_repr}.0 [lhead=cluster_{child_repr}{ml}]");
60                    }
61                    arg_i += 1;
62                });
63            }
64        }
65
66        out.push_str("}\n");
67        out
68    }
69
70    fn node_arity(&self, id: Cfg::G) -> usize {
71        let mut count = 0;
72        self.for_each_child(id, |_, _| count += 1);
73        count
74    }
75
76    fn anchor(i: usize, len: usize) -> &'static str {
77        match (len, i) {
78            (1, 0) => "",
79            (2, 0) => ":sw",
80            (2, 1) => ":se",
81            (3, 0) => ":sw",
82            (3, 1) => ":s",
83            (3, 2) => ":se",
84            _ => "",
85        }
86    }
87
88    /// Write DOT to a file, render with `dot`, and open the result.
89    pub fn show(&self, label: &str) {
90        let dot = self.to_dot();
91        let safe = label.replace(|c: char| !c.is_alphanumeric() && c != '_' && c != '-', "_");
92        let dot_path = std::env::temp_dir().join(format!("sp_{safe}.dot"));
93        let svg_path = std::env::temp_dir().join(format!("sp_{safe}.svg"));
94        std::fs::write(&dot_path, &dot).expect("failed to write dot");
95
96        let status = std::process::Command::new("dot")
97            .args(["-Tsvg", "-o"])
98            .arg(&svg_path)
99            .arg(&dot_path)
100            .status();
101
102        match status {
103            Ok(s) if s.success() => {
104                eprintln!("Wrote {}", svg_path.display());
105                #[cfg(target_os = "macos")]
106                {
107                    let _ = std::process::Command::new("open")
108                        .arg("-a")
109                        .arg("Safari")
110                        .arg(&svg_path)
111                        .spawn();
112                }
113                #[cfg(target_os = "linux")]
114                {
115                    let _ = std::process::Command::new("xdg-open")
116                        .arg(&svg_path)
117                        .spawn();
118                }
119            }
120            _ => {
121                eprintln!("dot not found or failed; wrote {}", dot_path.display());
122            }
123        }
124    }
125}