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 //! use std::borrow::IntoCow;
51 //! use graphviz as dot;
54 //! type Ed = (int,int);
55 //! struct Edges(Vec<Ed>);
57 //! pub fn render_to<W:Writer>(output: &mut W) {
58 //! let edges = Edges(vec!((0,1), (0,2), (1,3), (2,3), (3,4), (4,4)));
59 //! dot::render(&edges, output).unwrap()
62 //! impl<'a> dot::Labeller<'a, Nd, Ed> for Edges {
63 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
65 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
66 //! dot::Id::new(format!("N{}", *n)).unwrap()
70 //! impl<'a> dot::GraphWalk<'a, Nd, Ed> for Edges {
71 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
72 //! // (assumes that |N| \approxeq |E|)
73 //! let &Edges(ref v) = self;
74 //! let mut nodes = Vec::with_capacity(v.len());
75 //! for &(s,t) in v.iter() {
76 //! nodes.push(s); nodes.push(t);
83 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
84 //! let &Edges(ref edges) = self;
85 //! edges.as_slice().into_cow()
88 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
90 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
93 //! # pub fn main() { render_to(&mut Vec::new()) }
97 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
99 //! use std::old_io::File;
100 //! let mut f = File::create(&Path::new("example1.dot"));
101 //! render_to(&mut f)
105 //! Output from first example (in `example1.dot`):
108 //! digraph example1 {
114 //! N0 -> N1[label=""];
115 //! N0 -> N2[label=""];
116 //! N1 -> N3[label=""];
117 //! N2 -> N3[label=""];
118 //! N3 -> N4[label=""];
119 //! N4 -> N4[label=""];
123 //! The second example illustrates using `node_label` and `edge_label` to
124 //! add labels to the nodes and edges in the rendered graph. The graph
125 //! here carries both `nodes` (the label text to use for rendering a
126 //! particular node), and `edges` (again a list of `(source,target)`
129 //! This example also illustrates how to use a type (in this case the edge
130 //! type) that shares substructure with the graph: the edge type here is a
131 //! direct reference to the `(source,target)` pair stored in the graph's
132 //! internal vector (rather than passing around a copy of the pair
133 //! itself). Note that this implies that `fn edges(&'a self)` must
134 //! construct a fresh `Vec<&'a (uint,uint)>` from the `Vec<(uint,uint)>`
135 //! edges stored in `self`.
137 //! Since both the set of nodes and the set of edges are always
138 //! constructed from scratch via iterators, we use the `collect()` method
139 //! from the `Iterator` trait to collect the nodes and edges into freshly
140 //! constructed growable `Vec` values (rather use the `into_cow`
141 //! from the `IntoCow` trait as was used in the first example
144 //! The output from this example renders four nodes that make up the
145 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
146 //! labelled with the ⊆ character (specified using the HTML character
150 //! use std::borrow::IntoCow;
151 //! use graphviz as dot;
154 //! type Ed<'a> = &'a (uint, uint);
155 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
157 //! pub fn render_to<W:Writer>(output: &mut W) {
158 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
159 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
160 //! let graph = Graph { nodes: nodes, edges: edges };
162 //! dot::render(&graph, output).unwrap()
165 //! impl<'a> dot::Labeller<'a, Nd, Ed<'a>> for Graph {
166 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
167 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
168 //! dot::Id::new(format!("N{}", n)).unwrap()
170 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
171 //! dot::LabelText::LabelStr(self.nodes[*n].as_slice().into_cow())
173 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
174 //! dot::LabelText::LabelStr("⊆".into_cow())
178 //! impl<'a> dot::GraphWalk<'a, Nd, Ed<'a>> for Graph {
179 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
180 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
181 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
182 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
185 //! # pub fn main() { render_to(&mut Vec::new()) }
189 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
191 //! use std::old_io::File;
192 //! let mut f = File::create(&Path::new("example2.dot"));
193 //! render_to(&mut f)
197 //! The third example is similar to the second, except now each node and
198 //! edge now carries a reference to the string label for each node as well
199 //! as that node's index. (This is another illustration of how to share
200 //! structure with the graph itself, and why one might want to do so.)
202 //! The output from this example is the same as the second example: the
203 //! Hasse-diagram for the subsets of the set `{x, y}`.
206 //! use std::borrow::IntoCow;
207 //! use graphviz as dot;
209 //! type Nd<'a> = (uint, &'a str);
210 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
211 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
213 //! pub fn render_to<W:Writer>(output: &mut W) {
214 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
215 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
216 //! let graph = Graph { nodes: nodes, edges: edges };
218 //! dot::render(&graph, output).unwrap()
221 //! impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph {
222 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
223 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
224 //! dot::Id::new(format!("N{}", n.0)).unwrap()
226 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
228 //! dot::LabelText::LabelStr(self.nodes[i].as_slice().into_cow())
230 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
231 //! dot::LabelText::LabelStr("⊆".into_cow())
235 //! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
236 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
237 //! self.nodes.iter().map(|s|s.as_slice()).enumerate().collect()
239 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
240 //! self.edges.iter()
241 //! .map(|&(i,j)|((i, self.nodes[i].as_slice()),
242 //! (j, self.nodes[j].as_slice())))
245 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
246 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
249 //! # pub fn main() { render_to(&mut Vec::new()) }
253 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
255 //! use std::old_io::File;
256 //! let mut f = File::create(&Path::new("example3.dot"));
257 //! render_to(&mut f)
263 //! * [Graphviz](http://www.graphviz.org/)
265 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
267 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
268 #![cfg_attr(stage0, feature(custom_attribute))]
269 #![crate_name = "graphviz"]
270 #![unstable(feature = "rustc_private")]
271 #![feature(staged_api)]
273 #![crate_type = "rlib"]
274 #![crate_type = "dylib"]
275 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
276 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
277 html_root_url = "http://doc.rust-lang.org/nightly/")]
278 #![feature(int_uint)]
279 #![feature(collections)]
282 use self::LabelText::*;
284 use std::borrow::{IntoCow, Cow};
287 /// The text for a graphviz label on a node or edge.
288 pub enum LabelText<'a> {
289 /// This kind of label preserves the text directly as is.
291 /// Occurrences of backslashes (`\`) are escaped, and thus appear
292 /// as backslashes in the rendered label.
293 LabelStr(Cow<'a, str>),
295 /// This kind of label uses the graphviz label escString type:
296 /// http://www.graphviz.org/content/attrs#kescString
298 /// Occurrences of backslashes (`\`) are not escaped; instead they
299 /// are interpreted as initiating an escString escape sequence.
301 /// Escape sequences of particular interest: in addition to `\n`
302 /// to break a line (centering the line preceding the `\n`), there
303 /// are also the escape sequences `\l` which left-justifies the
304 /// preceding line and `\r` which right-justifies it.
305 EscStr(Cow<'a, str>),
308 // There is a tension in the design of the labelling API.
310 // For example, I considered making a `Labeller<T>` trait that
311 // provides labels for `T`, and then making the graph type `G`
312 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
313 // not possible without functional dependencies. (One could work
314 // around that, but I did not explore that avenue heavily.)
316 // Another approach that I actually used for a while was to make a
317 // `Label<Context>` trait that is implemented by the client-specific
318 // Node and Edge types (as well as an implementation on Graph itself
319 // for the overall name for the graph). The main disadvantage of this
320 // second approach (compared to having the `G` type parameter
321 // implement a Labelling service) that I have encountered is that it
322 // makes it impossible to use types outside of the current crate
323 // directly as Nodes/Edges; you need to wrap them in newtype'd
324 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
325 // practice clients using a graph in some other crate would need to
326 // provide some sort of adapter shim over the graph anyway to
327 // interface with this library).
329 // Another approach would be to make a single `Labeller<N,E>` trait
330 // that provides three methods (graph_label, node_label, edge_label),
331 // and then make `G` implement `Labeller<N,E>`. At first this did not
332 // appeal to me, since I had thought I would need separate methods on
333 // each data variant for dot-internal identifiers versus user-visible
334 // labels. However, the identifier/label distinction only arises for
335 // nodes; graphs themselves only have identifiers, and edges only have
338 // So in the end I decided to use the third approach described above.
340 /// `Id` is a Graphviz `ID`.
346 /// Creates an `Id` named `name`.
348 /// The caller must ensure that the input conforms to an
349 /// identifier format: it must be a non-empty string made up of
350 /// alphanumeric or underscore characters, not beginning with a
351 /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
353 /// (Note: this format is a strict subset of the `ID` format
354 /// defined by the DOT language. This function may change in the
355 /// future to accept a broader subset, or the entirety, of DOT's
358 /// Passing an invalid string (containing spaces, brackets,
359 /// quotes, ...) will return an empty `Err` value.
360 pub fn new<Name: IntoCow<'a, str>>(name: Name) -> Result<Id<'a>, ()> {
361 let name = name.into_cow();
363 let mut chars = name.chars();
365 Some(c) if is_letter_or_underscore(c) => { ; },
368 if !chars.all(is_constituent) {
372 return Ok(Id{ name: name });
374 fn is_letter_or_underscore(c: char) -> bool {
375 in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
377 fn is_constituent(c: char) -> bool {
378 is_letter_or_underscore(c) || in_range('0', c, '9')
380 fn in_range(low: char, c: char, high: char) -> bool {
381 low as uint <= c as uint && c as uint <= high as uint
385 pub fn as_slice(&'a self) -> &'a str {
389 pub fn name(self) -> Cow<'a, str> {
394 /// Each instance of a type that implements `Label<C>` maps to a
395 /// unique identifier with respect to `C`, which is used to identify
396 /// it in the generated .dot file. They can also provide more
397 /// elaborate (and non-unique) label text that is used in the graphviz
400 /// The graph instance is responsible for providing the DOT compatible
401 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
402 /// edges, as well as an identifier for the graph itself.
403 pub trait Labeller<'a,N,E> {
404 /// Must return a DOT compatible identifier naming the graph.
405 fn graph_id(&'a self) -> Id<'a>;
407 /// Maps `n` to a unique identifier with respect to `self`. The
408 /// implementer is responsible for ensuring that the returned name
409 /// is a valid DOT identifier.
410 fn node_id(&'a self, n: &N) -> Id<'a>;
412 /// Maps `n` to a label that will be used in the rendered output.
413 /// The label need not be unique, and may be the empty string; the
414 /// default is just the output from `node_id`.
415 fn node_label(&'a self, n: &N) -> LabelText<'a> {
416 LabelStr(self.node_id(n).name)
419 /// Maps `e` to a label that will be used in the rendered output.
420 /// The label need not be unique, and may be the empty string; the
421 /// default is in fact the empty string.
422 fn edge_label(&'a self, e: &E) -> LabelText<'a> {
424 LabelStr("".into_cow())
428 impl<'a> LabelText<'a> {
429 pub fn label<S:IntoCow<'a, str>>(s: S) -> LabelText<'a> {
430 LabelStr(s.into_cow())
433 pub fn escaped<S:IntoCow<'a, str>>(s: S) -> LabelText<'a> {
437 fn escape_char<F>(c: char, mut f: F) where F: FnMut(char) {
439 // not escaping \\, since Graphviz escString needs to
440 // interpret backslashes; see EscStr above.
442 _ => for c in c.escape_default() { f(c) }
445 fn escape_str(s: &str) -> String {
446 let mut out = String::with_capacity(s.len());
448 LabelText::escape_char(c, |c| out.push(c));
453 /// Renders text as string suitable for a label in a .dot file.
454 pub fn escape(&self) -> String {
456 &LabelStr(ref s) => s.escape_default(),
457 &EscStr(ref s) => LabelText::escape_str(&s[..]),
461 /// Decomposes content into string suitable for making EscStr that
462 /// yields same content as self. The result obeys the law
463 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
464 /// all `lt: LabelText`.
465 fn pre_escaped_content(self) -> Cow<'a, str> {
468 LabelStr(s) => if s.contains('\\') {
469 (&*s).escape_default().into_cow()
476 /// Puts `prefix` on a line above this label, with a blank line separator.
477 pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
478 prefix.suffix_line(self)
481 /// Puts `suffix` on a line below this label, with a blank line separator.
482 pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
483 let mut prefix = self.pre_escaped_content().into_owned();
484 let suffix = suffix.pre_escaped_content();
485 prefix.push_str(r"\n\n");
486 prefix.push_str(&suffix[..]);
487 EscStr(prefix.into_cow())
491 pub type Nodes<'a,N> = Cow<'a,[N]>;
492 pub type Edges<'a,E> = Cow<'a,[E]>;
494 // (The type parameters in GraphWalk should be associated items,
495 // when/if Rust supports such.)
497 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
498 /// made up of node handles `N` and edge handles `E`, where each `E`
499 /// can be mapped to its source and target nodes.
501 /// The lifetime parameter `'a` is exposed in this trait (rather than
502 /// introduced as a generic parameter on each method declaration) so
503 /// that a client impl can choose `N` and `E` that have substructure
504 /// that is bound by the self lifetime `'a`.
506 /// The `nodes` and `edges` method each return instantiations of
507 /// `Cow<[T]>` to leave implementers the freedom to create
508 /// entirely new vectors or to pass back slices into internally owned
510 pub trait GraphWalk<'a, N, E> {
511 /// Returns all the nodes in this graph.
512 fn nodes(&'a self) -> Nodes<'a, N>;
513 /// Returns all of the edges in this graph.
514 fn edges(&'a self) -> Edges<'a, E>;
515 /// The source node for `edge`.
516 fn source(&'a self, edge: &E) -> N;
517 /// The target node for `edge`.
518 fn target(&'a self, edge: &E) -> N;
521 #[derive(Copy, PartialEq, Eq, Debug)]
522 pub enum RenderOption {
527 /// Returns vec holding all the default render options.
528 pub fn default_options() -> Vec<RenderOption> { vec![] }
530 /// Renders directed graph `g` into the writer `w` in DOT syntax.
531 /// (Simple wrapper around `render_opts` that passes a default set of options.)
532 pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>(
534 w: &mut W) -> old_io::IoResult<()> {
535 render_opts(g, w, &[])
538 /// Renders directed graph `g` into the writer `w` in DOT syntax.
539 /// (Main entry point for the library.)
540 pub fn render_opts<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>(
543 options: &[RenderOption]) -> old_io::IoResult<()>
545 fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> old_io::IoResult<()> {
546 for &s in arg { try!(w.write_str(s)); }
550 fn indent<W:Writer>(w: &mut W) -> old_io::IoResult<()> {
554 try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"]));
555 for n in &*g.nodes() {
557 let id = g.node_id(n);
558 if options.contains(&RenderOption::NoNodeLabels) {
559 try!(writeln(w, &[id.as_slice(), ";"]));
561 let escaped = g.node_label(n).escape();
562 try!(writeln(w, &[id.as_slice(),
563 "[label=\"", &escaped, "\"];"]));
567 for e in &*g.edges() {
568 let escaped_label = g.edge_label(e).escape();
570 let source = g.source(e);
571 let target = g.target(e);
572 let source_id = g.node_id(&source);
573 let target_id = g.node_id(&target);
574 if options.contains(&RenderOption::NoEdgeLabels) {
575 try!(writeln(w, &[source_id.as_slice(),
576 " -> ", target_id.as_slice(), ";"]));
578 try!(writeln(w, &[source_id.as_slice(),
579 " -> ", target_id.as_slice(),
580 "[label=\"", &escaped_label, "\"];"]));
589 use self::NodeLabels::*;
590 use super::{Id, Labeller, Nodes, Edges, GraphWalk, render};
591 use super::LabelText::{self, LabelStr, EscStr};
592 use std::old_io::IoResult;
593 use std::borrow::IntoCow;
594 use std::iter::repeat;
596 /// each node is an index in a vector in the graph.
599 from: uint, to: uint, label: &'static str
602 fn edge(from: uint, to: uint, label: &'static str) -> Edge {
603 Edge { from: from, to: to, label: label }
606 struct LabelledGraph {
607 /// The name for this graph. Used for labelling generated `digraph`.
610 /// Each node is an index into `node_labels`; these labels are
611 /// used as the label text for each node. (The node *names*,
612 /// which are unique identifiers, are derived from their index
615 /// If a node maps to None here, then just use its name as its
617 node_labels: Vec<Option<&'static str>>,
619 /// Each edge relates a from-index to a to-index along with a
620 /// label; `edges` collects them.
624 // A simple wrapper around LabelledGraph that forces the labels to
625 // be emitted as EscStr.
626 struct LabelledGraphWithEscStrs {
631 AllNodesLabelled(Vec<L>),
632 UnlabelledNodes(uint),
633 SomeNodesLabelled(Vec<Option<L>>),
636 type Trivial = NodeLabels<&'static str>;
638 impl NodeLabels<&'static str> {
639 fn to_opt_strs(self) -> Vec<Option<&'static str>> {
642 => repeat(None).take(len).collect(),
643 AllNodesLabelled(lbls)
644 => lbls.into_iter().map(
645 |l|Some(l)).collect(),
646 SomeNodesLabelled(lbls)
647 => lbls.into_iter().collect(),
653 fn new(name: &'static str,
654 node_labels: Trivial,
655 edges: Vec<Edge>) -> LabelledGraph {
658 node_labels: node_labels.to_opt_strs(),
664 impl LabelledGraphWithEscStrs {
665 fn new(name: &'static str,
666 node_labels: Trivial,
667 edges: Vec<Edge>) -> LabelledGraphWithEscStrs {
668 LabelledGraphWithEscStrs {
669 graph: LabelledGraph::new(name, node_labels, edges)
674 fn id_name<'a>(n: &Node) -> Id<'a> {
675 Id::new(format!("N{}", *n)).unwrap()
678 impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
679 fn graph_id(&'a self) -> Id<'a> {
680 Id::new(&self.name[..]).unwrap()
682 fn node_id(&'a self, n: &Node) -> Id<'a> {
685 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
686 match self.node_labels[*n] {
687 Some(ref l) => LabelStr(l.into_cow()),
688 None => LabelStr(id_name(n).name()),
691 fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
692 LabelStr(e.label.into_cow())
696 impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
697 fn graph_id(&'a self) -> Id<'a> { self.graph.graph_id() }
698 fn node_id(&'a self, n: &Node) -> Id<'a> { self.graph.node_id(n) }
699 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
700 match self.graph.node_label(n) {
701 LabelStr(s) | EscStr(s) => EscStr(s),
704 fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
705 match self.graph.edge_label(e) {
706 LabelStr(s) | EscStr(s) => EscStr(s),
711 impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
712 fn nodes(&'a self) -> Nodes<'a,Node> {
713 (0..self.node_labels.len()).collect()
715 fn edges(&'a self) -> Edges<'a,&'a Edge> {
716 self.edges.iter().collect()
718 fn source(&'a self, edge: & &'a Edge) -> Node {
721 fn target(&'a self, edge: & &'a Edge) -> Node {
726 impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
727 fn nodes(&'a self) -> Nodes<'a,Node> {
730 fn edges(&'a self) -> Edges<'a,&'a Edge> {
733 fn source(&'a self, edge: & &'a Edge) -> Node {
736 fn target(&'a self, edge: & &'a Edge) -> Node {
741 fn test_input(g: LabelledGraph) -> IoResult<String> {
742 let mut writer = Vec::new();
743 render(&g, &mut writer).unwrap();
744 (&mut &*writer).read_to_string()
747 // All of the tests use raw-strings as the format for the expected outputs,
748 // so that you can cut-and-paste the content into a .dot file yourself to
749 // see what the graphviz visualizer would produce.
753 let labels : Trivial = UnlabelledNodes(0);
754 let r = test_input(LabelledGraph::new("empty_graph", labels, vec!()));
755 assert_eq!(r.unwrap(),
756 r#"digraph empty_graph {
763 let labels : Trivial = UnlabelledNodes(1);
764 let r = test_input(LabelledGraph::new("single_node", labels, vec!()));
765 assert_eq!(r.unwrap(),
766 r#"digraph single_node {
774 let labels : Trivial = UnlabelledNodes(2);
775 let result = test_input(LabelledGraph::new("single_edge", labels,
776 vec!(edge(0, 1, "E"))));
777 assert_eq!(result.unwrap(),
778 r#"digraph single_edge {
787 fn test_some_labelled() {
788 let labels : Trivial = SomeNodesLabelled(vec![Some("A"), None]);
789 let result = test_input(LabelledGraph::new("test_some_labelled", labels,
790 vec![edge(0, 1, "A-1")]));
791 assert_eq!(result.unwrap(),
792 r#"digraph test_some_labelled {
795 N0 -> N1[label="A-1"];
801 fn single_cyclic_node() {
802 let labels : Trivial = UnlabelledNodes(1);
803 let r = test_input(LabelledGraph::new("single_cyclic_node", labels,
804 vec!(edge(0, 0, "E"))));
805 assert_eq!(r.unwrap(),
806 r#"digraph single_cyclic_node {
815 let labels = AllNodesLabelled(vec!("{x,y}", "{x}", "{y}", "{}"));
816 let r = test_input(LabelledGraph::new(
817 "hasse_diagram", labels,
818 vec!(edge(0, 1, ""), edge(0, 2, ""),
819 edge(1, 3, ""), edge(2, 3, ""))));
820 assert_eq!(r.unwrap(),
821 r#"digraph hasse_diagram {
835 fn left_aligned_text() {
836 let labels = AllNodesLabelled(vec!(
848 let mut writer = Vec::new();
850 let g = LabelledGraphWithEscStrs::new(
851 "syntax_tree", labels,
852 vec!(edge(0, 1, "then"), edge(0, 2, "else"),
853 edge(1, 3, ";"), edge(2, 3, ";" )));
855 render(&g, &mut writer).unwrap();
856 let r = (&mut &*writer).read_to_string();
858 assert_eq!(r.unwrap(),
859 r#"digraph syntax_tree {
860 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
863 N3[label="afterward"];
864 N0 -> N1[label="then"];
865 N0 -> N2[label="else"];
873 fn simple_id_construction() {
874 let id1 = Id::new("hello");
877 Err(..) => panic!("'hello' is not a valid value for id anymore")
882 fn badly_formatted_id() {
883 let id2 = Id::new("Weird { struct : ure } !!!");
885 Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),