1 //! Generate files suitable for use with [Graphviz](https://www.graphviz.org/)
3 //! The `render` function generates output (e.g., an `output.dot` file) for
4 //! use with [Graphviz](https://www.graphviz.org/) by walking a labeled
5 //! graph. (Graphviz can then automatically lay out the nodes and edges
6 //! of the graph, and also optionally render the graph as an image or
7 //! other [output formats](https://www.graphviz.org/docs/outputs), such as SVG.)
9 //! Rather than impose some particular graph data structure on clients,
10 //! this library exposes two traits that clients can implement on their
11 //! own structs before handing them over to the rendering function.
13 //! Note: This library does not yet provide access to the full
14 //! expressiveness of the [DOT language](https://www.graphviz.org/doc/info/lang.html).
15 //! For example, there are many [attributes](https://www.graphviz.org/doc/info/attrs.html)
16 //! related to providing layout hints (e.g., left-to-right versus top-down, which
17 //! algorithm to use, etc). The current intention of this library is to
18 //! emit a human-readable .dot file with very regular structure suitable
19 //! for easy post-processing.
23 //! The first example uses a very simple graph representation: a list of
24 //! pairs of ints, representing the edges (the node set is implicit).
25 //! Each node label is derived directly from the int representing the node,
26 //! while the edge labels are all empty strings.
28 //! This example also illustrates how to use `Cow<[T]>` to return
29 //! an owned vector or a borrowed slice as appropriate: we construct the
30 //! node vector from scratch, but borrow the edge list (rather than
31 //! constructing a copy of all the edges from scratch).
33 //! The output from this example renders five nodes, with the first four
34 //! forming a diamond-shaped acyclic graph and then pointing to the fifth
38 //! #![feature(rustc_private)]
40 //! use std::io::Write;
41 //! use rustc_graphviz as dot;
44 //! type Ed = (isize,isize);
45 //! struct Edges(Vec<Ed>);
47 //! pub fn render_to<W: Write>(output: &mut W) {
48 //! let edges = Edges(vec![(0,1), (0,2), (1,3), (2,3), (3,4), (4,4)]);
49 //! dot::render(&edges, output).unwrap()
52 //! impl<'a> dot::Labeller<'a> for Edges {
55 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
57 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
58 //! dot::Id::new(format!("N{}", *n)).unwrap()
62 //! impl<'a> dot::GraphWalk<'a> for Edges {
65 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
66 //! // (assumes that |N| \approxeq |E|)
67 //! let &Edges(ref v) = self;
68 //! let mut nodes = Vec::with_capacity(v.len());
70 //! nodes.push(s); nodes.push(t);
77 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
78 //! let &Edges(ref edges) = self;
79 //! (&edges[..]).into()
82 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
84 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
87 //! # pub fn main() { render_to(&mut Vec::new()) }
91 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
93 //! use std::fs::File;
94 //! let mut f = File::create("example1.dot").unwrap();
99 //! Output from first example (in `example1.dot`):
102 //! digraph example1 {
108 //! N0 -> N1[label=""];
109 //! N0 -> N2[label=""];
110 //! N1 -> N3[label=""];
111 //! N2 -> N3[label=""];
112 //! N3 -> N4[label=""];
113 //! N4 -> N4[label=""];
117 //! The second example illustrates using `node_label` and `edge_label` to
118 //! add labels to the nodes and edges in the rendered graph. The graph
119 //! here carries both `nodes` (the label text to use for rendering a
120 //! particular node), and `edges` (again a list of `(source,target)`
123 //! This example also illustrates how to use a type (in this case the edge
124 //! type) that shares substructure with the graph: the edge type here is a
125 //! direct reference to the `(source,target)` pair stored in the graph's
126 //! internal vector (rather than passing around a copy of the pair
127 //! itself). Note that this implies that `fn edges(&'a self)` must
128 //! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
129 //! edges stored in `self`.
131 //! Since both the set of nodes and the set of edges are always
132 //! constructed from scratch via iterators, we use the `collect()` method
133 //! from the `Iterator` trait to collect the nodes and edges into freshly
134 //! constructed growable `Vec` values (rather than using `Cow` as in the
135 //! first example above).
137 //! The output from this example renders four nodes that make up the
138 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
139 //! labeled with the ⊆ character (specified using the HTML character
143 //! #![feature(rustc_private)]
145 //! use std::io::Write;
146 //! use rustc_graphviz as dot;
149 //! type Ed<'a> = &'a (usize, usize);
150 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
152 //! pub fn render_to<W: Write>(output: &mut W) {
153 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
154 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
155 //! let graph = Graph { nodes: nodes, edges: edges };
157 //! dot::render(&graph, output).unwrap()
160 //! impl<'a> dot::Labeller<'a> for Graph {
162 //! type Edge = Ed<'a>;
163 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
164 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
165 //! dot::Id::new(format!("N{}", n)).unwrap()
167 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
168 //! dot::LabelText::LabelStr(self.nodes[*n].into())
170 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
171 //! dot::LabelText::LabelStr("⊆".into())
175 //! impl<'a> dot::GraphWalk<'a> for Graph {
177 //! type Edge = Ed<'a>;
178 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
179 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
180 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
181 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
184 //! # pub fn main() { render_to(&mut Vec::new()) }
188 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
190 //! use std::fs::File;
191 //! let mut f = File::create("example2.dot").unwrap();
192 //! render_to(&mut f)
196 //! The third example is similar to the second, except now each node and
197 //! edge now carries a reference to the string label for each node as well
198 //! as that node's index. (This is another illustration of how to share
199 //! structure with the graph itself, and why one might want to do so.)
201 //! The output from this example is the same as the second example: the
202 //! Hasse-diagram for the subsets of the set `{x, y}`.
205 //! #![feature(rustc_private)]
207 //! use std::io::Write;
208 //! use rustc_graphviz as dot;
210 //! type Nd<'a> = (usize, &'a str);
211 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
212 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
214 //! pub fn render_to<W: Write>(output: &mut W) {
215 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
216 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
217 //! let graph = Graph { nodes: nodes, edges: edges };
219 //! dot::render(&graph, output).unwrap()
222 //! impl<'a> dot::Labeller<'a> for Graph {
223 //! type Node = Nd<'a>;
224 //! type Edge = Ed<'a>;
225 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
226 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
227 //! dot::Id::new(format!("N{}", n.0)).unwrap()
229 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
231 //! dot::LabelText::LabelStr(self.nodes[i].into())
233 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
234 //! dot::LabelText::LabelStr("⊆".into())
238 //! impl<'a> dot::GraphWalk<'a> for Graph {
239 //! type Node = Nd<'a>;
240 //! type Edge = Ed<'a>;
241 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
242 //! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
244 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
245 //! self.edges.iter()
246 //! .map(|&(i,j)|((i, &self.nodes[i][..]),
247 //! (j, &self.nodes[j][..])))
250 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
251 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
254 //! # pub fn main() { render_to(&mut Vec::new()) }
258 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
260 //! use std::fs::File;
261 //! let mut f = File::create("example3.dot").unwrap();
262 //! render_to(&mut f)
268 //! * [Graphviz](https://www.graphviz.org/)
270 //! * [DOT language](https://www.graphviz.org/doc/info/lang.html)
273 html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
274 test(attr(allow(unused_variables), deny(warnings)))
276 #![deny(rustc::untranslatable_diagnostic)]
277 #![deny(rustc::diagnostic_outside_of_impl)]
281 use std::borrow::Cow;
283 use std::io::prelude::*;
285 /// The text for a graphviz label on a node or edge.
286 pub enum LabelText<'a> {
287 /// This kind of label preserves the text directly as is.
289 /// Occurrences of backslashes (`\`) are escaped, and thus appear
290 /// as backslashes in the rendered label.
291 LabelStr(Cow<'a, str>),
293 /// This kind of label uses the graphviz label escString type:
294 /// <https://www.graphviz.org/docs/attr-types/escString>
296 /// Occurrences of backslashes (`\`) are not escaped; instead they
297 /// are interpreted as initiating an escString escape sequence.
299 /// Escape sequences of particular interest: in addition to `\n`
300 /// to break a line (centering the line preceding the `\n`), there
301 /// are also the escape sequences `\l` which left-justifies the
302 /// preceding line and `\r` which right-justifies it.
303 EscStr(Cow<'a, str>),
305 /// This uses a graphviz [HTML string label][html]. The string is
306 /// printed exactly as given, but between `<` and `>`. **No
307 /// escaping is performed.**
309 /// [html]: https://www.graphviz.org/doc/info/shapes.html#html
310 HtmlStr(Cow<'a, str>),
313 /// The style for a node or edge.
314 /// See <https://www.graphviz.org/docs/attr-types/style/> for descriptions.
315 /// Note that some of these are not valid for edges.
316 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
331 pub fn as_slice(self) -> &'static str {
334 Style::Solid => "solid",
335 Style::Dashed => "dashed",
336 Style::Dotted => "dotted",
337 Style::Bold => "bold",
338 Style::Rounded => "rounded",
339 Style::Diagonals => "diagonals",
340 Style::Filled => "filled",
341 Style::Striped => "striped",
342 Style::Wedged => "wedged",
347 // There is a tension in the design of the labelling API.
349 // For example, I considered making a `Labeller<T>` trait that
350 // provides labels for `T`, and then making the graph type `G`
351 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
352 // not possible without functional dependencies. (One could work
353 // around that, but I did not explore that avenue heavily.)
355 // Another approach that I actually used for a while was to make a
356 // `Label<Context>` trait that is implemented by the client-specific
357 // Node and Edge types (as well as an implementation on Graph itself
358 // for the overall name for the graph). The main disadvantage of this
359 // second approach (compared to having the `G` type parameter
360 // implement a Labelling service) that I have encountered is that it
361 // makes it impossible to use types outside of the current crate
362 // directly as Nodes/Edges; you need to wrap them in newtype'd
363 // structs. See e.g., the `No` and `Ed` structs in the examples. (In
364 // practice clients using a graph in some other crate would need to
365 // provide some sort of adapter shim over the graph anyway to
366 // interface with this library).
368 // Another approach would be to make a single `Labeller<N,E>` trait
369 // that provides three methods (graph_label, node_label, edge_label),
370 // and then make `G` implement `Labeller<N,E>`. At first this did not
371 // appeal to me, since I had thought I would need separate methods on
372 // each data variant for dot-internal identifiers versus user-visible
373 // labels. However, the identifier/label distinction only arises for
374 // nodes; graphs themselves only have identifiers, and edges only have
377 // So in the end I decided to use the third approach described above.
379 /// `Id` is a Graphviz `ID`.
385 /// Creates an `Id` named `name`.
387 /// The caller must ensure that the input conforms to an
388 /// identifier format: it must be a non-empty string made up of
389 /// alphanumeric or underscore characters, not beginning with a
390 /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
392 /// (Note: this format is a strict subset of the `ID` format
393 /// defined by the DOT language. This function may change in the
394 /// future to accept a broader subset, or the entirety, of DOT's
397 /// Passing an invalid string (containing spaces, brackets,
398 /// quotes, ...) will return an empty `Err` value.
399 pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, ()> {
400 let name = name.into();
401 match name.chars().next() {
402 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
405 if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
412 pub fn as_slice(&'a self) -> &'a str {
417 /// Each instance of a type that implements `Label<C>` maps to a
418 /// unique identifier with respect to `C`, which is used to identify
419 /// it in the generated .dot file. They can also provide more
420 /// elaborate (and non-unique) label text that is used in the graphviz
423 /// The graph instance is responsible for providing the DOT compatible
424 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
425 /// edges, as well as an identifier for the graph itself.
426 pub trait Labeller<'a> {
430 /// Must return a DOT compatible identifier naming the graph.
431 fn graph_id(&'a self) -> Id<'a>;
433 /// Maps `n` to a unique identifier with respect to `self`. The
434 /// implementor is responsible for ensuring that the returned name
435 /// is a valid DOT identifier.
436 fn node_id(&'a self, n: &Self::Node) -> Id<'a>;
438 /// Maps `n` to one of the [graphviz `shape` names][1]. If `None`
439 /// is returned, no `shape` attribute is specified.
441 /// [1]: https://www.graphviz.org/doc/info/shapes.html
442 fn node_shape(&'a self, _node: &Self::Node) -> Option<LabelText<'a>> {
446 /// Maps `n` to a label that will be used in the rendered output.
447 /// The label need not be unique, and may be the empty string; the
448 /// default is just the output from `node_id`.
449 fn node_label(&'a self, n: &Self::Node) -> LabelText<'a> {
450 LabelStr(self.node_id(n).name)
453 /// Maps `e` to a label that will be used in the rendered output.
454 /// The label need not be unique, and may be the empty string; the
455 /// default is in fact the empty string.
456 fn edge_label(&'a self, _e: &Self::Edge) -> LabelText<'a> {
460 /// Maps `n` to a style that will be used in the rendered output.
461 fn node_style(&'a self, _n: &Self::Node) -> Style {
465 /// Maps `e` to a style that will be used in the rendered output.
466 fn edge_style(&'a self, _e: &Self::Edge) -> Style {
471 /// Escape tags in such a way that it is suitable for inclusion in a
472 /// Graphviz HTML label.
473 pub fn escape_html(s: &str) -> String {
474 s.replace('&', "&")
475 .replace('\"', """)
476 .replace('<', "<")
477 .replace('>', ">")
478 .replace('\n', "<br align=\"left\"/>")
481 impl<'a> LabelText<'a> {
482 pub fn label<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
486 pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
490 fn escape_char<F>(c: char, mut f: F)
495 // not escaping \\, since Graphviz escString needs to
496 // interpret backslashes; see EscStr above.
499 for c in c.escape_default() {
505 fn escape_str(s: &str) -> String {
506 let mut out = String::with_capacity(s.len());
508 LabelText::escape_char(c, |c| out.push(c));
513 /// Renders text as string suitable for a label in a .dot file.
514 /// This includes quotes or suitable delimiters.
515 pub fn to_dot_string(&self) -> String {
517 LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
518 EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(s)),
519 HtmlStr(ref s) => format!("<{}>", s),
523 /// Decomposes content into string suitable for making EscStr that
524 /// yields same content as self. The result obeys the law
525 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
526 /// all `lt: LabelText`.
527 fn pre_escaped_content(self) -> Cow<'a, str> {
531 if s.contains('\\') {
532 s.escape_default().to_string().into()
541 /// Puts `suffix` on a line below this label, with a blank line separator.
542 pub fn suffix_line(self, suffix: LabelText<'_>) -> LabelText<'static> {
543 let mut prefix = self.pre_escaped_content().into_owned();
544 let suffix = suffix.pre_escaped_content();
545 prefix.push_str(r"\n\n");
546 prefix.push_str(&suffix);
547 EscStr(prefix.into())
551 pub type Nodes<'a, N> = Cow<'a, [N]>;
552 pub type Edges<'a, E> = Cow<'a, [E]>;
554 // (The type parameters in GraphWalk should be associated items,
555 // when/if Rust supports such.)
557 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
558 /// made up of node handles `N` and edge handles `E`, where each `E`
559 /// can be mapped to its source and target nodes.
561 /// The lifetime parameter `'a` is exposed in this trait (rather than
562 /// introduced as a generic parameter on each method declaration) so
563 /// that a client impl can choose `N` and `E` that have substructure
564 /// that is bound by the self lifetime `'a`.
566 /// The `nodes` and `edges` method each return instantiations of
567 /// `Cow<[T]>` to leave implementors the freedom to create
568 /// entirely new vectors or to pass back slices into internally owned
570 pub trait GraphWalk<'a> {
574 /// Returns all the nodes in this graph.
575 fn nodes(&'a self) -> Nodes<'a, Self::Node>;
576 /// Returns all of the edges in this graph.
577 fn edges(&'a self) -> Edges<'a, Self::Edge>;
578 /// The source node for `edge`.
579 fn source(&'a self, edge: &Self::Edge) -> Self::Node;
580 /// The target node for `edge`.
581 fn target(&'a self, edge: &Self::Edge) -> Self::Node;
584 #[derive(Clone, PartialEq, Eq, Debug)]
585 pub enum RenderOption {
595 /// Renders directed graph `g` into the writer `w` in DOT syntax.
596 /// (Simple wrapper around `render_opts` that passes a default set of options.)
597 pub fn render<'a, N, E, G, W>(g: &'a G, w: &mut W) -> io::Result<()>
601 G: Labeller<'a, Node = N, Edge = E> + GraphWalk<'a, Node = N, Edge = E>,
604 render_opts(g, w, &[])
607 /// Renders directed graph `g` into the writer `w` in DOT syntax.
608 /// (Main entry point for the library.)
609 pub fn render_opts<'a, N, E, G, W>(g: &'a G, w: &mut W, options: &[RenderOption]) -> io::Result<()>
613 G: Labeller<'a, Node = N, Edge = E> + GraphWalk<'a, Node = N, Edge = E>,
616 writeln!(w, "digraph {} {{", g.graph_id().as_slice())?;
618 // Global graph properties
619 let mut graph_attrs = Vec::new();
620 let mut content_attrs = Vec::new();
622 if let Some(fontname) = options.iter().find_map(|option| {
623 if let RenderOption::Fontname(fontname) = option { Some(fontname) } else { None }
625 font = format!(r#"fontname="{}""#, fontname);
626 graph_attrs.push(&font[..]);
627 content_attrs.push(&font[..]);
629 if options.contains(&RenderOption::DarkTheme) {
630 graph_attrs.push(r#"bgcolor="black""#);
631 graph_attrs.push(r#"fontcolor="white""#);
632 content_attrs.push(r#"color="white""#);
633 content_attrs.push(r#"fontcolor="white""#);
635 if !(graph_attrs.is_empty() && content_attrs.is_empty()) {
636 writeln!(w, r#" graph[{}];"#, graph_attrs.join(" "))?;
637 let content_attrs_str = content_attrs.join(" ");
638 writeln!(w, r#" node[{}];"#, content_attrs_str)?;
639 writeln!(w, r#" edge[{}];"#, content_attrs_str)?;
642 let mut text = Vec::new();
643 for n in g.nodes().iter() {
645 let id = g.node_id(n);
647 let escaped = &g.node_label(n).to_dot_string();
649 write!(text, "{}", id.as_slice()).unwrap();
651 if !options.contains(&RenderOption::NoNodeLabels) {
652 write!(text, "[label={}]", escaped).unwrap();
655 let style = g.node_style(n);
656 if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
657 write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
660 if let Some(s) = g.node_shape(n) {
661 write!(text, "[shape={}]", &s.to_dot_string()).unwrap();
664 writeln!(text, ";").unwrap();
670 for e in g.edges().iter() {
671 let escaped_label = &g.edge_label(e).to_dot_string();
673 let source = g.source(e);
674 let target = g.target(e);
675 let source_id = g.node_id(&source);
676 let target_id = g.node_id(&target);
678 write!(text, "{} -> {}", source_id.as_slice(), target_id.as_slice()).unwrap();
680 if !options.contains(&RenderOption::NoEdgeLabels) {
681 write!(text, "[label={}]", escaped_label).unwrap();
684 let style = g.edge_style(e);
685 if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
686 write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
689 writeln!(text, ";").unwrap();