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 std::io::Write;
53 //! use graphviz as dot;
56 //! type Ed = (isize,isize);
57 //! struct Edges(Vec<Ed>);
59 //! pub fn render_to<W: Write>(output: &mut W) {
60 //! let edges = Edges(vec![(0,1), (0,2), (1,3), (2,3), (3,4), (4,4)]);
61 //! dot::render(&edges, output).unwrap()
64 //! impl<'a> dot::Labeller<'a> for Edges {
67 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
69 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
70 //! dot::Id::new(format!("N{}", *n)).unwrap()
74 //! impl<'a> dot::GraphWalk<'a> for Edges {
77 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
78 //! // (assumes that |N| \approxeq |E|)
79 //! let &Edges(ref v) = self;
80 //! let mut nodes = Vec::with_capacity(v.len());
82 //! nodes.push(s); nodes.push(t);
89 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
90 //! let &Edges(ref edges) = self;
91 //! (&edges[..]).into()
94 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
96 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
99 //! # pub fn main() { render_to(&mut Vec::new()) }
103 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
105 //! use std::fs::File;
106 //! let mut f = File::create("example1.dot").unwrap();
107 //! render_to(&mut f)
111 //! Output from first example (in `example1.dot`):
114 //! digraph example1 {
120 //! N0 -> N1[label=""];
121 //! N0 -> N2[label=""];
122 //! N1 -> N3[label=""];
123 //! N2 -> N3[label=""];
124 //! N3 -> N4[label=""];
125 //! N4 -> N4[label=""];
129 //! The second example illustrates using `node_label` and `edge_label` to
130 //! add labels to the nodes and edges in the rendered graph. The graph
131 //! here carries both `nodes` (the label text to use for rendering a
132 //! particular node), and `edges` (again a list of `(source,target)`
135 //! This example also illustrates how to use a type (in this case the edge
136 //! type) that shares substructure with the graph: the edge type here is a
137 //! direct reference to the `(source,target)` pair stored in the graph's
138 //! internal vector (rather than passing around a copy of the pair
139 //! itself). Note that this implies that `fn edges(&'a self)` must
140 //! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
141 //! edges stored in `self`.
143 //! Since both the set of nodes and the set of edges are always
144 //! constructed from scratch via iterators, we use the `collect()` method
145 //! from the `Iterator` trait to collect the nodes and edges into freshly
146 //! constructed growable `Vec` values (rather than using `Cow` as in the
147 //! first example above).
149 //! The output from this example renders four nodes that make up the
150 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
151 //! labeled with the ⊆ character (specified using the HTML character
155 //! #![feature(rustc_private)]
157 //! use std::io::Write;
158 //! use graphviz as dot;
161 //! type Ed<'a> = &'a (usize, usize);
162 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
164 //! pub fn render_to<W: Write>(output: &mut W) {
165 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
166 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
167 //! let graph = Graph { nodes: nodes, edges: edges };
169 //! dot::render(&graph, output).unwrap()
172 //! impl<'a> dot::Labeller<'a> for Graph {
174 //! type Edge = Ed<'a>;
175 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
176 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
177 //! dot::Id::new(format!("N{}", n)).unwrap()
179 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
180 //! dot::LabelText::LabelStr(self.nodes[*n].into())
182 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
183 //! dot::LabelText::LabelStr("⊆".into())
187 //! impl<'a> dot::GraphWalk<'a> for Graph {
189 //! type Edge = Ed<'a>;
190 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
191 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
192 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
193 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
196 //! # pub fn main() { render_to(&mut Vec::new()) }
200 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
202 //! use std::fs::File;
203 //! let mut f = File::create("example2.dot").unwrap();
204 //! render_to(&mut f)
208 //! The third example is similar to the second, except now each node and
209 //! edge now carries a reference to the string label for each node as well
210 //! as that node's index. (This is another illustration of how to share
211 //! structure with the graph itself, and why one might want to do so.)
213 //! The output from this example is the same as the second example: the
214 //! Hasse-diagram for the subsets of the set `{x, y}`.
217 //! #![feature(rustc_private)]
219 //! use std::io::Write;
220 //! use graphviz as dot;
222 //! type Nd<'a> = (usize, &'a str);
223 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
224 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
226 //! pub fn render_to<W: Write>(output: &mut W) {
227 //! let nodes = vec!["{x,y}","{x}","{y}","{}"];
228 //! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
229 //! let graph = Graph { nodes: nodes, edges: edges };
231 //! dot::render(&graph, output).unwrap()
234 //! impl<'a> dot::Labeller<'a> for Graph {
235 //! type Node = Nd<'a>;
236 //! type Edge = Ed<'a>;
237 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
238 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
239 //! dot::Id::new(format!("N{}", n.0)).unwrap()
241 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
243 //! dot::LabelText::LabelStr(self.nodes[i].into())
245 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
246 //! dot::LabelText::LabelStr("⊆".into())
250 //! impl<'a> dot::GraphWalk<'a> for Graph {
251 //! type Node = Nd<'a>;
252 //! type Edge = Ed<'a>;
253 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
254 //! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
256 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
257 //! self.edges.iter()
258 //! .map(|&(i,j)|((i, &self.nodes[i][..]),
259 //! (j, &self.nodes[j][..])))
262 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
263 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
266 //! # pub fn main() { render_to(&mut Vec::new()) }
270 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
272 //! use std::fs::File;
273 //! let mut f = File::create("example3.dot").unwrap();
274 //! render_to(&mut f)
280 //! * [Graphviz](http://www.graphviz.org/)
282 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
284 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
285 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
286 html_root_url = "https://doc.rust-lang.org/nightly/",
287 test(attr(allow(unused_variables), deny(warnings))))]
290 #![feature(str_escape)]
292 use self::LabelText::*;
294 use std::borrow::Cow;
295 use std::io::prelude::*;
298 /// The text for a graphviz label on a node or edge.
299 pub enum LabelText<'a> {
300 /// This kind of label preserves the text directly as is.
302 /// Occurrences of backslashes (`\`) are escaped, and thus appear
303 /// as backslashes in the rendered label.
304 LabelStr(Cow<'a, str>),
306 /// This kind of label uses the graphviz label escString type:
307 /// <http://www.graphviz.org/content/attrs#kescString>
309 /// Occurrences of backslashes (`\`) are not escaped; instead they
310 /// are interpreted as initiating an escString escape sequence.
312 /// Escape sequences of particular interest: in addition to `\n`
313 /// to break a line (centering the line preceding the `\n`), there
314 /// are also the escape sequences `\l` which left-justifies the
315 /// preceding line and `\r` which right-justifies it.
316 EscStr(Cow<'a, str>),
318 /// This uses a graphviz [HTML string label][html]. The string is
319 /// printed exactly as given, but between `<` and `>`. **No
320 /// escaping is performed.**
322 /// [html]: http://www.graphviz.org/content/node-shapes#html
323 HtmlStr(Cow<'a, str>),
326 /// The style for a node or edge.
327 /// See <http://www.graphviz.org/doc/info/attrs.html#k:style> for descriptions.
328 /// Note that some of these are not valid for edges.
329 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
344 pub fn as_slice(self) -> &'static str {
347 Style::Solid => "solid",
348 Style::Dashed => "dashed",
349 Style::Dotted => "dotted",
350 Style::Bold => "bold",
351 Style::Rounded => "rounded",
352 Style::Diagonals => "diagonals",
353 Style::Filled => "filled",
354 Style::Striped => "striped",
355 Style::Wedged => "wedged",
360 // There is a tension in the design of the labelling API.
362 // For example, I considered making a `Labeller<T>` trait that
363 // provides labels for `T`, and then making the graph type `G`
364 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
365 // not possible without functional dependencies. (One could work
366 // around that, but I did not explore that avenue heavily.)
368 // Another approach that I actually used for a while was to make a
369 // `Label<Context>` trait that is implemented by the client-specific
370 // Node and Edge types (as well as an implementation on Graph itself
371 // for the overall name for the graph). The main disadvantage of this
372 // second approach (compared to having the `G` type parameter
373 // implement a Labelling service) that I have encountered is that it
374 // makes it impossible to use types outside of the current crate
375 // directly as Nodes/Edges; you need to wrap them in newtype'd
376 // structs. See e.g., the `No` and `Ed` structs in the examples. (In
377 // practice clients using a graph in some other crate would need to
378 // provide some sort of adapter shim over the graph anyway to
379 // interface with this library).
381 // Another approach would be to make a single `Labeller<N,E>` trait
382 // that provides three methods (graph_label, node_label, edge_label),
383 // and then make `G` implement `Labeller<N,E>`. At first this did not
384 // appeal to me, since I had thought I would need separate methods on
385 // each data variant for dot-internal identifiers versus user-visible
386 // labels. However, the identifier/label distinction only arises for
387 // nodes; graphs themselves only have identifiers, and edges only have
390 // So in the end I decided to use the third approach described above.
392 /// `Id` is a Graphviz `ID`.
398 /// Creates an `Id` named `name`.
400 /// The caller must ensure that the input conforms to an
401 /// identifier format: it must be a non-empty string made up of
402 /// alphanumeric or underscore characters, not beginning with a
403 /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
405 /// (Note: this format is a strict subset of the `ID` format
406 /// defined by the DOT language. This function may change in the
407 /// future to accept a broader subset, or the entirety, of DOT's
410 /// Passing an invalid string (containing spaces, brackets,
411 /// quotes, ...) will return an empty `Err` value.
412 pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, ()> {
413 let name = name.into();
414 match name.chars().next() {
415 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
418 if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' ) {
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> {
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: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
502 pub fn escaped<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
506 pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
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()
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())
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[..])?;
699 use self::NodeLabels::*;
700 use super::{Id, Labeller, Nodes, Edges, GraphWalk, render, Style};
701 use super::LabelText::{self, LabelStr, EscStr, HtmlStr};
703 use std::io::prelude::*;
705 /// each node is an index in a vector in the graph.
714 fn edge(from: usize, to: usize, label: &'static str, style: Style) -> Edge {
723 struct LabelledGraph {
724 /// The name for this graph. Used for labeling generated `digraph`.
727 /// Each node is an index into `node_labels`; these labels are
728 /// used as the label text for each node. (The node *names*,
729 /// which are unique identifiers, are derived from their index
732 /// If a node maps to None here, then just use its name as its
734 node_labels: Vec<Option<&'static str>>,
736 node_styles: Vec<Style>,
738 /// Each edge relates a from-index to a to-index along with a
739 /// label; `edges` collects them.
743 // A simple wrapper around LabelledGraph that forces the labels to
744 // be emitted as EscStr.
745 struct LabelledGraphWithEscStrs {
746 graph: LabelledGraph,
750 AllNodesLabelled(Vec<L>),
751 UnlabelledNodes(usize),
752 SomeNodesLabelled(Vec<Option<L>>),
755 type Trivial = NodeLabels<&'static str>;
757 impl NodeLabels<&'static str> {
758 fn to_opt_strs(self) -> Vec<Option<&'static str>> {
760 UnlabelledNodes(len) => vec![None; len],
761 AllNodesLabelled(lbls) => lbls.into_iter().map(|l| Some(l)).collect(),
762 SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
766 fn len(&self) -> usize {
768 &UnlabelledNodes(len) => len,
769 &AllNodesLabelled(ref lbls) => lbls.len(),
770 &SomeNodesLabelled(ref lbls) => lbls.len(),
776 fn new(name: &'static str,
777 node_labels: Trivial,
779 node_styles: Option<Vec<Style>>)
781 let count = node_labels.len();
784 node_labels: node_labels.to_opt_strs(),
786 node_styles: match node_styles {
787 Some(nodes) => nodes,
788 None => vec![Style::None; count],
794 impl LabelledGraphWithEscStrs {
795 fn new(name: &'static str,
796 node_labels: Trivial,
798 -> LabelledGraphWithEscStrs {
799 LabelledGraphWithEscStrs { graph: LabelledGraph::new(name, node_labels, edges, None) }
803 fn id_name<'a>(n: &Node) -> Id<'a> {
804 Id::new(format!("N{}", *n)).unwrap()
807 impl<'a> Labeller<'a> for LabelledGraph {
809 type Edge = &'a Edge;
810 fn graph_id(&'a self) -> Id<'a> {
811 Id::new(self.name).unwrap()
813 fn node_id(&'a self, n: &Node) -> Id<'a> {
816 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
817 match self.node_labels[*n] {
818 Some(l) => LabelStr(l.into()),
819 None => LabelStr(id_name(n).name()),
822 fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
823 LabelStr(e.label.into())
825 fn node_style(&'a self, n: &Node) -> Style {
828 fn edge_style(&'a self, e: &&'a Edge) -> Style {
833 impl<'a> Labeller<'a> for LabelledGraphWithEscStrs {
835 type Edge = &'a Edge;
836 fn graph_id(&'a self) -> Id<'a> {
837 self.graph.graph_id()
839 fn node_id(&'a self, n: &Node) -> Id<'a> {
840 self.graph.node_id(n)
842 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
843 match self.graph.node_label(n) {
844 LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
847 fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
848 match self.graph.edge_label(e) {
849 LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
854 impl<'a> GraphWalk<'a> for LabelledGraph {
856 type Edge = &'a Edge;
857 fn nodes(&'a self) -> Nodes<'a, Node> {
858 (0..self.node_labels.len()).collect()
860 fn edges(&'a self) -> Edges<'a, &'a Edge> {
861 self.edges.iter().collect()
863 fn source(&'a self, edge: &&'a Edge) -> Node {
866 fn target(&'a self, edge: &&'a Edge) -> Node {
871 impl<'a> GraphWalk<'a> for LabelledGraphWithEscStrs {
873 type Edge = &'a Edge;
874 fn nodes(&'a self) -> Nodes<'a, Node> {
877 fn edges(&'a self) -> Edges<'a, &'a Edge> {
880 fn source(&'a self, edge: &&'a Edge) -> Node {
883 fn target(&'a self, edge: &&'a Edge) -> Node {
888 fn test_input(g: LabelledGraph) -> io::Result<String> {
889 let mut writer = Vec::new();
890 render(&g, &mut writer).unwrap();
891 let mut s = String::new();
892 Read::read_to_string(&mut &*writer, &mut s)?;
896 // All of the tests use raw-strings as the format for the expected outputs,
897 // so that you can cut-and-paste the content into a .dot file yourself to
898 // see what the graphviz visualizer would produce.
902 let labels: Trivial = UnlabelledNodes(0);
903 let r = test_input(LabelledGraph::new("empty_graph", labels, vec![], None));
904 assert_eq!(r.unwrap(),
905 r#"digraph empty_graph {
912 let labels: Trivial = UnlabelledNodes(1);
913 let r = test_input(LabelledGraph::new("single_node", labels, vec![], None));
914 assert_eq!(r.unwrap(),
915 r#"digraph single_node {
922 fn single_node_with_style() {
923 let labels: Trivial = UnlabelledNodes(1);
924 let styles = Some(vec![Style::Dashed]);
925 let r = test_input(LabelledGraph::new("single_node", labels, vec![], styles));
926 assert_eq!(r.unwrap(),
927 r#"digraph single_node {
928 N0[label="N0"][style="dashed"];
935 let labels: Trivial = UnlabelledNodes(2);
936 let result = test_input(LabelledGraph::new("single_edge",
938 vec![edge(0, 1, "E", Style::None)],
940 assert_eq!(result.unwrap(),
941 r#"digraph single_edge {
950 fn single_edge_with_style() {
951 let labels: Trivial = UnlabelledNodes(2);
952 let result = test_input(LabelledGraph::new("single_edge",
954 vec![edge(0, 1, "E", Style::Bold)],
956 assert_eq!(result.unwrap(),
957 r#"digraph single_edge {
960 N0 -> N1[label="E"][style="bold"];
966 fn test_some_labelled() {
967 let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
968 let styles = Some(vec![Style::None, Style::Dotted]);
969 let result = test_input(LabelledGraph::new("test_some_labelled",
971 vec![edge(0, 1, "A-1", Style::None)],
973 assert_eq!(result.unwrap(),
974 r#"digraph test_some_labelled {
976 N1[label="N1"][style="dotted"];
977 N0 -> N1[label="A-1"];
983 fn single_cyclic_node() {
984 let labels: Trivial = UnlabelledNodes(1);
985 let r = test_input(LabelledGraph::new("single_cyclic_node",
987 vec![edge(0, 0, "E", Style::None)],
989 assert_eq!(r.unwrap(),
990 r#"digraph single_cyclic_node {
999 let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
1000 let r = test_input(LabelledGraph::new("hasse_diagram",
1002 vec![edge(0, 1, "", Style::None),
1003 edge(0, 2, "", Style::None),
1004 edge(1, 3, "", Style::None),
1005 edge(2, 3, "", Style::None)],
1007 assert_eq!(r.unwrap(),
1008 r#"digraph hasse_diagram {
1022 fn left_aligned_text() {
1023 let labels = AllNodesLabelled(vec![
1035 let mut writer = Vec::new();
1037 let g = LabelledGraphWithEscStrs::new("syntax_tree",
1039 vec![edge(0, 1, "then", Style::None),
1040 edge(0, 2, "else", Style::None),
1041 edge(1, 3, ";", Style::None),
1042 edge(2, 3, ";", Style::None)]);
1044 render(&g, &mut writer).unwrap();
1045 let mut r = String::new();
1046 Read::read_to_string(&mut &*writer, &mut r).unwrap();
1049 r#"digraph syntax_tree {
1050 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
1051 N1[label="branch1"];
1052 N2[label="branch2"];
1053 N3[label="afterward"];
1054 N0 -> N1[label="then"];
1055 N0 -> N2[label="else"];
1056 N1 -> N3[label=";"];
1057 N2 -> N3[label=";"];
1063 fn simple_id_construction() {
1064 let id1 = Id::new("hello");
1067 Err(..) => panic!("'hello' is not a valid value for id anymore"),
1072 fn badly_formatted_id() {
1073 let id2 = Id::new("Weird { struct : ure } !!!");
1075 Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),