1 // Copyright 2014 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 labelled
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, core, into_cow)]
51 //! use std::borrow::IntoCow;
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, Nd, Ed> for Edges {
65 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
67 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
68 //! dot::Id::new(format!("N{}", *n)).unwrap()
72 //! impl<'a> dot::GraphWalk<'a, Nd, Ed> for Edges {
73 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
74 //! // (assumes that |N| \approxeq |E|)
75 //! let &Edges(ref v) = self;
76 //! let mut nodes = Vec::with_capacity(v.len());
77 //! for &(s,t) in v.iter() {
78 //! nodes.push(s); nodes.push(t);
85 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
86 //! let &Edges(ref edges) = self;
87 //! (&edges[..]).into_cow()
90 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
92 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
95 //! # pub fn main() { render_to(&mut Vec::new()) }
99 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
101 //! use std::fs::File;
102 //! let mut f = File::create("example1.dot").unwrap();
103 //! render_to(&mut f)
107 //! Output from first example (in `example1.dot`):
110 //! digraph example1 {
116 //! N0 -> N1[label=""];
117 //! N0 -> N2[label=""];
118 //! N1 -> N3[label=""];
119 //! N2 -> N3[label=""];
120 //! N3 -> N4[label=""];
121 //! N4 -> N4[label=""];
125 //! The second example illustrates using `node_label` and `edge_label` to
126 //! add labels to the nodes and edges in the rendered graph. The graph
127 //! here carries both `nodes` (the label text to use for rendering a
128 //! particular node), and `edges` (again a list of `(source,target)`
131 //! This example also illustrates how to use a type (in this case the edge
132 //! type) that shares substructure with the graph: the edge type here is a
133 //! direct reference to the `(source,target)` pair stored in the graph's
134 //! internal vector (rather than passing around a copy of the pair
135 //! itself). Note that this implies that `fn edges(&'a self)` must
136 //! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
137 //! edges stored in `self`.
139 //! Since both the set of nodes and the set of edges are always
140 //! constructed from scratch via iterators, we use the `collect()` method
141 //! from the `Iterator` trait to collect the nodes and edges into freshly
142 //! constructed growable `Vec` values (rather use the `into_cow`
143 //! from the `IntoCow` trait as was used in the first example
146 //! The output from this example renders four nodes that make up the
147 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
148 //! labelled with the ⊆ character (specified using the HTML character
152 //! # #![feature(rustc_private, core, into_cow)]
153 //! use std::borrow::IntoCow;
154 //! use std::io::Write;
155 //! use graphviz as dot;
158 //! type Ed<'a> = &'a (usize, usize);
159 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
161 //! pub fn render_to<W: Write>(output: &mut W) {
162 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
163 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
164 //! let graph = Graph { nodes: nodes, edges: edges };
166 //! dot::render(&graph, output).unwrap()
169 //! impl<'a> dot::Labeller<'a, Nd, Ed<'a>> for Graph {
170 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
171 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
172 //! dot::Id::new(format!("N{}", n)).unwrap()
174 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
175 //! dot::LabelText::LabelStr(self.nodes[*n].as_slice().into_cow())
177 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
178 //! dot::LabelText::LabelStr("⊆".into_cow())
182 //! impl<'a> dot::GraphWalk<'a, Nd, Ed<'a>> for Graph {
183 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
184 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
185 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
186 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
189 //! # pub fn main() { render_to(&mut Vec::new()) }
193 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
195 //! use std::fs::File;
196 //! let mut f = File::create("example2.dot").unwrap();
197 //! render_to(&mut f)
201 //! The third example is similar to the second, except now each node and
202 //! edge now carries a reference to the string label for each node as well
203 //! as that node's index. (This is another illustration of how to share
204 //! structure with the graph itself, and why one might want to do so.)
206 //! The output from this example is the same as the second example: the
207 //! Hasse-diagram for the subsets of the set `{x, y}`.
210 //! # #![feature(rustc_private, core, into_cow)]
211 //! use std::borrow::IntoCow;
212 //! use std::io::Write;
213 //! use graphviz as dot;
215 //! type Nd<'a> = (usize, &'a str);
216 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
217 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
219 //! pub fn render_to<W: Write>(output: &mut W) {
220 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
221 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
222 //! let graph = Graph { nodes: nodes, edges: edges };
224 //! dot::render(&graph, output).unwrap()
227 //! impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph {
228 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
229 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
230 //! dot::Id::new(format!("N{}", n.0)).unwrap()
232 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
234 //! dot::LabelText::LabelStr(self.nodes[i].into_cow())
236 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
237 //! dot::LabelText::LabelStr("⊆".into_cow())
241 //! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
242 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
243 //! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
245 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
246 //! self.edges.iter()
247 //! .map(|&(i,j)|((i, &self.nodes[i][..]),
248 //! (j, &self.nodes[j][..])))
251 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
252 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
255 //! # pub fn main() { render_to(&mut Vec::new()) }
259 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
261 //! use std::fs::File;
262 //! let mut f = File::create("example3.dot").unwrap();
263 //! render_to(&mut f)
269 //! * [Graphviz](http://www.graphviz.org/)
271 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
273 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
274 #![cfg_attr(stage0, feature(custom_attribute))]
275 #![crate_name = "graphviz"]
276 #![unstable(feature = "rustc_private")]
277 #![feature(staged_api)]
279 #![crate_type = "rlib"]
280 #![crate_type = "dylib"]
281 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
282 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
283 html_root_url = "http://doc.rust-lang.org/nightly/")]
284 #![feature(collections)]
285 #![feature(into_cow)]
287 use self::LabelText::*;
289 use std::borrow::{IntoCow, Cow};
290 use std::io::prelude::*;
293 /// The text for a graphviz label on a node or edge.
294 pub enum LabelText<'a> {
295 /// This kind of label preserves the text directly as is.
297 /// Occurrences of backslashes (`\`) are escaped, and thus appear
298 /// as backslashes in the rendered label.
299 LabelStr(Cow<'a, str>),
301 /// This kind of label uses the graphviz label escString type:
302 /// http://www.graphviz.org/content/attrs#kescString
304 /// Occurrences of backslashes (`\`) are not escaped; instead they
305 /// are interpreted as initiating an escString escape sequence.
307 /// Escape sequences of particular interest: in addition to `\n`
308 /// to break a line (centering the line preceding the `\n`), there
309 /// are also the escape sequences `\l` which left-justifies the
310 /// preceding line and `\r` which right-justifies it.
311 EscStr(Cow<'a, str>),
314 // There is a tension in the design of the labelling API.
316 // For example, I considered making a `Labeller<T>` trait that
317 // provides labels for `T`, and then making the graph type `G`
318 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
319 // not possible without functional dependencies. (One could work
320 // around that, but I did not explore that avenue heavily.)
322 // Another approach that I actually used for a while was to make a
323 // `Label<Context>` trait that is implemented by the client-specific
324 // Node and Edge types (as well as an implementation on Graph itself
325 // for the overall name for the graph). The main disadvantage of this
326 // second approach (compared to having the `G` type parameter
327 // implement a Labelling service) that I have encountered is that it
328 // makes it impossible to use types outside of the current crate
329 // directly as Nodes/Edges; you need to wrap them in newtype'd
330 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
331 // practice clients using a graph in some other crate would need to
332 // provide some sort of adapter shim over the graph anyway to
333 // interface with this library).
335 // Another approach would be to make a single `Labeller<N,E>` trait
336 // that provides three methods (graph_label, node_label, edge_label),
337 // and then make `G` implement `Labeller<N,E>`. At first this did not
338 // appeal to me, since I had thought I would need separate methods on
339 // each data variant for dot-internal identifiers versus user-visible
340 // labels. However, the identifier/label distinction only arises for
341 // nodes; graphs themselves only have identifiers, and edges only have
344 // So in the end I decided to use the third approach described above.
346 /// `Id` is a Graphviz `ID`.
352 /// Creates an `Id` named `name`.
354 /// The caller must ensure that the input conforms to an
355 /// identifier format: it must be a non-empty string made up of
356 /// alphanumeric or underscore characters, not beginning with a
357 /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
359 /// (Note: this format is a strict subset of the `ID` format
360 /// defined by the DOT language. This function may change in the
361 /// future to accept a broader subset, or the entirety, of DOT's
364 /// Passing an invalid string (containing spaces, brackets,
365 /// quotes, ...) will return an empty `Err` value.
366 pub fn new<Name: IntoCow<'a, str>>(name: Name) -> Result<Id<'a>, ()> {
367 let name = name.into_cow();
369 let mut chars = name.chars();
371 Some(c) if is_letter_or_underscore(c) => { ; },
374 if !chars.all(is_constituent) {
378 return Ok(Id{ name: name });
380 fn is_letter_or_underscore(c: char) -> bool {
381 in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
383 fn is_constituent(c: char) -> bool {
384 is_letter_or_underscore(c) || in_range('0', c, '9')
386 fn in_range(low: char, c: char, high: char) -> bool {
387 low as usize <= c as usize && c as usize <= high as usize
391 pub fn as_slice(&'a self) -> &'a str {
395 pub fn name(self) -> Cow<'a, str> {
400 /// Each instance of a type that implements `Label<C>` maps to a
401 /// unique identifier with respect to `C`, which is used to identify
402 /// it in the generated .dot file. They can also provide more
403 /// elaborate (and non-unique) label text that is used in the graphviz
406 /// The graph instance is responsible for providing the DOT compatible
407 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
408 /// edges, as well as an identifier for the graph itself.
409 pub trait Labeller<'a,N,E> {
410 /// Must return a DOT compatible identifier naming the graph.
411 fn graph_id(&'a self) -> Id<'a>;
413 /// Maps `n` to a unique identifier with respect to `self`. The
414 /// implementer is responsible for ensuring that the returned name
415 /// is a valid DOT identifier.
416 fn node_id(&'a self, n: &N) -> Id<'a>;
418 /// Maps `n` to a label that will be used in the rendered output.
419 /// The label need not be unique, and may be the empty string; the
420 /// default is just the output from `node_id`.
421 fn node_label(&'a self, n: &N) -> LabelText<'a> {
422 LabelStr(self.node_id(n).name)
425 /// Maps `e` to a label that will be used in the rendered output.
426 /// The label need not be unique, and may be the empty string; the
427 /// default is in fact the empty string.
428 fn edge_label(&'a self, e: &E) -> LabelText<'a> {
430 LabelStr("".into_cow())
434 impl<'a> LabelText<'a> {
435 pub fn label<S:IntoCow<'a, str>>(s: S) -> LabelText<'a> {
436 LabelStr(s.into_cow())
439 pub fn escaped<S:IntoCow<'a, str>>(s: S) -> LabelText<'a> {
443 fn escape_char<F>(c: char, mut f: F) where F: FnMut(char) {
445 // not escaping \\, since Graphviz escString needs to
446 // interpret backslashes; see EscStr above.
448 _ => for c in c.escape_default() { f(c) }
451 fn escape_str(s: &str) -> String {
452 let mut out = String::with_capacity(s.len());
454 LabelText::escape_char(c, |c| out.push(c));
459 /// Renders text as string suitable for a label in a .dot file.
460 pub fn escape(&self) -> String {
462 &LabelStr(ref s) => s.escape_default(),
463 &EscStr(ref s) => LabelText::escape_str(&s[..]),
467 /// Decomposes content into string suitable for making EscStr that
468 /// yields same content as self. The result obeys the law
469 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
470 /// all `lt: LabelText`.
471 fn pre_escaped_content(self) -> Cow<'a, str> {
474 LabelStr(s) => if s.contains('\\') {
475 (&*s).escape_default().into_cow()
482 /// Puts `prefix` on a line above this label, with a blank line separator.
483 pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
484 prefix.suffix_line(self)
487 /// Puts `suffix` on a line below this label, with a blank line separator.
488 pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
489 let mut prefix = self.pre_escaped_content().into_owned();
490 let suffix = suffix.pre_escaped_content();
491 prefix.push_str(r"\n\n");
492 prefix.push_str(&suffix[..]);
493 EscStr(prefix.into_cow())
497 pub type Nodes<'a,N> = Cow<'a,[N]>;
498 pub type Edges<'a,E> = Cow<'a,[E]>;
500 // (The type parameters in GraphWalk should be associated items,
501 // when/if Rust supports such.)
503 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
504 /// made up of node handles `N` and edge handles `E`, where each `E`
505 /// can be mapped to its source and target nodes.
507 /// The lifetime parameter `'a` is exposed in this trait (rather than
508 /// introduced as a generic parameter on each method declaration) so
509 /// that a client impl can choose `N` and `E` that have substructure
510 /// that is bound by the self lifetime `'a`.
512 /// The `nodes` and `edges` method each return instantiations of
513 /// `Cow<[T]>` to leave implementers the freedom to create
514 /// entirely new vectors or to pass back slices into internally owned
516 pub trait GraphWalk<'a, N, E> {
517 /// Returns all the nodes in this graph.
518 fn nodes(&'a self) -> Nodes<'a, N>;
519 /// Returns all of the edges in this graph.
520 fn edges(&'a self) -> Edges<'a, E>;
521 /// The source node for `edge`.
522 fn source(&'a self, edge: &E) -> N;
523 /// The target node for `edge`.
524 fn target(&'a self, edge: &E) -> N;
527 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
528 pub enum RenderOption {
533 /// Returns vec holding all the default render options.
534 pub fn default_options() -> Vec<RenderOption> { vec![] }
536 /// Renders directed graph `g` into the writer `w` in DOT syntax.
537 /// (Simple wrapper around `render_opts` that passes a default set of options.)
538 pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Write>(
540 w: &mut W) -> io::Result<()> {
541 render_opts(g, w, &[])
544 /// Renders directed graph `g` into the writer `w` in DOT syntax.
545 /// (Main entry point for the library.)
546 pub fn render_opts<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Write>(
549 options: &[RenderOption]) -> io::Result<()>
551 fn writeln<W:Write>(w: &mut W, arg: &[&str]) -> io::Result<()> {
552 for &s in arg { try!(w.write_all(s.as_bytes())); }
556 fn indent<W:Write>(w: &mut W) -> io::Result<()> {
560 try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"]));
561 for n in &*g.nodes() {
563 let id = g.node_id(n);
564 if options.contains(&RenderOption::NoNodeLabels) {
565 try!(writeln(w, &[id.as_slice(), ";"]));
567 let escaped = g.node_label(n).escape();
568 try!(writeln(w, &[id.as_slice(),
569 "[label=\"", &escaped, "\"];"]));
573 for e in &*g.edges() {
574 let escaped_label = g.edge_label(e).escape();
576 let source = g.source(e);
577 let target = g.target(e);
578 let source_id = g.node_id(&source);
579 let target_id = g.node_id(&target);
580 if options.contains(&RenderOption::NoEdgeLabels) {
581 try!(writeln(w, &[source_id.as_slice(),
582 " -> ", target_id.as_slice(), ";"]));
584 try!(writeln(w, &[source_id.as_slice(),
585 " -> ", target_id.as_slice(),
586 "[label=\"", &escaped_label, "\"];"]));
595 use self::NodeLabels::*;
596 use super::{Id, Labeller, Nodes, Edges, GraphWalk, render};
597 use super::LabelText::{self, LabelStr, EscStr};
599 use std::io::prelude::*;
600 use std::borrow::IntoCow;
601 use std::iter::repeat;
603 /// each node is an index in a vector in the graph.
606 from: usize, to: usize, label: &'static str
609 fn edge(from: usize, to: usize, label: &'static str) -> Edge {
610 Edge { from: from, to: to, label: label }
613 struct LabelledGraph {
614 /// The name for this graph. Used for labelling generated `digraph`.
617 /// Each node is an index into `node_labels`; these labels are
618 /// used as the label text for each node. (The node *names*,
619 /// which are unique identifiers, are derived from their index
622 /// If a node maps to None here, then just use its name as its
624 node_labels: Vec<Option<&'static str>>,
626 /// Each edge relates a from-index to a to-index along with a
627 /// label; `edges` collects them.
631 // A simple wrapper around LabelledGraph that forces the labels to
632 // be emitted as EscStr.
633 struct LabelledGraphWithEscStrs {
638 AllNodesLabelled(Vec<L>),
639 UnlabelledNodes(usize),
640 SomeNodesLabelled(Vec<Option<L>>),
643 type Trivial = NodeLabels<&'static str>;
645 impl NodeLabels<&'static str> {
646 fn to_opt_strs(self) -> Vec<Option<&'static str>> {
649 => repeat(None).take(len).collect(),
650 AllNodesLabelled(lbls)
651 => lbls.into_iter().map(
652 |l|Some(l)).collect(),
653 SomeNodesLabelled(lbls)
654 => lbls.into_iter().collect(),
660 fn new(name: &'static str,
661 node_labels: Trivial,
662 edges: Vec<Edge>) -> LabelledGraph {
665 node_labels: node_labels.to_opt_strs(),
671 impl LabelledGraphWithEscStrs {
672 fn new(name: &'static str,
673 node_labels: Trivial,
674 edges: Vec<Edge>) -> LabelledGraphWithEscStrs {
675 LabelledGraphWithEscStrs {
676 graph: LabelledGraph::new(name, node_labels, edges)
681 fn id_name<'a>(n: &Node) -> Id<'a> {
682 Id::new(format!("N{}", *n)).unwrap()
685 impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
686 fn graph_id(&'a self) -> Id<'a> {
687 Id::new(&self.name[..]).unwrap()
689 fn node_id(&'a self, n: &Node) -> Id<'a> {
692 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
693 match self.node_labels[*n] {
694 Some(ref l) => LabelStr(l.into_cow()),
695 None => LabelStr(id_name(n).name()),
698 fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
699 LabelStr(e.label.into_cow())
703 impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
704 fn graph_id(&'a self) -> Id<'a> { self.graph.graph_id() }
705 fn node_id(&'a self, n: &Node) -> Id<'a> { self.graph.node_id(n) }
706 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
707 match self.graph.node_label(n) {
708 LabelStr(s) | EscStr(s) => EscStr(s),
711 fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
712 match self.graph.edge_label(e) {
713 LabelStr(s) | EscStr(s) => EscStr(s),
718 impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
719 fn nodes(&'a self) -> Nodes<'a,Node> {
720 (0..self.node_labels.len()).collect()
722 fn edges(&'a self) -> Edges<'a,&'a Edge> {
723 self.edges.iter().collect()
725 fn source(&'a self, edge: & &'a Edge) -> Node {
728 fn target(&'a self, edge: & &'a Edge) -> Node {
733 impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
734 fn nodes(&'a self) -> Nodes<'a,Node> {
737 fn edges(&'a self) -> Edges<'a,&'a Edge> {
740 fn source(&'a self, edge: & &'a Edge) -> Node {
743 fn target(&'a self, edge: & &'a Edge) -> Node {
748 fn test_input(g: LabelledGraph) -> io::Result<String> {
749 let mut writer = Vec::new();
750 render(&g, &mut writer).unwrap();
751 let mut s = String::new();
752 try!(Read::read_to_string(&mut &*writer, &mut s));
756 // All of the tests use raw-strings as the format for the expected outputs,
757 // so that you can cut-and-paste the content into a .dot file yourself to
758 // see what the graphviz visualizer would produce.
762 let labels : Trivial = UnlabelledNodes(0);
763 let r = test_input(LabelledGraph::new("empty_graph", labels, vec!()));
764 assert_eq!(r.unwrap(),
765 r#"digraph empty_graph {
772 let labels : Trivial = UnlabelledNodes(1);
773 let r = test_input(LabelledGraph::new("single_node", labels, vec!()));
774 assert_eq!(r.unwrap(),
775 r#"digraph single_node {
783 let labels : Trivial = UnlabelledNodes(2);
784 let result = test_input(LabelledGraph::new("single_edge", labels,
785 vec!(edge(0, 1, "E"))));
786 assert_eq!(result.unwrap(),
787 r#"digraph single_edge {
796 fn test_some_labelled() {
797 let labels : Trivial = SomeNodesLabelled(vec![Some("A"), None]);
798 let result = test_input(LabelledGraph::new("test_some_labelled", labels,
799 vec![edge(0, 1, "A-1")]));
800 assert_eq!(result.unwrap(),
801 r#"digraph test_some_labelled {
804 N0 -> N1[label="A-1"];
810 fn single_cyclic_node() {
811 let labels : Trivial = UnlabelledNodes(1);
812 let r = test_input(LabelledGraph::new("single_cyclic_node", labels,
813 vec!(edge(0, 0, "E"))));
814 assert_eq!(r.unwrap(),
815 r#"digraph single_cyclic_node {
824 let labels = AllNodesLabelled(vec!("{x,y}", "{x}", "{y}", "{}"));
825 let r = test_input(LabelledGraph::new(
826 "hasse_diagram", labels,
827 vec!(edge(0, 1, ""), edge(0, 2, ""),
828 edge(1, 3, ""), edge(2, 3, ""))));
829 assert_eq!(r.unwrap(),
830 r#"digraph hasse_diagram {
844 fn left_aligned_text() {
845 let labels = AllNodesLabelled(vec!(
857 let mut writer = Vec::new();
859 let g = LabelledGraphWithEscStrs::new(
860 "syntax_tree", labels,
861 vec!(edge(0, 1, "then"), edge(0, 2, "else"),
862 edge(1, 3, ";"), edge(2, 3, ";" )));
864 render(&g, &mut writer).unwrap();
865 let mut r = String::new();
866 Read::read_to_string(&mut &*writer, &mut r).unwrap();
869 r#"digraph syntax_tree {
870 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
873 N3[label="afterward"];
874 N0 -> N1[label="then"];
875 N0 -> N2[label="else"];
883 fn simple_id_construction() {
884 let id1 = Id::new("hello");
887 Err(..) => panic!("'hello' is not a valid value for id anymore")
892 fn badly_formatted_id() {
893 let id2 = Id::new("Weird { struct : ure } !!!");
895 Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),