1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#![warn(missing_docs)]

use std::borrow::Cow;
use std::error::Error;

use auto_impl::auto_impl;
use slotmap::Key;

use super::ops::DelayType;
use super::{Color, GraphNodeId, GraphSubgraphId};

/// Trait for writing textual representations of graphs, i.e. mermaid or dot graphs.
#[auto_impl(&mut, Box)]
pub(crate) trait GraphWrite {
    /// Error type emitted by writing.
    type Err: Error;

    /// Begin the graph. First method called.
    fn write_prologue(&mut self) -> Result<(), Self::Err>;

    /// Write a node, with styling.
    fn write_node(
        &mut self,
        node_id: GraphNodeId,
        node: &str,
        node_color: Option<Color>,
    ) -> Result<(), Self::Err>;

    /// Write an edge, with styling.
    fn write_edge(
        &mut self,
        src_id: GraphNodeId,
        dst_id: GraphNodeId,
        delay_type: Option<DelayType>,
        label: Option<&str>,
        is_reference: bool,
    ) -> Result<(), Self::Err>;

    /// Begin writing a subgraph.
    fn write_subgraph_start(
        &mut self,
        sg_id: GraphSubgraphId,
        stratum: usize,
        subgraph_nodes: impl Iterator<Item = GraphNodeId>,
    ) -> Result<(), Self::Err>;
    /// Write the nodes associated with a single variable name, within a subgraph.
    fn write_varname(
        &mut self,
        varname: &str,
        varname_nodes: impl Iterator<Item = GraphNodeId>,
        sg_id: Option<GraphSubgraphId>,
    ) -> Result<(), Self::Err>;
    /// End writing a subgraph.
    fn write_subgraph_end(&mut self) -> Result<(), Self::Err>;

    /// End the graph. Last method called.
    fn write_epilogue(&mut self) -> Result<(), Self::Err>;
}

/// Escapes a string for use in a mermaid graph label.
pub fn escape_mermaid(string: &str) -> String {
    string
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        // Mermaid entity codes
        // https://mermaid.js.org/syntax/flowchart.html#entity-codes-to-escape-characters
        .replace('#', "&num;")
        // Not really needed, newline literals seem to work
        .replace('\n', "<br>")
        // Mermaid font awesome fa
        // https://github.com/mermaid-js/mermaid/blob/e4d2118d4bfa023628a020b7ab1f8c491e6dc523/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js#L62
        .replace("fa:fa", "fa:<wbr>fa")
        .replace("fab:fa", "fab:<wbr>fa")
        .replace("fal:fa", "fal:<wbr>fa")
        .replace("far:fa", "far:<wbr>fa")
        .replace("fas:fa", "fas:<wbr>fa")
}

pub struct Mermaid<W> {
    write: W,
    // How many links have been written, for styling
    // https://mermaid.js.org/syntax/flowchart.html#styling-links
    link_count: usize,
}
impl<W> Mermaid<W> {
    pub fn new(write: W) -> Self {
        Self {
            write,
            link_count: 0,
        }
    }
}
impl<W> GraphWrite for Mermaid<W>
where
    W: std::fmt::Write,
{
    type Err = std::fmt::Error;

    fn write_prologue(&mut self) -> Result<(), Self::Err> {
        writeln!(
            self.write,
            r"%%{{init:{{'theme':'base','themeVariables':{{'clusterBkg':'#ddd','clusterBorder':'#888'}}}}}}%%",
        )?;
        writeln!(self.write, "flowchart TD")?;
        writeln!(
            self.write,
            "classDef pullClass fill:#8af,stroke:#000,text-align:left,white-space:pre",
        )?;
        writeln!(
            self.write,
            "classDef pushClass fill:#ff8,stroke:#000,text-align:left,white-space:pre",
        )?;
        writeln!(
            self.write,
            "classDef otherClass fill:#fdc,stroke:#000,text-align:left,white-space:pre",
        )?;

        writeln!(self.write, "linkStyle default stroke:#aaa")?;
        Ok(())
    }

    fn write_node(
        &mut self,
        node_id: GraphNodeId,
        node: &str,
        node_color: Option<Color>,
    ) -> Result<(), Self::Err> {
        let class_str = match node_color {
            Some(Color::Push) => "pushClass",
            Some(Color::Pull) => "pullClass",
            _ => "otherClass",
        };
        let label = format!(
            r#"{node_id:?}{lbracket}"{node_label} <code>{code}</code>"{rbracket}:::{class}"#,
            node_id = node_id.data(),
            node_label = if node.contains('\n') {
                format!("<div style=text-align:center>({:?})</div>", node_id.data())
            } else {
                format!("({:?})", node_id.data())
            },
            class = class_str,
            lbracket = match node_color {
                Some(Color::Push) => r"[/",
                Some(Color::Pull) => r"[\",
                _ => "[",
            },
            code = escape_mermaid(node),
            rbracket = match node_color {
                Some(Color::Push) => r"\]",
                Some(Color::Pull) => r"/]",
                _ => "]",
            },
        );
        writeln!(self.write, "{}", label)?;
        Ok(())
    }

    fn write_edge(
        &mut self,
        src_id: GraphNodeId,
        dst_id: GraphNodeId,
        delay_type: Option<DelayType>,
        label: Option<&str>,
        _is_reference: bool,
    ) -> Result<(), Self::Err> {
        let src_str = format!("{:?}", src_id.data());
        let dest_str = format!("{:?}", dst_id.data());
        #[expect(clippy::write_literal, reason = "code readability")]
        write!(
            self.write,
            "{src}{arrow_body}{arrow_head}{label}{dst}",
            src = src_str.trim(),
            arrow_body = "--",
            arrow_head = match delay_type {
                None | Some(DelayType::MonotoneAccum) => ">",
                Some(DelayType::Stratum) => "x",
                Some(DelayType::Tick | DelayType::TickLazy) => "o",
            },
            label = if let Some(label) = &label {
                Cow::Owned(format!("|{}|", escape_mermaid(label.trim())))
            } else {
                Cow::Borrowed("")
            },
            dst = dest_str.trim(),
        )?;
        if let Some(delay_type) = delay_type {
            write!(
                self.write,
                "; linkStyle {} stroke:{}",
                self.link_count,
                match delay_type {
                    DelayType::Stratum | DelayType::Tick | DelayType::TickLazy => "red",
                    DelayType::MonotoneAccum => "#060",
                }
            )?;
        }
        writeln!(self.write)?;
        self.link_count += 1;
        Ok(())
    }

    fn write_subgraph_start(
        &mut self,
        sg_id: GraphSubgraphId,
        stratum: usize,
        subgraph_nodes: impl Iterator<Item = GraphNodeId>,
    ) -> Result<(), Self::Err> {
        writeln!(
            self.write,
            "subgraph sg_{sg:?} [\"sg_{sg:?} stratum {:?}\"]",
            stratum,
            sg = sg_id.data(),
        )?;
        for node_id in subgraph_nodes {
            writeln!(self.write, "    {node_id:?}", node_id = node_id.data())?;
        }
        Ok(())
    }

    fn write_varname(
        &mut self,
        varname: &str,
        varname_nodes: impl Iterator<Item = GraphNodeId>,
        sg_id: Option<GraphSubgraphId>,
    ) -> Result<(), Self::Err> {
        let pad = if let Some(sg_id) = sg_id {
            writeln!(
                self.write,
                "    subgraph sg_{sg:?}_var_{var} [\"var <tt>{var}</tt>\"]",
                sg = sg_id.data(),
                var = varname,
            )?;
            "    "
        } else {
            writeln!(
                self.write,
                "subgraph var_{0} [\"var <tt>{0}</tt>\"]",
                varname,
            )?;
            writeln!(self.write, "style var_{} fill:transparent", varname)?;
            ""
        };
        for local_named_node in varname_nodes {
            writeln!(self.write, "    {}{:?}", pad, local_named_node.data())?;
        }
        writeln!(self.write, "{}end", pad)?;
        Ok(())
    }

    fn write_subgraph_end(&mut self) -> Result<(), Self::Err> {
        writeln!(self.write, "end")?;
        Ok(())
    }

    fn write_epilogue(&mut self) -> Result<(), Self::Err> {
        // No-op.
        Ok(())
    }
}

/// Escapes a string for use in a DOT graph label.
///
/// Newline can be:
/// * "\\n" for newline.
/// * "\\l" for left-aligned newline.
/// * "\\r" for right-aligned newline.
pub fn escape_dot(string: &str, newline: &str) -> String {
    string.replace('"', "\\\"").replace('\n', newline)
}

pub struct Dot<W> {
    write: W,
}
impl<W> Dot<W> {
    pub fn new(write: W) -> Self {
        Self { write }
    }
}
impl<W> GraphWrite for Dot<W>
where
    W: std::fmt::Write,
{
    type Err = std::fmt::Error;

    fn write_prologue(&mut self) -> Result<(), Self::Err> {
        writeln!(self.write, "digraph {{")?;
        const FONTS: &str = "\"Monaco,Menlo,Consolas,&quot;Droid Sans Mono&quot;,Inconsolata,&quot;Courier New&quot;,monospace\"";
        writeln!(self.write, "    node [fontname={}, style=filled];", FONTS)?;
        writeln!(self.write, "    edge [fontname={}];", FONTS)?;
        Ok(())
    }

    fn write_node(
        &mut self,
        node_id: GraphNodeId,
        node: &str,
        node_color: Option<Color>,
    ) -> Result<(), Self::Err> {
        let nm = escape_dot(node, "\\l");
        let label = format!("n{:?}", node_id.data());
        let shape_str = match node_color {
            Some(Color::Push) => "house",
            Some(Color::Pull) => "invhouse",
            Some(Color::Hoff) => "parallelogram",
            Some(Color::Comp) => "circle",
            None => "rectangle",
        };
        let color_str = match node_color {
            Some(Color::Push) => "\"#ffff88\"",
            Some(Color::Pull) => "\"#88aaff\"",
            Some(Color::Hoff) => "\"#ddddff\"",
            Some(Color::Comp) => "white",
            None => "\"#ddddff\"",
        };
        write!(
            self.write,
            "    {} [label=\"({}) {}{}\"",
            label,
            label,
            nm,
            // if contains linebreak left-justify by appending another "\\l"
            if nm.contains("\\l") { "\\l" } else { "" },
        )?;
        write!(self.write, ", shape={}, fillcolor={}", shape_str, color_str)?;
        writeln!(self.write, "]")?;
        Ok(())
    }

    fn write_edge(
        &mut self,
        src_id: GraphNodeId,
        dst_id: GraphNodeId,
        delay_type: Option<DelayType>,
        label: Option<&str>,
        _is_reference: bool,
    ) -> Result<(), Self::Err> {
        let mut properties = Vec::<Cow<'static, str>>::new();
        if let Some(label) = label {
            properties.push(format!("label=\"{}\"", escape_dot(label, "\\n")).into());
        };
        // Color
        if delay_type.is_some() {
            properties.push("color=red".into());
        }

        write!(
            self.write,
            "    n{:?} -> n{:?}",
            src_id.data(),
            dst_id.data(),
        )?;
        if !properties.is_empty() {
            write!(self.write, " [")?;
            for prop in itertools::Itertools::intersperse(properties.into_iter(), ", ".into()) {
                write!(self.write, "{}", prop)?;
            }
            write!(self.write, "]")?;
        }
        writeln!(self.write)?;
        Ok(())
    }

    fn write_subgraph_start(
        &mut self,
        sg_id: GraphSubgraphId,
        stratum: usize,
        subgraph_nodes: impl Iterator<Item = GraphNodeId>,
    ) -> Result<(), Self::Err> {
        writeln!(
            self.write,
            "    subgraph \"cluster n{:?}\" {{",
            sg_id.data(),
        )?;
        writeln!(self.write, "        fillcolor=\"#dddddd\"")?;
        writeln!(self.write, "        style=filled")?;
        writeln!(
            self.write,
            "        label = \"sg_{:?}\\nstratum {}\"",
            sg_id.data(),
            stratum,
        )?;
        for node_id in subgraph_nodes {
            writeln!(self.write, "        n{:?}", node_id.data(),)?;
        }
        Ok(())
    }

    fn write_varname(
        &mut self,
        varname: &str,
        varname_nodes: impl Iterator<Item = GraphNodeId>,
        sg_id: Option<GraphSubgraphId>,
    ) -> Result<(), Self::Err> {
        let pad = if let Some(sg_id) = sg_id {
            writeln!(
                self.write,
                "        subgraph \"cluster_sg_{sg:?}_var_{var}\" {{",
                sg = sg_id.data(),
                var = varname,
            )?;
            "    "
        } else {
            writeln!(
                self.write,
                "    subgraph \"cluster_var_{var}\" {{",
                var = varname,
            )?;
            ""
        };
        writeln!(
            self.write,
            "        {}label=\"var {var}\"",
            pad,
            var = varname
        )?;
        for local_named_node in varname_nodes {
            writeln!(self.write, "        {}n{:?}", pad, local_named_node.data())?;
        }
        writeln!(self.write, "    {}}}", pad)?;
        Ok(())
    }

    fn write_subgraph_end(&mut self) -> Result<(), Self::Err> {
        // subgraph footer
        writeln!(self.write, "    }}")?;
        Ok(())
    }

    fn write_epilogue(&mut self) -> Result<(), Self::Err> {
        writeln!(self.write, "}}")?;
        Ok(())
    }
}