Skip to main content

fic/emit/
dot.rs

1//! Graphviz DOT graph generation for Fiducia system topology.
2//!
3//! Generates a `.dot` file from the resolved AST showing:
4//! - Protection domains as virtual address-space columns (HTML label tables)
5//! - Memory regions as plain rectangles
6//! - Channel connections between PDs (solid directed edges)
7//! - Memory mappings anchored from each vaddr row in the PD to its region (dashed edges)
8//!
9//! Render with: `dot -Tpng output.dot -o output.png`
10
11use std::collections::HashMap;
12use std::fmt::Write as FmtWrite;
13
14use anyhow::{Context, Result};
15
16use crate::ast::ChannelKind;
17use crate::tast::TyEnv;
18
19/// One row per mapped region in a PD's address-space table: explicit
20/// `Mapping`s plus channel-buffer regions (implicitly mapped into both
21/// endpoints, #239).
22struct Row<'a> {
23    region: &'a str,
24    vaddr: Option<u64>,
25    perms: &'a str,
26}
27
28/// Write a Graphviz DOT representation of `rast` to `path`.
29pub fn write_dot(tenv: &TyEnv, path: &str) -> Result<()> {
30    let out = render(tenv)?;
31    std::fs::write(path, out).with_context(|| format!("failed to write DOT file: {path}"))
32}
33
34/// Render the Graphviz DOT representation of `rast` as a string.
35///
36/// Pure: no I/O. `write_dot` is this plus one `fs::write`; the benchmark
37/// times this function so file-system noise stays out of its samples (#358).
38#[allow(clippy::too_many_lines)]
39pub fn render(tenv: &TyEnv) -> Result<String> {
40    let mut out = String::new();
41    let pd_name = |pd| tenv.pds[pd].name.as_str();
42
43    let mut pd_rows: HashMap<&str, Vec<Row>> = HashMap::new();
44    for m in tenv.mappings.iter() {
45        pd_rows.entry(pd_name(m.pd)).or_default().push(Row {
46            region: tenv.mrs[m.region].name.as_str(),
47            vaddr: Some(m.vaddr),
48            perms: m.perms.as_str(),
49        });
50    }
51
52    // Build a map of mr_name -> size (bytes) for vaddr range display
53    let mr_sizes: HashMap<&str, u64> = tenv
54        .mrs
55        .iter()
56        .map(|mr| (mr.name.as_str(), mr.size.value()))
57        .collect();
58
59    writeln!(out, "digraph rawast {{")?;
60    writeln!(out, "    rankdir=LR;")?;
61    writeln!(
62        out,
63        "    graph [fontname=\"Helvetica\", splines=line, ranksep=1.5, nodesep=0.6];"
64    )?;
65    writeln!(out, "    node  [fontname=\"Helvetica\", fontsize=11];")?;
66    writeln!(out, "    edge  [fontname=\"Helvetica\", fontsize=9];")?;
67    writeln!(out)?;
68
69    // PD names for rank alignment, in declaration order.
70    let pd_names: Vec<&str> = tenv.pds.iter().map(|pd| pd.name.as_str()).collect();
71
72    // Protection domain nodes — HTML table showing virtual address space layout
73    writeln!(out, "    // Protection Domains (virtual address space)")?;
74    for pd in tenv.pds.iter() {
75        // Sort rows descending by vaddr (highest at top, like a memory diagram)
76        let mut sorted: Vec<&Row> = pd_rows
77            .get(pd.name.as_str())
78            .map(|rows| rows.iter().collect())
79            .unwrap_or_default();
80        sorted.sort_by_key(|r| std::cmp::Reverse(r.vaddr));
81
82        writeln!(out, "    // PD: {}", pd.name)?;
83        write!(
84            out,
85            "    {:?} [shape=plain, label=<\
86                 <TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\">",
87            pd.name
88        )?;
89
90        // Header row (spans both columns)
91        write!(
92            out,
93            "<TR><TD COLSPAN=\"2\" BGCOLOR=\"#4a90d9\" ALIGN=\"CENTER\" CELLPADDING=\"4\">\
94                 <FONT COLOR=\"white\"><B>{}</B>  pri={}</FONT></TD></TR>",
95            pd.name, pd.priority
96        )?;
97
98        // Memory-map style: boundary rows interleaved with content rows.
99        // Left col = address label; right col = region box.
100        // Layout per region (sorted high→low):
101        //   boundary row  (end vaddr)
102        //   content  row  (region name + perms, PORT here)
103        // followed by one final boundary row (start vaddr of lowest region).
104        for (i, row) in sorted.iter().enumerate() {
105            let bgcolor = if i % 2 == 0 { "#eaf4fb" } else { "#d0e8f5" };
106            let port = mapping_port(&pd.name, row.region);
107            let mr_size = mr_sizes.get(row.region).copied().unwrap_or(0);
108
109            // Boundary line: address = vaddr + size (top of this region)
110            let top_addr = row.vaddr.map(|v| format!("{:#x}", v + mr_size));
111            let top_label = top_addr.as_deref().unwrap_or("");
112            write!(
113                out,
114                "<TR>\
115                     <TD ALIGN=\"RIGHT\" VALIGN=\"BOTTOM\" CELLPADDING=\"1\">\
116                     <FONT COLOR=\"#555555\" POINT-SIZE=\"8\">{top_label}</FONT></TD>\
117                     <TD BORDER=\"1\" SIDES=\"T\" WIDTH=\"120\" CELLPADDING=\"0\"></TD>\
118                     </TR>"
119            )?;
120
121            // Content row: region name inside the coloured box
122            write!(
123                out,
124                "<TR>\
125                     <TD WIDTH=\"60\"></TD>\
126                     <TD PORT=\"{port}\" BGCOLOR=\"{bgcolor}\" ALIGN=\"LEFT\" CELLPADDING=\"4\">\
127                     <B>{}</B></TD>\
128                     </TR>",
129                row.region,
130            )?;
131        }
132
133        // Final boundary row: vaddr of the lowest mapping
134        if let Some(last) = sorted.last() {
135            let bottom = last.vaddr.map(|v| format!("{v:#x}"));
136            let bottom_label = bottom.as_deref().unwrap_or("");
137            write!(
138                out,
139                "<TR>\
140                     <TD ALIGN=\"RIGHT\" VALIGN=\"TOP\" CELLPADDING=\"1\">\
141                     <FONT COLOR=\"#555555\" POINT-SIZE=\"8\">{bottom_label}</FONT></TD>\
142                     <TD BORDER=\"1\" SIDES=\"T\" CELLPADDING=\"0\"></TD>\
143                     </TR>"
144            )?;
145        }
146
147        writeln!(out, "</TABLE>>];")?;
148    }
149
150    // Keep all PDs in the same rank (one vertical column on the left).
151    // constraint=false on channel edges (below) stops those edges from
152    // interfering with this rank assignment.
153    if !pd_names.is_empty() {
154        let names_str = pd_names
155            .iter()
156            .map(|n| format!("{n:?}"))
157            .collect::<Vec<_>>()
158            .join("; ");
159        writeln!(out, "    {{ rank=same; {names_str}; }}")?;
160    }
161    writeln!(out)?;
162
163    // Memory region nodes — grouped in a cluster so they form one vertical column
164    writeln!(out, "    // Memory Regions (physical memory column)")?;
165    writeln!(out, "    subgraph cluster_memory {{")?;
166    writeln!(
167        out,
168        "        label=\"Physical Memory\"; style=filled; fillcolor=\"#f9f9f9\";\
169         \n        color=\"#aaaaaa\"; fontname=\"Helvetica\"; fontsize=12;"
170    )?;
171
172    for mr in tenv.mrs.iter() {
173        let size_str = fmt_bytes(mr.size.value());
174        let phys = mr
175            .phys_addr
176            .map_or(String::new(), |a| format!("<BR/>@ {a:#x}"));
177        writeln!(
178            out,
179            "        {:?} [shape=box, style=filled, fillcolor=\"#fffacd\", \
180             label=<\
181             <TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"2\">\
182             <TR><TD><B>{}</B></TD></TR>\
183             <TR><TD>{}{}</TD></TR>\
184             <TR><TD><FONT COLOR=\"#888888\">[{}]</FONT></TD></TR>\
185             </TABLE>>];",
186            mr.name, mr.name, size_str, phys, mr.security_label,
187        )?;
188    }
189
190    writeln!(out, "    }}")?;
191    writeln!(out)?;
192
193    // Channel edges — solid, between PD nodes, direction from ChannelKind
194    writeln!(out, "    // Channels")?;
195    for ch in tenv.chans.iter() {
196        let (dir, suffix) = match ch.kind {
197            ChannelKind::AsyncBi => ("both", ""),
198            ChannelKind::AsyncUni => ("forward", ""),
199            ChannelKind::SyncUni => ("forward", " [pp]"),
200        };
201        writeln!(
202            out,
203            "    {:?} -> {:?} [xlabel=\"{}{}\", style=solid, dir={dir}, \
204             color=\"#333333\", penwidth=1.5, constraint=false];",
205            pd_name(ch.sender.pd),
206            pd_name(ch.receiver.pd),
207            ch.name,
208            suffix,
209        )?;
210    }
211    writeln!(out)?;
212
213    // Mapping edges — dashed, anchored from the specific port row in the PD
214    // table. Covers explicit mappings and channel-buffer regions alike.
215    writeln!(out, "    // Mappings")?;
216    for pd in &pd_names {
217        let Some(rows) = pd_rows.get(pd) else {
218            continue;
219        };
220        for row in rows {
221            let port = mapping_port(pd, row.region);
222            writeln!(
223                out,
224                "    {pd:?}:{port} -> {:?} [style=dashed, color=\"#888888\", arrowsize=0.7, \
225                 xlabel=\"{}\", fontcolor=\"#666666\", fontsize=9];",
226                row.region, row.perms,
227            )?;
228        }
229    }
230
231    writeln!(out, "}}")?;
232
233    Ok(out)
234}
235
236/// Generate a stable DOT port name for a PD's mapping to a memory region.
237fn mapping_port(pd_name: &str, mr_name: &str) -> String {
238    format!(
239        "m_{}_{}",
240        pd_name.replace('-', "_"),
241        mr_name.replace('-', "_")
242    )
243}
244
245#[allow(clippy::cast_precision_loss)]
246fn fmt_bytes(n: u64) -> String {
247    if n >= 1_048_576 {
248        format!("{:.1} MB", n as f64 / 1_048_576.0)
249    } else if n >= 1024 {
250        format!("{:.1} KB", n as f64 / 1024.0)
251    } else {
252        format!("{n} B")
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use crate::tast::env::built;
260
261    fn dot(fis: &str) -> String {
262        let (tast, _) = built(fis, &[]).expect("builds");
263        let path = std::env::temp_dir().join(format!("fic_dot_test_{}.dot", fis.len()));
264        let path_str = path.to_str().unwrap();
265        write_dot(&tast.tenv, path_str).unwrap();
266        let out = std::fs::read_to_string(&path).unwrap();
267        std::fs::remove_file(&path).unwrap();
268        out
269    }
270
271    #[test]
272    fn write_dot_renders_pds_and_channel_edges() {
273        let out = dot("ProtectionDomain a(10);\n\
274             ProtectionDomain b(20);\n\
275             Chan ch1 = a <-> b;");
276        assert!(out.contains("\"a\""));
277        assert!(out.contains("\"b\""));
278        assert!(out.contains("\"a\" -> \"b\" [xlabel=\"ch1\""));
279    }
280
281    #[test]
282    fn buffer_region_rows_and_edges_in_both_endpoints() {
283        let out = dot("MemoryRegion ring(0x1000);\n\
284             ProtectionDomain a(10);\n\
285             ProtectionDomain b(20);\n\
286             Chan c = a --> b via ring<byte>;");
287        // Both endpoints show the buffer region in their address space and
288        // a dashed mapping edge to it.
289        assert!(out.contains("\"a\":m_a_ring -> \"ring\""));
290        assert!(out.contains("\"b\":m_b_ring -> \"ring\""));
291    }
292}