Skip to main content

graphity_dot/
dot_writer.rs

1//! The DOT writer - Java's class `DotWriter`.
2
3use std::borrow::Cow;
4use std::fmt;
5use std::io;
6
7use graphity_core::{Graph, NodePartition};
8
9use crate::Attributes;
10use crate::selection::{Selection, TextHook, invalid_argument, is_identifier};
11
12/// The DOT keywords, which Graphviz never reads as an attribute name; compared ignoring case.
13const KEYWORDS: [&str; 6] = ["node", "edge", "graph", "digraph", "subgraph", "strict"];
14
15/// The attributes whose values Graphviz reads as labels, decoding HTML entities.
16const LABEL_ATTRIBUTES: [&str; 4] = ["label", "xlabel", "headlabel", "taillabel"];
17
18/// An attribute hook: adds the attributes of one node or edge - Java's `AttributeHook`.
19type AttributeHook<'a> = Box<dyn Fn(u32, &mut Attributes<'a>) + 'a>;
20
21/// A writer of DOT (the language of Graphviz) that labels and styles a graph with the caller's data by
22/// node ID and edge index.
23///
24/// [`DotWriter::of`] returns a writer for a graph, the methods that configure it return the writer
25/// again, and [`write`](Self::write) or [`write_to_string`](Self::write_to_string) write the text. The
26/// graph holds no data, so labels and attributes come from hooks that receive a node ID or an edge
27/// index and read the caller's arrays. Here, the packages of a small program get their names from
28/// `names`. The strongly connected components `sccs` tell which packages are in a cycle, and these are
29/// drawn in red:
30///
31/// <!-- example: writing_dot.rs#nodeAttributes -->
32/// ```
33/// # use graphity_dot::DotWriter;
34/// # let dependencies = graphity_core::Graph::of(
35/// #     &[0, 3, 4, 7, 9, 10, 13, 14, 14],
36/// #     &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
37/// # ).unwrap();
38/// # let names: &[&str] = &["app", "cli", "ui", "service", "model", "storage", "json", "util"];
39/// # let sccs = graphity_core::components::sccs_of(&dependencies);
40/// let dot = DotWriter::of(&dependencies)
41///     .node_label(|node| Some(names[node as usize].into()))
42///     .node_attributes(|node, attributes| {
43///         if sccs.contains_cycle(sccs.scc_of(node)) {
44///             attributes.insert("color", "red");
45///         }
46///     })
47///     .write_to_string();
48/// // model and storage, the cycle, in red:
49/// //   4 [label="model", color="red"];
50/// //   5 [label="storage", color="red"];
51/// # assert!(dot.contains("  4 [label=\"model\", color=\"red\"];\n  5 [label=\"storage\", color=\"red\"];\n"));
52/// # assert_eq!(dot.matches("red").count(), 2);
53/// ```
54///
55/// Nodes are named by their node IDs. The text lists the graph attributes, the clusters in group
56/// order with their nodes, then the nodes in no cluster, then the edges in edge index order, so the
57/// same graph and hooks always give the same text. A node outside the clusters is listed only if it
58/// has a label or attributes, or no edge in the text; Graphviz creates the other nodes from their
59/// edges.
60///
61/// Labels and attribute values are written as quoted strings: the writer escapes quotes and
62/// backslashes and turns line breaks into DOT's `\n`. Graphviz decodes HTML entities such as `&lt;` in
63/// the attributes `label`, `xlabel`, `headlabel` and `taillabel`. In these, the writer also turns `&`
64/// into `&amp;`, so that a label shows exactly its text. Other values, such as a `URL`, keep their
65/// `&`. NUL, which DOT cannot hold, is written as U+FFFD.
66///
67/// Attribute names must be identifiers - an ASCII letter or underscore, then ASCII letters, digits or
68/// underscores - other than the DOT keywords `node`, `edge`, `graph`, `digraph`, `subgraph` and
69/// `strict`, in any letter case.
70///
71/// The label hooks return a [`Cow`]: a `&str` into the caller's data, which lives for the writer's
72/// lifetime `'a`, is written without a copy (`Some(names[node as usize].as_str().into())`), and a
73/// computed text is a `String` (`Some(format!("v{node}").into())`). `None` is Java's `null`.
74///
75/// A writer keeps its configuration and can write any number of times. The graph, the partition and
76/// the data the hooks read are borrowed for its lifetime `'a`. The hooks are `Fn` closures, called
77/// from [`write`](Self::write) through `&self`; a hook that counts its calls needs a
78/// [`Cell`](std::cell::Cell). For Markdown and documentation, `MermaidWriter` in the crate
79/// `graphity-mermaid` writes a Mermaid flowchart.
80///
81/// Since the hooks are arbitrary closures, the writer is neither `Send` nor `Sync` - Java's instances
82/// are not safe to share between threads either.
83pub struct DotWriter<'a> {
84    selection: Selection<'a>,
85    graph_attributes: Attributes<'a>,
86    node_label: Option<TextHook<'a>>,
87    edge_label: Option<TextHook<'a>>,
88    node_attributes: Option<AttributeHook<'a>>,
89    edge_attributes: Option<AttributeHook<'a>>,
90}
91
92impl<'a> DotWriter<'a> {
93    /// Returns a writer for `graph`, with no labels, attributes, clusters or filter yet. The graph of a
94    /// [`BiAdjacentGraph`](graphity_core::BiAdjacentGraph) is accepted as well, as a `&Graph`.
95    ///
96    /// **Time:** O(1).
97    pub fn of(graph: &'a Graph) -> Self {
98        Self {
99            selection: Selection::new(graph),
100            graph_attributes: Attributes::new(),
101            node_label: None,
102            edge_label: None,
103            node_attributes: None,
104            edge_attributes: None,
105        }
106    }
107
108    /// Sets an attribute of the graph, such as `rankdir` to `LR`.
109    ///
110    /// **Time:** O(number of graph attributes), as the attributes are a vector of pairs, which for the
111    /// handful of attributes of a graph beats hashing.
112    ///
113    /// # Panics
114    /// With an `invalid argument` message if `name` is not an identifier or is a DOT keyword.
115    #[must_use]
116    #[track_caller]
117    pub fn graph_attribute(
118        mut self,
119        name: impl Into<Cow<'a, str>>,
120        value: impl Into<Cow<'a, str>>,
121    ) -> Self {
122        let name = name.into();
123        check_name(&name);
124        self.graph_attributes.insert(name, value);
125        self
126    }
127
128    /// Sets the label of each node, by node ID; `None` leaves a node unlabeled, and Graphviz then shows
129    /// its node ID. `label` is called with a node ID and returns the label of the node or `None`.
130    ///
131    /// **Time:** O(1).
132    #[must_use]
133    pub fn node_label(mut self, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a) -> Self {
134        self.node_label = Some(Box::new(label));
135        self
136    }
137
138    /// Sets the label of each edge, by edge index; `None` leaves an edge unlabeled. `label` is called with
139    /// an edge index and returns the label of the edge or `None`.
140    ///
141    /// **Time:** O(1).
142    #[must_use]
143    pub fn edge_label(mut self, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a) -> Self {
144        self.edge_label = Some(Box::new(label));
145        self
146    }
147
148    /// Sets the hook that adds DOT attributes, such as `shape`, `color` or `style`, to each node, by node
149    /// ID - Java's `AttributeHook` is a closure here, and its map an [`Attributes`].
150    ///
151    /// The hook receives the label from [`node_label`](Self::node_label) as the attribute `label`, which
152    /// it can replace or remove. `hook` is called with each node that is written and puts its attributes.
153    ///
154    /// **Time:** O(1).
155    #[must_use]
156    pub fn node_attributes(mut self, hook: impl Fn(u32, &mut Attributes<'a>) + 'a) -> Self {
157        self.node_attributes = Some(Box::new(hook));
158        self
159    }
160
161    /// Sets the hook that adds DOT attributes, such as `color` or `style`, to each edge, by edge index.
162    ///
163    /// The hook receives the label from [`edge_label`](Self::edge_label) as the attribute `label`, which
164    /// it can replace or remove. `hook` is called with each edge that is written and puts its attributes.
165    ///
166    /// **Time:** O(1).
167    #[must_use]
168    pub fn edge_attributes(mut self, hook: impl Fn(u32, &mut Attributes<'a>) + 'a) -> Self {
169        self.edge_attributes = Some(Box::new(hook));
170        self
171    }
172
173    /// Draws each group of `partition` as a cluster, with a label by group ID. `label` is called with a
174    /// group ID and returns the label of its cluster or `None`.
175    ///
176    /// Nodes in no group stay outside every cluster, and a group without a node to write has no cluster.
177    /// A label of `None` leaves a cluster unlabeled, also when the graph has a `label`, which Graphviz
178    /// would otherwise repeat on every cluster. An [`Sccs`](graphity_core::Sccs) is accepted as well, as
179    /// a `&NodePartition`.
180    ///
181    /// **Time:** O(1).
182    ///
183    /// # Panics
184    /// With an `invalid argument` message if `partition` has a different node count than the graph.
185    #[must_use]
186    #[track_caller]
187    pub fn clusters(
188        mut self,
189        partition: &'a NodePartition,
190        label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a,
191    ) -> Self {
192        self.selection.set_clusters(partition, Box::new(label));
193        self
194    }
195
196    /// Restricts the text to the nodes that `include` accepts and the edges between them.
197    ///
198    /// Node IDs stay those of the graph, so the hooks keep reading the same arrays.
199    ///
200    /// **Time:** O(1).
201    #[must_use]
202    pub fn node_filter(mut self, include: impl Fn(u32) -> bool + 'a) -> Self {
203        self.selection.node_filter = Some(Box::new(include));
204        self
205    }
206
207    /// Switches to the undirected reading of the graph: a `graph` with `--` edges instead of a `digraph`.
208    ///
209    /// The edges `a -> b` and `b -> a` become one, written as the edge from the lower node ID; the edge
210    /// hooks receive its edge index.
211    ///
212    /// **Time:** O(1).
213    #[must_use]
214    pub fn undirected(mut self) -> Self {
215        self.selection.undirected = true;
216        self
217    }
218
219    /// Writes the graph to `out`, as DOT text.
220    ///
221    /// `out` is any [`io::Write`], such as a file, standard output, a socket or a `Vec<u8>`, and receives
222    /// the text in UTF-8; Java takes an `Appendable`. It is taken by value: lend it with `&mut out` to
223    /// keep using it, and flush it yourself; this call neither flushes nor closes it. Passed by value, it
224    /// is dropped when the call returns, which closes a [`File`](std::fs::File) and flushes a
225    /// [`BufWriter`](std::io::BufWriter) without reporting an error. The writer issues many small writes,
226    /// so an unbuffered `out` such as a `File` is best wrapped in a `BufWriter`, lent with `&mut` and
227    /// flushed afterwards.
228    ///
229    /// **Time:** O(node_count + edge_count + group_count), plus the hooks, with group_count the number of
230    /// groups of the partition drawn as clusters; in the undirected reading, O(log out_degree(target))
231    /// more per edge.
232    /// **Memory:** node_count bytes while it runs.
233    ///
234    /// # Errors
235    /// The first error of `out` - Java's `IOException`.
236    ///
237    /// # Panics
238    /// With an `invalid argument` message if an attribute hook puts a name that is not an identifier or
239    /// is a DOT keyword; what was written before stays in `out`.
240    pub fn write<W: io::Write>(&self, mut out: W) -> io::Result<()> {
241        let selection = &self.selection;
242        let n = selection.graph.node_count();
243        let arrow = if selection.undirected { " -- " } else { " -> " };
244        out.write_all(if selection.undirected {
245            b"graph {\n"
246        } else {
247            b"digraph {\n"
248        })?;
249        for (name, value) in &self.graph_attributes {
250            write!(out, "  {name}=")?;
251            quote(value, is_label_attribute(name), &mut out)?;
252            out.write_all(b";\n")?;
253        }
254        let graph_labeled = self.graph_attributes.contains_key("label");
255
256        let mut has_edge = vec![false; n as usize];
257        selection.for_each_written_edge(|source, target, _| {
258            has_edge[source as usize] = true;
259            has_edge[target as usize] = true;
260            Ok::<(), io::Error>(())
261        })?;
262
263        let mut attributes = Attributes::new();
264        if let Some(clusters) = &selection.clusters {
265            let partition = clusters.partition;
266            for group in 0..partition.group_count() {
267                let mut opened = false;
268                for &node in partition.nodes_of(group).iter() {
269                    if !selection.is_included(node) {
270                        continue;
271                    }
272                    if !opened {
273                        writeln!(out, "  subgraph cluster_{group} {{")?;
274                        if let Some(label) = (clusters.label)(group) {
275                            out.write_all(b"    label=")?;
276                            quote(&label, true, &mut out)?;
277                            out.write_all(b";\n")?;
278                        } else if graph_labeled {
279                            out.write_all(b"    label=\"\";\n")?;
280                        }
281                        opened = true;
282                    }
283                    self.put_node_attributes(node, &mut attributes);
284                    write_node(node, &attributes, "    ", &mut out)?;
285                }
286                if opened {
287                    out.write_all(b"  }\n")?;
288                }
289            }
290        }
291        for node in 0..n {
292            if !selection.is_included(node) || selection.cluster_of(node).is_some() {
293                continue;
294            }
295            self.put_node_attributes(node, &mut attributes);
296            if !attributes.is_empty() || !has_edge[node as usize] {
297                write_node(node, &attributes, "  ", &mut out)?;
298            }
299        }
300        selection.for_each_written_edge(|source, target, edge_index| {
301            write!(out, "  {source}{arrow}{target}")?;
302            self.put_edge_attributes(edge_index, &mut attributes);
303            write_attributes(&attributes, &mut out)?;
304            out.write_all(b";\n")
305        })?;
306        out.write_all(b"}\n")
307    }
308
309    /// Returns the DOT text of the graph, as [`write`](Self::write) writes it.
310    ///
311    /// **Time:** as for [`write`](Self::write).
312    /// **Memory:** the text for the result, whose buffer may hold up to as much again in spare capacity;
313    /// while it runs, node_count bytes more.
314    ///
315    /// # Panics
316    /// As for [`write`](Self::write).
317    pub fn write_to_string(&self) -> String {
318        let mut text = Vec::new();
319        self.write(&mut text)
320            .expect("writing to a Vec<u8> does not fail");
321        String::from_utf8(text).expect("the writer writes UTF-8")
322    }
323
324    fn put_node_attributes(&self, node: u32, attributes: &mut Attributes<'a>) {
325        attributes.clear();
326        if let Some(label) = self.node_label.as_ref().and_then(|label| label(node)) {
327            attributes.insert("label", label);
328        }
329        if let Some(hook) = &self.node_attributes {
330            hook(node, attributes);
331        }
332    }
333
334    fn put_edge_attributes(&self, edge_index: u32, attributes: &mut Attributes<'a>) {
335        attributes.clear();
336        if let Some(label) = self.edge_label.as_ref().and_then(|label| label(edge_index)) {
337            attributes.insert("label", label);
338        }
339        if let Some(hook) = &self.edge_attributes {
340            hook(edge_index, attributes);
341        }
342    }
343}
344
345impl fmt::Debug for DotWriter<'_> {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        f.debug_struct("DotWriter")
348            .field("graph", self.selection.graph)
349            .field("graph_attributes", &self.graph_attributes)
350            .field("undirected", &self.selection.undirected)
351            .finish_non_exhaustive()
352    }
353}
354
355fn write_node<W: io::Write>(
356    node: u32,
357    attributes: &Attributes<'_>,
358    indent: &str,
359    out: &mut W,
360) -> io::Result<()> {
361    write!(out, "{indent}{node}")?;
362    write_attributes(attributes, out)?;
363    out.write_all(b";\n")
364}
365
366/// Writes ` [name="value", ...]`, nothing for no attributes, checking each name before writing it.
367fn write_attributes<W: io::Write>(attributes: &Attributes<'_>, out: &mut W) -> io::Result<()> {
368    let mut first = true;
369    for (name, value) in attributes {
370        let name = check_name(name);
371        out.write_all(if first { b" [" } else { b", " })?;
372        out.write_all(name.as_bytes())?;
373        out.write_all(b"=")?;
374        quote(value, is_label_attribute(name), out)?;
375        first = false;
376    }
377    if !first {
378        out.write_all(b"]")?;
379    }
380    Ok(())
381}
382
383fn is_label_attribute(name: &str) -> bool {
384    LABEL_ATTRIBUTES.contains(&name)
385}
386
387/// Returns `name` if it is an identifier other than a DOT keyword in any case.
388///
389/// # Panics
390/// With an `invalid argument` message otherwise.
391#[track_caller]
392fn check_name(name: &str) -> &str {
393    if !is_identifier(name)
394        || KEYWORDS
395            .iter()
396            .any(|keyword| keyword.eq_ignore_ascii_case(name))
397    {
398        invalid_argument(format_args!("not a DOT attribute name: {name}"));
399    }
400    name
401}
402
403/// Writes `text` as a DOT quoted string that shows exactly that text, NUL aside, which DOT cannot
404/// hold. For an attribute in which Graphviz decodes HTML entities, the labels, `decodes_entities`
405/// turns `&` into `&amp;`.
406fn quote<W: io::Write>(text: &str, decodes_entities: bool, out: &mut W) -> io::Result<()> {
407    out.write_all(b"\"")?;
408    // Every character the writer replaces is ASCII, so a byte never matches inside a multi-byte
409    // character, and the runs between replacements are written as they are.
410    let bytes = text.as_bytes();
411    let mut plain = 0;
412    for (i, &c) in bytes.iter().enumerate() {
413        let replacement: &[u8] = match c {
414            b'"' => b"\\\"",
415            b'\\' => b"\\\\",
416            b'\n' => b"\\n",
417            b'\r' if bytes.get(i + 1) == Some(&b'\n') => b"",
418            b'\r' => b"\\n",
419            b'&' if decodes_entities => b"&amp;",
420            b'\0' => "\u{FFFD}".as_bytes(),
421            _ => continue,
422        };
423        out.write_all(&bytes[plain..i])?;
424        out.write_all(replacement)?;
425        plain = i + 1;
426    }
427    out.write_all(&bytes[plain..])?;
428    out.write_all(b"\"")
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    fn quoted(text: &str, label: bool) -> String {
436        let mut out = Vec::new();
437        quote(text, label, &mut out).unwrap();
438        String::from_utf8(out).unwrap()
439    }
440
441    #[test]
442    fn quote_escapes_exactly_the_special_characters() {
443        assert_eq!(quoted("", false), "\"\"");
444        assert_eq!(quoted("plain", true), "\"plain\"");
445        assert_eq!(quoted("a\"b\\c", false), "\"a\\\"b\\\\c\"");
446        assert_eq!(quoted("a\nb\rc\r\nd\r", false), "\"a\\nb\\nc\\nd\\n\"");
447        assert_eq!(quoted("\r\r\n\n", false), "\"\\n\\n\\n\"");
448        assert_eq!(quoted("&a&", true), "\"&amp;a&amp;\"");
449        assert_eq!(quoted("&a&", false), "\"&a&\"");
450        assert_eq!(quoted("\0x\0", false), "\"\u{FFFD}x\u{FFFD}\"");
451        // Characters outside ASCII and outside the BMP pass through, as Java's UTF-16 units do.
452        assert_eq!(quoted("é\u{1F600}\"ü", true), "\"é\u{1F600}\\\"ü\"");
453        assert_eq!(quoted("<b>\t'x'", true), "\"<b>\t'x'\"");
454    }
455
456    #[test]
457    fn names_are_identifiers_other_than_keywords_in_any_case() {
458        for name in ["rankdir", "URL", "_x", "label", "nodes", "Graph1", "edge_"] {
459            assert_eq!(check_name(name), name);
460        }
461        for name in [
462            "node", "NODE", "Edge", "graph", "gRaPh", "digraph", "subgraph", "Strict", "a-b", "",
463            "1a",
464        ] {
465            let result = std::panic::catch_unwind(|| check_name(name));
466            assert!(result.is_err(), "{name}");
467        }
468    }
469
470    #[test]
471    fn label_attributes_are_compared_with_case() {
472        for name in LABEL_ATTRIBUTES {
473            assert!(is_label_attribute(name));
474        }
475        assert!(!is_label_attribute("Label") && !is_label_attribute("URL"));
476    }
477}