1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Generate files suitable for use with [Graphviz](http://www.graphviz.org/)
13 //! The `render` function generates output (e.g. an `output.dot` file) for
14 //! use with [Graphviz](http://www.graphviz.org/) by walking a labeled
15 //! graph. (Graphviz can then automatically lay out the nodes and edges
16 //! of the graph, and also optionally render the graph as an image or
17 //! other [output formats](
18 //! http://www.graphviz.org/content/output-formats), such as SVG.)
20 //! Rather than impose some particular graph data structure on clients,
21 //! this library exposes two traits that clients can implement on their
22 //! own structs before handing them over to the rendering function.
24 //! Note: This library does not yet provide access to the full
25 //! expressiveness of the [DOT language](
26 //! http://www.graphviz.org/doc/info/lang.html). For example, there are
27 //! many [attributes](http://www.graphviz.org/content/attrs) related to
28 //! providing layout hints (e.g. left-to-right versus top-down, which
29 //! algorithm to use, etc). The current intention of this library is to
30 //! emit a human-readable .dot file with very regular structure suitable
31 //! for easy post-processing.
35 //! The first example uses a very simple graph representation: a list of
36 //! pairs of ints, representing the edges (the node set is implicit).
37 //! Each node label is derived directly from the int representing the node,
38 //! while the edge labels are all empty strings.
40 //! This example also illustrates how to use `Cow<[T]>` to return
41 //! an owned vector or a borrowed slice as appropriate: we construct the
42 //! node vector from scratch, but borrow the edge list (rather than
43 //! constructing a copy of all the edges from scratch).
45 //! The output from this example renders five nodes, with the first four
46 //! forming a diamond-shaped acyclic graph and then pointing to the fifth
50 //! #![feature(rustc_private)]
52 //! use graphviz::IntoCow;
53 //! use std::io::Write;
54 //! use graphviz as dot;
57 //! type Ed = (isize,isize);
58 //! struct Edges(Vec<Ed>);
60 //! pub fn render_to<W: Write>(output: &mut W) {
61 //! let edges = Edges(vec![(0,1), (0,2), (1,3), (2,3), (3,4), (4,4)]);
62 //! dot::render(&edges, output).unwrap()
65 //! impl<'a> dot::Labeller<'a> for Edges {
68 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
70 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
71 //! dot::Id::new(format!("N{}", *n)).unwrap()
75 //! impl<'a> dot::GraphWalk<'a> for Edges {
78 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
79 //! // (assumes that |N| \approxeq |E|)
80 //! let &Edges(ref v) = self;
81 //! let mut nodes = Vec::with_capacity(v.len());
83 //! nodes.push(s); nodes.push(t);
90 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
91 //! let &Edges(ref edges) = self;
92 //! (&edges[..]).into_cow()
95 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
97 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
100 //! # pub fn main() { render_to(&mut Vec::new()) }
104 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
106 //! use std::fs::File;
107 //! let mut f = File::create("example1.dot").unwrap();
108 //! render_to(&mut f)
112 //! Output from first example (in `example1.dot`):
115 //! digraph example1 {
121 //! N0 -> N1[label=""];
122 //! N0 -> N2[label=""];
123 //! N1 -> N3[label=""];
124 //! N2 -> N3[label=""];
125 //! N3 -> N4[label=""];
126 //! N4 -> N4[label=""];
130 //! The second example illustrates using `node_label` and `edge_label` to
131 //! add labels to the nodes and edges in the rendered graph. The graph
132 //! here carries both `nodes` (the label text to use for rendering a
133 //! particular node), and `edges` (again a list of `(source,target)`
136 //! This example also illustrates how to use a type (in this case the edge
137 //! type) that shares substructure with the graph: the edge type here is a
138 //! direct reference to the `(source,target)` pair stored in the graph's
139 //! internal vector (rather than passing around a copy of the pair
140 //! itself). Note that this implies that `fn edges(&'a self)` must
141 //! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
142 //! edges stored in `self`.
144 //! Since both the set of nodes and the set of edges are always
145 //! constructed from scratch via iterators, we use the `collect()` method
146 //! from the `Iterator` trait to collect the nodes and edges into freshly
147 //! constructed growable `Vec` values (rather use the `into_cow`
148 //! from the `IntoCow` trait as was used in the first example
151 //! The output from this example renders four nodes that make up the
152 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
153 //! labeled with the ⊆ character (specified using the HTML character
157 //! #![feature(rustc_private)]
159 //! use std::io::Write;
160 //! use graphviz as dot;
163 //! type Ed<'a> = &'a (usize, usize);
164 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
166 //! pub fn render_to<W: Write>(output: &mut W) {
167 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
168 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
169 //! let graph = Graph { nodes: nodes, edges: edges };
171 //! dot::render(&graph, output).unwrap()
174 //! impl<'a> dot::Labeller<'a> for Graph {
176 //! type Edge = Ed<'a>;
177 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
178 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
179 //! dot::Id::new(format!("N{}", n)).unwrap()
181 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
182 //! dot::LabelText::LabelStr(self.nodes[*n].into())
184 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
185 //! dot::LabelText::LabelStr("⊆".into())
189 //! impl<'a> dot::GraphWalk<'a> for Graph {
191 //! type Edge = Ed<'a>;
192 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
193 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
194 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
195 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
198 //! # pub fn main() { render_to(&mut Vec::new()) }
202 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
204 //! use std::fs::File;
205 //! let mut f = File::create("example2.dot").unwrap();
206 //! render_to(&mut f)
210 //! The third example is similar to the second, except now each node and
211 //! edge now carries a reference to the string label for each node as well
212 //! as that node's index. (This is another illustration of how to share
213 //! structure with the graph itself, and why one might want to do so.)
215 //! The output from this example is the same as the second example: the
216 //! Hasse-diagram for the subsets of the set `{x, y}`.
219 //! #![feature(rustc_private)]
221 //! use std::io::Write;
222 //! use graphviz as dot;
224 //! type Nd<'a> = (usize, &'a str);
225 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
226 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
228 //! pub fn render_to<W: Write>(output: &mut W) {
229 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
230 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
231 //! let graph = Graph { nodes: nodes, edges: edges };
233 //! dot::render(&graph, output).unwrap()
236 //! impl<'a> dot::Labeller<'a> for Graph {
237 //! type Node = Nd<'a>;
238 //! type Edge = Ed<'a>;
239 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
240 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
241 //! dot::Id::new(format!("N{}", n.0)).unwrap()
243 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
245 //! dot::LabelText::LabelStr(self.nodes[i].into())
247 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
248 //! dot::LabelText::LabelStr("⊆".into())
252 //! impl<'a> dot::GraphWalk<'a> for Graph {
253 //! type Node = Nd<'a>;
254 //! type Edge = Ed<'a>;
255 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
256 //! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
258 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
259 //! self.edges.iter()
260 //! .map(|&(i,j)|((i, &self.nodes[i][..]),
261 //! (j, &self.nodes[j][..])))
264 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
265 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
268 //! # pub fn main() { render_to(&mut Vec::new()) }
272 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
274 //! use std::fs::File;
275 //! let mut f = File::create("example3.dot").unwrap();
276 //! render_to(&mut f)
282 //! * [Graphviz](http://www.graphviz.org/)
284 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
286 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
287 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
288 html_root_url = "https://doc.rust-lang.org/nightly/",
289 test(attr(allow(unused_variables), deny(warnings))))]
291 #![feature(str_escape)]
293 use self::LabelText::*;
295 use std::borrow::{Cow, ToOwned};
296 use std::io::prelude::*;
299 /// The text for a graphviz label on a node or edge.
300 pub enum LabelText<'a> {
301 /// This kind of label preserves the text directly as is.
303 /// Occurrences of backslashes (`\`) are escaped, and thus appear
304 /// as backslashes in the rendered label.
305 LabelStr(Cow<'a, str>),
307 /// This kind of label uses the graphviz label escString type:
308 /// <http://www.graphviz.org/content/attrs#kescString>
310 /// Occurrences of backslashes (`\`) are not escaped; instead they
311 /// are interpreted as initiating an escString escape sequence.
313 /// Escape sequences of particular interest: in addition to `\n`
314 /// to break a line (centering the line preceding the `\n`), there
315 /// are also the escape sequences `\l` which left-justifies the
316 /// preceding line and `\r` which right-justifies it.
317 EscStr(Cow<'a, str>),
319 /// This uses a graphviz [HTML string label][html]. The string is
320 /// printed exactly as given, but between `<` and `>`. **No
321 /// escaping is performed.**
323 /// [html]: http://www.graphviz.org/content/node-shapes#html
324 HtmlStr(Cow<'a, str>),
327 /// The style for a node or edge.
328 /// See <http://www.graphviz.org/doc/info/attrs.html#k:style> for descriptions.
329 /// Note that some of these are not valid for edges.
330 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
345 pub fn as_slice(self) -> &'static str {
348 Style::Solid => "solid",
349 Style::Dashed => "dashed",
350 Style::Dotted => "dotted",
351 Style::Bold => "bold",
352 Style::Rounded => "rounded",
353 Style::Diagonals => "diagonals",
354 Style::Filled => "filled",
355 Style::Striped => "striped",
356 Style::Wedged => "wedged",
361 // There is a tension in the design of the labelling API.
363 // For example, I considered making a `Labeller<T>` trait that
364 // provides labels for `T`, and then making the graph type `G`
365 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
366 // not possible without functional dependencies. (One could work
367 // around that, but I did not explore that avenue heavily.)
369 // Another approach that I actually used for a while was to make a
370 // `Label<Context>` trait that is implemented by the client-specific
371 // Node and Edge types (as well as an implementation on Graph itself
372 // for the overall name for the graph). The main disadvantage of this
373 // second approach (compared to having the `G` type parameter
374 // implement a Labelling service) that I have encountered is that it
375 // makes it impossible to use types outside of the current crate
376 // directly as Nodes/Edges; you need to wrap them in newtype'd
377 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
378 // practice clients using a graph in some other crate would need to
379 // provide some sort of adapter shim over the graph anyway to
380 // interface with this library).
382 // Another approach would be to make a single `Labeller<N,E>` trait
383 // that provides three methods (graph_label, node_label, edge_label),
384 // and then make `G` implement `Labeller<N,E>`. At first this did not
385 // appeal to me, since I had thought I would need separate methods on
386 // each data variant for dot-internal identifiers versus user-visible
387 // labels. However, the identifier/label distinction only arises for
388 // nodes; graphs themselves only have identifiers, and edges only have
391 // So in the end I decided to use the third approach described above.
393 /// `Id` is a Graphviz `ID`.
399 /// Creates an `Id` named `name`.
401 /// The caller must ensure that the input conforms to an
402 /// identifier format: it must be a non-empty string made up of
403 /// alphanumeric or underscore characters, not beginning with a
404 /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
406 /// (Note: this format is a strict subset of the `ID` format
407 /// defined by the DOT language. This function may change in the
408 /// future to accept a broader subset, or the entirety, of DOT's
411 /// Passing an invalid string (containing spaces, brackets,
412 /// quotes, ...) will return an empty `Err` value.
413 pub fn new<Name: IntoCow<'a, str>>(name: Name) -> Result<Id<'a>, ()> {
414 let name = name.into_cow();
415 match name.chars().next() {
416 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
419 if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' ) {
422 return Ok(Id { name: name });
425 pub fn as_slice(&'a self) -> &'a str {
429 pub fn name(self) -> Cow<'a, str> {
434 /// Each instance of a type that implements `Label<C>` maps to a
435 /// unique identifier with respect to `C`, which is used to identify
436 /// it in the generated .dot file. They can also provide more
437 /// elaborate (and non-unique) label text that is used in the graphviz
440 /// The graph instance is responsible for providing the DOT compatible
441 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
442 /// edges, as well as an identifier for the graph itself.
443 pub trait Labeller<'a> {
447 /// Must return a DOT compatible identifier naming the graph.
448 fn graph_id(&'a self) -> Id<'a>;
450 /// Maps `n` to a unique identifier with respect to `self`. The
451 /// implementor is responsible for ensuring that the returned name
452 /// is a valid DOT identifier.
453 fn node_id(&'a self, n: &Self::Node) -> Id<'a>;
455 /// Maps `n` to one of the [graphviz `shape` names][1]. If `None`
456 /// is returned, no `shape` attribute is specified.
458 /// [1]: http://www.graphviz.org/content/node-shapes
459 fn node_shape(&'a self, _node: &Self::Node) -> Option<LabelText<'a>> {
463 /// Maps `n` to a label that will be used in the rendered output.
464 /// The label need not be unique, and may be the empty string; the
465 /// default is just the output from `node_id`.
466 fn node_label(&'a self, n: &Self::Node) -> LabelText<'a> {
467 LabelStr(self.node_id(n).name)
470 /// Maps `e` to a label that will be used in the rendered output.
471 /// The label need not be unique, and may be the empty string; the
472 /// default is in fact the empty string.
473 fn edge_label(&'a self, _e: &Self::Edge) -> LabelText<'a> {
474 LabelStr("".into_cow())
477 /// Maps `n` to a style that will be used in the rendered output.
478 fn node_style(&'a self, _n: &Self::Node) -> Style {
482 /// Maps `e` to a style that will be used in the rendered output.
483 fn edge_style(&'a self, _e: &Self::Edge) -> Style {
488 /// Escape tags in such a way that it is suitable for inclusion in a
489 /// Graphviz HTML label.
490 pub fn escape_html(s: &str) -> String {
491 s.replace("&", "&")
492 .replace("\"", """)
493 .replace("<", "<")
494 .replace(">", ">")
497 impl<'a> LabelText<'a> {
498 pub fn label<S: IntoCow<'a, str>>(s: S) -> LabelText<'a> {
499 LabelStr(s.into_cow())
502 pub fn escaped<S: IntoCow<'a, str>>(s: S) -> LabelText<'a> {
506 pub fn html<S: IntoCow<'a, str>>(s: S) -> LabelText<'a> {
507 HtmlStr(s.into_cow())
510 fn escape_char<F>(c: char, mut f: F)
514 // not escaping \\, since Graphviz escString needs to
515 // interpret backslashes; see EscStr above.
518 for c in c.escape_default() {
524 fn escape_str(s: &str) -> String {
525 let mut out = String::with_capacity(s.len());
527 LabelText::escape_char(c, |c| out.push(c));
532 /// Renders text as string suitable for a label in a .dot file.
533 /// This includes quotes or suitable delimiters.
534 pub fn to_dot_string(&self) -> String {
536 &LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
537 &EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s)),
538 &HtmlStr(ref s) => format!("<{}>", s),
542 /// Decomposes content into string suitable for making EscStr that
543 /// yields same content as self. The result obeys the law
544 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
545 /// all `lt: LabelText`.
546 fn pre_escaped_content(self) -> Cow<'a, str> {
550 if s.contains('\\') {
551 (&*s).escape_default().into_cow()
560 /// Puts `prefix` on a line above this label, with a blank line separator.
561 pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
562 prefix.suffix_line(self)
565 /// Puts `suffix` on a line below this label, with a blank line separator.
566 pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
567 let mut prefix = self.pre_escaped_content().into_owned();
568 let suffix = suffix.pre_escaped_content();
569 prefix.push_str(r"\n\n");
570 prefix.push_str(&suffix);
571 EscStr(prefix.into_cow())
575 pub type Nodes<'a,N> = Cow<'a,[N]>;
576 pub type Edges<'a,E> = Cow<'a,[E]>;
578 // (The type parameters in GraphWalk should be associated items,
579 // when/if Rust supports such.)
581 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
582 /// made up of node handles `N` and edge handles `E`, where each `E`
583 /// can be mapped to its source and target nodes.
585 /// The lifetime parameter `'a` is exposed in this trait (rather than
586 /// introduced as a generic parameter on each method declaration) so
587 /// that a client impl can choose `N` and `E` that have substructure
588 /// that is bound by the self lifetime `'a`.
590 /// The `nodes` and `edges` method each return instantiations of
591 /// `Cow<[T]>` to leave implementors the freedom to create
592 /// entirely new vectors or to pass back slices into internally owned
594 pub trait GraphWalk<'a> {
598 /// Returns all the nodes in this graph.
599 fn nodes(&'a self) -> Nodes<'a, Self::Node>;
600 /// Returns all of the edges in this graph.
601 fn edges(&'a self) -> Edges<'a, Self::Edge>;
602 /// The source node for `edge`.
603 fn source(&'a self, edge: &Self::Edge) -> Self::Node;
604 /// The target node for `edge`.
605 fn target(&'a self, edge: &Self::Edge) -> Self::Node;
608 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
609 pub enum RenderOption {
616 /// Returns vec holding all the default render options.
617 pub fn default_options() -> Vec<RenderOption> {
621 /// Renders directed graph `g` into the writer `w` in DOT syntax.
622 /// (Simple wrapper around `render_opts` that passes a default set of options.)
623 pub fn render<'a,N,E,G,W>(g: &'a G, w: &mut W) -> io::Result<()>
626 G: Labeller<'a, Node=N, Edge=E> + GraphWalk<'a, Node=N, Edge=E>,
629 render_opts(g, w, &[])
632 /// Renders directed graph `g` into the writer `w` in DOT syntax.
633 /// (Main entry point for the library.)
634 pub fn render_opts<'a, N, E, G, W>(g: &'a G,
636 options: &[RenderOption])
640 G: Labeller<'a, Node=N, Edge=E> + GraphWalk<'a, Node=N, Edge=E>,
643 writeln!(w, "digraph {} {{", g.graph_id().as_slice())?;
644 for n in g.nodes().iter() {
646 let id = g.node_id(n);
648 let escaped = &g.node_label(n).to_dot_string();
650 let mut text = Vec::new();
651 write!(text, "{}", id.as_slice()).unwrap();
653 if !options.contains(&RenderOption::NoNodeLabels) {
654 write!(text, "[label={}]", escaped).unwrap();
657 let style = g.node_style(n);
658 if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
659 write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
662 if let Some(s) = g.node_shape(n) {
663 write!(text, "[shape={}]", &s.to_dot_string()).unwrap();
666 writeln!(text, ";").unwrap();
667 w.write_all(&text[..])?;
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 let mut text = Vec::new();
679 write!(text, "{} -> {}", source_id.as_slice(), target_id.as_slice()).unwrap();
681 if !options.contains(&RenderOption::NoEdgeLabels) {
682 write!(text, "[label={}]", escaped_label).unwrap();
685 let style = g.edge_style(e);
686 if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
687 write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
690 writeln!(text, ";").unwrap();
691 w.write_all(&text[..])?;
697 pub trait IntoCow<'a, B: ?Sized> where B: ToOwned {
698 fn into_cow(self) -> Cow<'a, B>;
701 impl<'a> IntoCow<'a, str> for String {
702 fn into_cow(self) -> Cow<'a, str> {
707 impl<'a> IntoCow<'a, str> for &'a str {
708 fn into_cow(self) -> Cow<'a, str> {
713 impl<'a> IntoCow<'a, str> for Cow<'a, str> {
714 fn into_cow(self) -> Cow<'a, str> {
719 impl<'a, T: Clone> IntoCow<'a, [T]> for Vec<T> {
720 fn into_cow(self) -> Cow<'a, [T]> {
725 impl<'a, T: Clone> IntoCow<'a, [T]> for &'a [T] {
726 fn into_cow(self) -> Cow<'a, [T]> {
733 use self::NodeLabels::*;
734 use super::{Id, Labeller, Nodes, Edges, GraphWalk, render, Style};
735 use super::LabelText::{self, LabelStr, EscStr, HtmlStr};
737 use std::io::prelude::*;
740 /// each node is an index in a vector in the graph.
749 fn edge(from: usize, to: usize, label: &'static str, style: Style) -> Edge {
758 struct LabelledGraph {
759 /// The name for this graph. Used for labeling generated `digraph`.
762 /// Each node is an index into `node_labels`; these labels are
763 /// used as the label text for each node. (The node *names*,
764 /// which are unique identifiers, are derived from their index
767 /// If a node maps to None here, then just use its name as its
769 node_labels: Vec<Option<&'static str>>,
771 node_styles: Vec<Style>,
773 /// Each edge relates a from-index to a to-index along with a
774 /// label; `edges` collects them.
778 // A simple wrapper around LabelledGraph that forces the labels to
779 // be emitted as EscStr.
780 struct LabelledGraphWithEscStrs {
781 graph: LabelledGraph,
785 AllNodesLabelled(Vec<L>),
786 UnlabelledNodes(usize),
787 SomeNodesLabelled(Vec<Option<L>>),
790 type Trivial = NodeLabels<&'static str>;
792 impl NodeLabels<&'static str> {
793 fn to_opt_strs(self) -> Vec<Option<&'static str>> {
795 UnlabelledNodes(len) => vec![None; len],
796 AllNodesLabelled(lbls) => lbls.into_iter().map(|l| Some(l)).collect(),
797 SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
801 fn len(&self) -> usize {
803 &UnlabelledNodes(len) => len,
804 &AllNodesLabelled(ref lbls) => lbls.len(),
805 &SomeNodesLabelled(ref lbls) => lbls.len(),
811 fn new(name: &'static str,
812 node_labels: Trivial,
814 node_styles: Option<Vec<Style>>)
816 let count = node_labels.len();
819 node_labels: node_labels.to_opt_strs(),
821 node_styles: match node_styles {
822 Some(nodes) => nodes,
823 None => vec![Style::None; count],
829 impl LabelledGraphWithEscStrs {
830 fn new(name: &'static str,
831 node_labels: Trivial,
833 -> LabelledGraphWithEscStrs {
834 LabelledGraphWithEscStrs { graph: LabelledGraph::new(name, node_labels, edges, None) }
838 fn id_name<'a>(n: &Node) -> Id<'a> {
839 Id::new(format!("N{}", *n)).unwrap()
842 impl<'a> Labeller<'a> for LabelledGraph {
844 type Edge = &'a Edge;
845 fn graph_id(&'a self) -> Id<'a> {
846 Id::new(self.name).unwrap()
848 fn node_id(&'a self, n: &Node) -> Id<'a> {
851 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
852 match self.node_labels[*n] {
853 Some(ref l) => LabelStr(l.into_cow()),
854 None => LabelStr(id_name(n).name()),
857 fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
858 LabelStr(e.label.into_cow())
860 fn node_style(&'a self, n: &Node) -> Style {
863 fn edge_style(&'a self, e: &&'a Edge) -> Style {
868 impl<'a> Labeller<'a> for LabelledGraphWithEscStrs {
870 type Edge = &'a Edge;
871 fn graph_id(&'a self) -> Id<'a> {
872 self.graph.graph_id()
874 fn node_id(&'a self, n: &Node) -> Id<'a> {
875 self.graph.node_id(n)
877 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
878 match self.graph.node_label(n) {
879 LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
882 fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
883 match self.graph.edge_label(e) {
884 LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
889 impl<'a> GraphWalk<'a> for LabelledGraph {
891 type Edge = &'a Edge;
892 fn nodes(&'a self) -> Nodes<'a, Node> {
893 (0..self.node_labels.len()).collect()
895 fn edges(&'a self) -> Edges<'a, &'a Edge> {
896 self.edges.iter().collect()
898 fn source(&'a self, edge: &&'a Edge) -> Node {
901 fn target(&'a self, edge: &&'a Edge) -> Node {
906 impl<'a> GraphWalk<'a> for LabelledGraphWithEscStrs {
908 type Edge = &'a Edge;
909 fn nodes(&'a self) -> Nodes<'a, Node> {
912 fn edges(&'a self) -> Edges<'a, &'a Edge> {
915 fn source(&'a self, edge: &&'a Edge) -> Node {
918 fn target(&'a self, edge: &&'a Edge) -> Node {
923 fn test_input(g: LabelledGraph) -> io::Result<String> {
924 let mut writer = Vec::new();
925 render(&g, &mut writer).unwrap();
926 let mut s = String::new();
927 Read::read_to_string(&mut &*writer, &mut s)?;
931 // All of the tests use raw-strings as the format for the expected outputs,
932 // so that you can cut-and-paste the content into a .dot file yourself to
933 // see what the graphviz visualizer would produce.
937 let labels: Trivial = UnlabelledNodes(0);
938 let r = test_input(LabelledGraph::new("empty_graph", labels, vec![], None));
939 assert_eq!(r.unwrap(),
940 r#"digraph empty_graph {
947 let labels: Trivial = UnlabelledNodes(1);
948 let r = test_input(LabelledGraph::new("single_node", labels, vec![], None));
949 assert_eq!(r.unwrap(),
950 r#"digraph single_node {
957 fn single_node_with_style() {
958 let labels: Trivial = UnlabelledNodes(1);
959 let styles = Some(vec![Style::Dashed]);
960 let r = test_input(LabelledGraph::new("single_node", labels, vec![], styles));
961 assert_eq!(r.unwrap(),
962 r#"digraph single_node {
963 N0[label="N0"][style="dashed"];
970 let labels: Trivial = UnlabelledNodes(2);
971 let result = test_input(LabelledGraph::new("single_edge",
973 vec![edge(0, 1, "E", Style::None)],
975 assert_eq!(result.unwrap(),
976 r#"digraph single_edge {
985 fn single_edge_with_style() {
986 let labels: Trivial = UnlabelledNodes(2);
987 let result = test_input(LabelledGraph::new("single_edge",
989 vec![edge(0, 1, "E", Style::Bold)],
991 assert_eq!(result.unwrap(),
992 r#"digraph single_edge {
995 N0 -> N1[label="E"][style="bold"];
1001 fn test_some_labelled() {
1002 let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
1003 let styles = Some(vec![Style::None, Style::Dotted]);
1004 let result = test_input(LabelledGraph::new("test_some_labelled",
1006 vec![edge(0, 1, "A-1", Style::None)],
1008 assert_eq!(result.unwrap(),
1009 r#"digraph test_some_labelled {
1011 N1[label="N1"][style="dotted"];
1012 N0 -> N1[label="A-1"];
1018 fn single_cyclic_node() {
1019 let labels: Trivial = UnlabelledNodes(1);
1020 let r = test_input(LabelledGraph::new("single_cyclic_node",
1022 vec![edge(0, 0, "E", Style::None)],
1024 assert_eq!(r.unwrap(),
1025 r#"digraph single_cyclic_node {
1027 N0 -> N0[label="E"];
1033 fn hasse_diagram() {
1034 let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
1035 let r = test_input(LabelledGraph::new("hasse_diagram",
1037 vec![edge(0, 1, "", Style::None),
1038 edge(0, 2, "", Style::None),
1039 edge(1, 3, "", Style::None),
1040 edge(2, 3, "", Style::None)],
1042 assert_eq!(r.unwrap(),
1043 r#"digraph hasse_diagram {
1057 fn left_aligned_text() {
1058 let labels = AllNodesLabelled(vec![
1070 let mut writer = Vec::new();
1072 let g = LabelledGraphWithEscStrs::new("syntax_tree",
1074 vec![edge(0, 1, "then", Style::None),
1075 edge(0, 2, "else", Style::None),
1076 edge(1, 3, ";", Style::None),
1077 edge(2, 3, ";", Style::None)]);
1079 render(&g, &mut writer).unwrap();
1080 let mut r = String::new();
1081 Read::read_to_string(&mut &*writer, &mut r).unwrap();
1084 r#"digraph syntax_tree {
1085 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
1086 N1[label="branch1"];
1087 N2[label="branch2"];
1088 N3[label="afterward"];
1089 N0 -> N1[label="then"];
1090 N0 -> N2[label="else"];
1091 N1 -> N3[label=";"];
1092 N2 -> N3[label=";"];
1098 fn simple_id_construction() {
1099 let id1 = Id::new("hello");
1102 Err(..) => panic!("'hello' is not a valid value for id anymore"),
1107 fn badly_formatted_id() {
1108 let id2 = Id::new("Weird { struct : ure } !!!");
1110 Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),