]> git.lizzy.rs Git - rust.git/blob - src/libgraphviz/lib.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[rust.git] / src / libgraphviz / lib.rs
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.
4 //
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.
10
11 //! Generate files suitable for use with [Graphviz](http://www.graphviz.org/)
12 //!
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.)
19 //!
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.
23 //!
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.
32 //!
33 //! # Examples
34 //!
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.
39 //!
40 //! This example also illustrates how to use `CowVec` 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).
44 //!
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
47 //! which is cyclic.
48 //!
49 //! ```rust
50 //! use graphviz as dot;
51 //!
52 //! type Nd = int;
53 //! type Ed = (int,int);
54 //! struct Edges(Vec<Ed>);
55 //!
56 //! pub fn render_to<W:Writer>(output: &mut W) {
57 //!     let edges = Edges(vec!((0,1), (0,2), (1,3), (2,3), (3,4), (4,4)));
58 //!     dot::render(&edges, output).unwrap()
59 //! }
60 //!
61 //! impl<'a> dot::Labeller<'a, Nd, Ed> for Edges {
62 //!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
63 //!
64 //!     fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
65 //!         dot::Id::new(format!("N{}", *n)).unwrap()
66 //!     }
67 //! }
68 //!
69 //! impl<'a> dot::GraphWalk<'a, Nd, Ed> for Edges {
70 //!     fn nodes(&self) -> dot::Nodes<'a,Nd> {
71 //!         // (assumes that |N| \approxeq |E|)
72 //!         let &Edges(ref v) = self;
73 //!         let mut nodes = Vec::with_capacity(v.len());
74 //!         for &(s,t) in v.iter() {
75 //!             nodes.push(s); nodes.push(t);
76 //!         }
77 //!         nodes.sort();
78 //!         nodes.dedup();
79 //!         nodes.into_cow()
80 //!     }
81 //!
82 //!     fn edges(&'a self) -> dot::Edges<'a,Ed> {
83 //!         let &Edges(ref edges) = self;
84 //!         edges.as_slice().into_cow()
85 //!     }
86 //!
87 //!     fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
88 //!
89 //!     fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
90 //! }
91 //!
92 //! # pub fn main() { render_to(&mut Vec::new()) }
93 //! ```
94 //!
95 //! ```no_run
96 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
97 //! pub fn main() {
98 //!     use std::io::File;
99 //!     let mut f = File::create(&Path::new("example1.dot"));
100 //!     render_to(&mut f)
101 //! }
102 //! ```
103 //!
104 //! Output from first example (in `example1.dot`):
105 //!
106 //! ```ignore
107 //! digraph example1 {
108 //!     N0[label="N0"];
109 //!     N1[label="N1"];
110 //!     N2[label="N2"];
111 //!     N3[label="N3"];
112 //!     N4[label="N4"];
113 //!     N0 -> N1[label=""];
114 //!     N0 -> N2[label=""];
115 //!     N1 -> N3[label=""];
116 //!     N2 -> N3[label=""];
117 //!     N3 -> N4[label=""];
118 //!     N4 -> N4[label=""];
119 //! }
120 //! ```
121 //!
122 //! The second example illustrates using `node_label` and `edge_label` to
123 //! add labels to the nodes and edges in the rendered graph. The graph
124 //! here carries both `nodes` (the label text to use for rendering a
125 //! particular node), and `edges` (again a list of `(source,target)`
126 //! indices).
127 //!
128 //! This example also illustrates how to use a type (in this case the edge
129 //! type) that shares substructure with the graph: the edge type here is a
130 //! direct reference to the `(source,target)` pair stored in the graph's
131 //! internal vector (rather than passing around a copy of the pair
132 //! itself). Note that this implies that `fn edges(&'a self)` must
133 //! construct a fresh `Vec<&'a (uint,uint)>` from the `Vec<(uint,uint)>`
134 //! edges stored in `self`.
135 //!
136 //! Since both the set of nodes and the set of edges are always
137 //! constructed from scratch via iterators, we use the `collect()` method
138 //! from the `Iterator` trait to collect the nodes and edges into freshly
139 //! constructed growable `Vec` values (rather use the `into_cow`
140 //! from the `IntoCow` trait as was used in the first example
141 //! above).
142 //!
143 //! The output from this example renders four nodes that make up the
144 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
145 //! labelled with the &sube; character (specified using the HTML character
146 //! entity `&sube`).
147 //!
148 //! ```rust
149 //! use graphviz as dot;
150 //!
151 //! type Nd = uint;
152 //! type Ed<'a> = &'a (uint, uint);
153 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
154 //!
155 //! pub fn render_to<W:Writer>(output: &mut W) {
156 //!     let nodes = vec!("{x,y}","{x}","{y}","{}");
157 //!     let edges = vec!((0,1), (0,2), (1,3), (2,3));
158 //!     let graph = Graph { nodes: nodes, edges: edges };
159 //!
160 //!     dot::render(&graph, output).unwrap()
161 //! }
162 //!
163 //! impl<'a> dot::Labeller<'a, Nd, Ed<'a>> for Graph {
164 //!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
165 //!     fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
166 //!         dot::Id::new(format!("N{}", n)).unwrap()
167 //!     }
168 //!     fn node_label<'a>(&'a self, n: &Nd) -> dot::LabelText<'a> {
169 //!         dot::LabelStr(self.nodes[*n].as_slice().into_cow())
170 //!     }
171 //!     fn edge_label<'a>(&'a self, _: &Ed) -> dot::LabelText<'a> {
172 //!         dot::LabelStr("&sube;".into_cow())
173 //!     }
174 //! }
175 //!
176 //! impl<'a> dot::GraphWalk<'a, Nd, Ed<'a>> for Graph {
177 //!     fn nodes(&self) -> dot::Nodes<'a,Nd> { range(0,self.nodes.len()).collect() }
178 //!     fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
179 //!     fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
180 //!     fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
181 //! }
182 //!
183 //! # pub fn main() { render_to(&mut Vec::new()) }
184 //! ```
185 //!
186 //! ```no_run
187 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
188 //! pub fn main() {
189 //!     use std::io::File;
190 //!     let mut f = File::create(&Path::new("example2.dot"));
191 //!     render_to(&mut f)
192 //! }
193 //! ```
194 //!
195 //! The third example is similar to the second, except now each node and
196 //! edge now carries a reference to the string label for each node as well
197 //! as that node's index. (This is another illustration of how to share
198 //! structure with the graph itself, and why one might want to do so.)
199 //!
200 //! The output from this example is the same as the second example: the
201 //! Hasse-diagram for the subsets of the set `{x, y}`.
202 //!
203 //! ```rust
204 //! use graphviz as dot;
205 //!
206 //! type Nd<'a> = (uint, &'a str);
207 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
208 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
209 //!
210 //! pub fn render_to<W:Writer>(output: &mut W) {
211 //!     let nodes = vec!("{x,y}","{x}","{y}","{}");
212 //!     let edges = vec!((0,1), (0,2), (1,3), (2,3));
213 //!     let graph = Graph { nodes: nodes, edges: edges };
214 //!
215 //!     dot::render(&graph, output).unwrap()
216 //! }
217 //!
218 //! impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph {
219 //!     fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
220 //!     fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
221 //!         dot::Id::new(format!("N{}", n.val0())).unwrap()
222 //!     }
223 //!     fn node_label<'a>(&'a self, n: &Nd<'a>) -> dot::LabelText<'a> {
224 //!         let &(i, _) = n;
225 //!         dot::LabelStr(self.nodes[i].as_slice().into_cow())
226 //!     }
227 //!     fn edge_label<'a>(&'a self, _: &Ed<'a>) -> dot::LabelText<'a> {
228 //!         dot::LabelStr("&sube;".into_cow())
229 //!     }
230 //! }
231 //!
232 //! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
233 //!     fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
234 //!         self.nodes.iter().map(|s|s.as_slice()).enumerate().collect()
235 //!     }
236 //!     fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
237 //!         self.edges.iter()
238 //!             .map(|&(i,j)|((i, self.nodes[i].as_slice()),
239 //!                           (j, self.nodes[j].as_slice())))
240 //!             .collect()
241 //!     }
242 //!     fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
243 //!     fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
244 //! }
245 //!
246 //! # pub fn main() { render_to(&mut Vec::new()) }
247 //! ```
248 //!
249 //! ```no_run
250 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
251 //! pub fn main() {
252 //!     use std::io::File;
253 //!     let mut f = File::create(&Path::new("example3.dot"));
254 //!     render_to(&mut f)
255 //! }
256 //! ```
257 //!
258 //! # References
259 //!
260 //! * [Graphviz](http://www.graphviz.org/)
261 //!
262 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
263
264 #![crate_name = "graphviz"]
265 #![experimental]
266 #![crate_type = "rlib"]
267 #![crate_type = "dylib"]
268 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
269        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
270        html_root_url = "http://doc.rust-lang.org/nightly/")]
271 #![feature(globs, slicing_syntax)]
272
273 pub use self::LabelText::*;
274
275 use std::io;
276 use std::str::CowString;
277 use std::vec::CowVec;
278
279 pub mod maybe_owned_vec;
280
281 /// The text for a graphviz label on a node or edge.
282 pub enum LabelText<'a> {
283     /// This kind of label preserves the text directly as is.
284     ///
285     /// Occurrences of backslashes (`\`) are escaped, and thus appear
286     /// as backslashes in the rendered label.
287     LabelStr(CowString<'a>),
288
289     /// This kind of label uses the graphviz label escString type:
290     /// http://www.graphviz.org/content/attrs#kescString
291     ///
292     /// Occurrences of backslashes (`\`) are not escaped; instead they
293     /// are interpreted as initiating an escString escape sequence.
294     ///
295     /// Escape sequences of particular interest: in addition to `\n`
296     /// to break a line (centering the line preceding the `\n`), there
297     /// are also the escape sequences `\l` which left-justifies the
298     /// preceding line and `\r` which right-justifies it.
299     EscStr(CowString<'a>),
300 }
301
302 // There is a tension in the design of the labelling API.
303 //
304 // For example, I considered making a `Labeller<T>` trait that
305 // provides labels for `T`, and then making the graph type `G`
306 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
307 // not possible without functional dependencies. (One could work
308 // around that, but I did not explore that avenue heavily.)
309 //
310 // Another approach that I actually used for a while was to make a
311 // `Label<Context>` trait that is implemented by the client-specific
312 // Node and Edge types (as well as an implementation on Graph itself
313 // for the overall name for the graph). The main disadvantage of this
314 // second approach (compared to having the `G` type parameter
315 // implement a Labelling service) that I have encountered is that it
316 // makes it impossible to use types outside of the current crate
317 // directly as Nodes/Edges; you need to wrap them in newtype'd
318 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
319 // practice clients using a graph in some other crate would need to
320 // provide some sort of adapter shim over the graph anyway to
321 // interface with this library).
322 //
323 // Another approach would be to make a single `Labeller<N,E>` trait
324 // that provides three methods (graph_label, node_label, edge_label),
325 // and then make `G` implement `Labeller<N,E>`. At first this did not
326 // appeal to me, since I had thought I would need separate methods on
327 // each data variant for dot-internal identifiers versus user-visible
328 // labels. However, the identifier/label distinction only arises for
329 // nodes; graphs themselves only have identifiers, and edges only have
330 // labels.
331 //
332 // So in the end I decided to use the third approach described above.
333
334 /// `Id` is a Graphviz `ID`.
335 pub struct Id<'a> {
336     name: CowString<'a>,
337 }
338
339 impl<'a> Id<'a> {
340     /// Creates an `Id` named `name`.
341     ///
342     /// The caller must ensure that the input conforms to an
343     /// identifier format: it must be a non-empty string made up of
344     /// alphanumeric or underscore characters, not beginning with a
345     /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
346     ///
347     /// (Note: this format is a strict subset of the `ID` format
348     /// defined by the DOT language.  This function may change in the
349     /// future to accept a broader subset, or the entirety, of DOT's
350     /// `ID` format.)
351     ///
352     /// Passing an invalid string (containing spaces, brackets,
353     /// quotes, ...) will return an empty `Err` value.
354     pub fn new<Name: IntoCow<'a, String, str>>(name: Name) -> Result<Id<'a>, ()> {
355         let name = name.into_cow();
356         {
357             let mut chars = name.chars();
358             match chars.next() {
359                 Some(c) if is_letter_or_underscore(c) => { ; },
360                 _ => return Err(())
361             }
362             if !chars.all(is_constituent) {
363                 return Err(());
364             }
365         }
366         return Ok(Id{ name: name });
367
368         fn is_letter_or_underscore(c: char) -> bool {
369             in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
370         }
371         fn is_constituent(c: char) -> bool {
372             is_letter_or_underscore(c) || in_range('0', c, '9')
373         }
374         fn in_range(low: char, c: char, high: char) -> bool {
375             low as uint <= c as uint && c as uint <= high as uint
376         }
377     }
378
379     pub fn as_slice(&'a self) -> &'a str {
380         &*self.name
381     }
382
383     pub fn name(self) -> CowString<'a> {
384         self.name
385     }
386 }
387
388 /// Each instance of a type that implements `Label<C>` maps to a
389 /// unique identifier with respect to `C`, which is used to identify
390 /// it in the generated .dot file. They can also provide more
391 /// elaborate (and non-unique) label text that is used in the graphviz
392 /// rendered output.
393
394 /// The graph instance is responsible for providing the DOT compatible
395 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
396 /// edges, as well as an identifier for the graph itself.
397 pub trait Labeller<'a,N,E> {
398     /// Must return a DOT compatible identifier naming the graph.
399     fn graph_id(&'a self) -> Id<'a>;
400
401     /// Maps `n` to a unique identifier with respect to `self`. The
402     /// implementer is responsible for ensuring that the returned name
403     /// is a valid DOT identifier.
404     fn node_id(&'a self, n: &N) -> Id<'a>;
405
406     /// Maps `n` to a label that will be used in the rendered output.
407     /// The label need not be unique, and may be the empty string; the
408     /// default is just the output from `node_id`.
409     fn node_label(&'a self, n: &N) -> LabelText<'a> {
410         LabelStr(self.node_id(n).name)
411     }
412
413     /// Maps `e` to a label that will be used in the rendered output.
414     /// The label need not be unique, and may be the empty string; the
415     /// default is in fact the empty string.
416     fn edge_label(&'a self, e: &E) -> LabelText<'a> {
417         let _ignored = e;
418         LabelStr("".into_cow())
419     }
420 }
421
422 impl<'a> LabelText<'a> {
423     fn escape_char(c: char, f: |char|) {
424         match c {
425             // not escaping \\, since Graphviz escString needs to
426             // interpret backslashes; see EscStr above.
427             '\\' => f(c),
428             _ => for c in c.escape_default() { f(c) }
429         }
430     }
431     fn escape_str(s: &str) -> String {
432         let mut out = String::with_capacity(s.len());
433         for c in s.chars() {
434             LabelText::escape_char(c, |c| out.push(c));
435         }
436         out
437     }
438
439     /// Renders text as string suitable for a label in a .dot file.
440     pub fn escape(&self) -> String {
441         match self {
442             &LabelStr(ref s) => s.escape_default(),
443             &EscStr(ref s) => LabelText::escape_str(s.as_slice()),
444         }
445     }
446
447     /// Decomposes content into string suitable for making EscStr that
448     /// yields same content as self.  The result obeys the law
449     /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
450     /// all `lt: LabelText`.
451     fn pre_escaped_content(self) -> CowString<'a> {
452         match self {
453             EscStr(s) => s,
454             LabelStr(s) => if s.contains_char('\\') {
455                 s.escape_default().into_cow()
456             } else {
457                 s
458             },
459         }
460     }
461
462     /// Puts `prefix` on a line above this label, with a blank line separator.
463     pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
464         prefix.suffix_line(self)
465     }
466
467     /// Puts `suffix` on a line below this label, with a blank line separator.
468     pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
469         let mut prefix = self.pre_escaped_content().into_string();
470         let suffix = suffix.pre_escaped_content();
471         prefix.push_str(r"\n\n");
472         prefix.push_str(suffix.as_slice());
473         EscStr(prefix.into_cow())
474     }
475 }
476
477 pub type Nodes<'a,N> = CowVec<'a,N>;
478 pub type Edges<'a,E> = CowVec<'a,E>;
479
480 // (The type parameters in GraphWalk should be associated items,
481 // when/if Rust supports such.)
482
483 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
484 /// made up of node handles `N` and edge handles `E`, where each `E`
485 /// can be mapped to its source and target nodes.
486 ///
487 /// The lifetime parameter `'a` is exposed in this trait (rather than
488 /// introduced as a generic parameter on each method declaration) so
489 /// that a client impl can choose `N` and `E` that have substructure
490 /// that is bound by the self lifetime `'a`.
491 ///
492 /// The `nodes` and `edges` method each return instantiations of
493 /// `CowVec` to leave implementers the freedom to create
494 /// entirely new vectors or to pass back slices into internally owned
495 /// vectors.
496 pub trait GraphWalk<'a, N, E> {
497     /// Returns all the nodes in this graph.
498     fn nodes(&'a self) -> Nodes<'a, N>;
499     /// Returns all of the edges in this graph.
500     fn edges(&'a self) -> Edges<'a, E>;
501     /// The source node for `edge`.
502     fn source(&'a self, edge: &E) -> N;
503     /// The target node for `edge`.
504     fn target(&'a self, edge: &E) -> N;
505 }
506
507 /// Renders directed graph `g` into the writer `w` in DOT syntax.
508 /// (Main entry point for the library.)
509 pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>(
510               g: &'a G,
511               w: &mut W) -> io::IoResult<()>
512 {
513     fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> io::IoResult<()> {
514         for &s in arg.iter() { try!(w.write_str(s)); }
515         w.write_char('\n')
516     }
517
518     fn indent<W:Writer>(w: &mut W) -> io::IoResult<()> {
519         w.write_str("    ")
520     }
521
522     try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"]));
523     for n in g.nodes().iter() {
524         try!(indent(w));
525         let id = g.node_id(n);
526         let escaped = g.node_label(n).escape();
527         try!(writeln(w, &[id.as_slice(),
528                           "[label=\"", escaped.as_slice(), "\"];"]));
529     }
530
531     for e in g.edges().iter() {
532         let escaped_label = g.edge_label(e).escape();
533         try!(indent(w));
534         let source = g.source(e);
535         let target = g.target(e);
536         let source_id = g.node_id(&source);
537         let target_id = g.node_id(&target);
538         try!(writeln(w, &[source_id.as_slice(), " -> ", target_id.as_slice(),
539                           "[label=\"", escaped_label.as_slice(), "\"];"]));
540     }
541
542     writeln(w, &["}"])
543 }
544
545 #[cfg(test)]
546 mod tests {
547     use self::NodeLabels::*;
548     use super::{Id, LabelText, LabelStr, EscStr, Labeller};
549     use super::{Nodes, Edges, GraphWalk, render};
550     use std::io::IoResult;
551     use std::str;
552
553     /// each node is an index in a vector in the graph.
554     type Node = uint;
555     struct Edge {
556         from: uint, to: uint, label: &'static str
557     }
558
559     fn edge(from: uint, to: uint, label: &'static str) -> Edge {
560         Edge { from: from, to: to, label: label }
561     }
562
563     struct LabelledGraph {
564         /// The name for this graph. Used for labelling generated `digraph`.
565         name: &'static str,
566
567         /// Each node is an index into `node_labels`; these labels are
568         /// used as the label text for each node. (The node *names*,
569         /// which are unique identifiers, are derived from their index
570         /// in this array.)
571         ///
572         /// If a node maps to None here, then just use its name as its
573         /// text.
574         node_labels: Vec<Option<&'static str>>,
575
576         /// Each edge relates a from-index to a to-index along with a
577         /// label; `edges` collects them.
578         edges: Vec<Edge>,
579     }
580
581     // A simple wrapper around LabelledGraph that forces the labels to
582     // be emitted as EscStr.
583     struct LabelledGraphWithEscStrs {
584         graph: LabelledGraph
585     }
586
587     enum NodeLabels<L> {
588         AllNodesLabelled(Vec<L>),
589         UnlabelledNodes(uint),
590         SomeNodesLabelled(Vec<Option<L>>),
591     }
592
593     type Trivial = NodeLabels<&'static str>;
594
595     impl NodeLabels<&'static str> {
596         fn to_opt_strs(self) -> Vec<Option<&'static str>> {
597             match self {
598                 UnlabelledNodes(len)
599                     => Vec::from_elem(len, None).into_iter().collect(),
600                 AllNodesLabelled(lbls)
601                     => lbls.into_iter().map(
602                         |l|Some(l)).collect(),
603                 SomeNodesLabelled(lbls)
604                     => lbls.into_iter().collect(),
605             }
606         }
607     }
608
609     impl LabelledGraph {
610         fn new(name: &'static str,
611                node_labels: Trivial,
612                edges: Vec<Edge>) -> LabelledGraph {
613             LabelledGraph {
614                 name: name,
615                 node_labels: node_labels.to_opt_strs(),
616                 edges: edges
617             }
618         }
619     }
620
621     impl LabelledGraphWithEscStrs {
622         fn new(name: &'static str,
623                node_labels: Trivial,
624                edges: Vec<Edge>) -> LabelledGraphWithEscStrs {
625             LabelledGraphWithEscStrs {
626                 graph: LabelledGraph::new(name, node_labels, edges)
627             }
628         }
629     }
630
631     fn id_name<'a>(n: &Node) -> Id<'a> {
632         Id::new(format!("N{}", *n)).unwrap()
633     }
634
635     impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
636         fn graph_id(&'a self) -> Id<'a> {
637             Id::new(self.name.as_slice()).unwrap()
638         }
639         fn node_id(&'a self, n: &Node) -> Id<'a> {
640             id_name(n)
641         }
642         fn node_label(&'a self, n: &Node) -> LabelText<'a> {
643             match self.node_labels[*n] {
644                 Some(ref l) => LabelStr(l.into_cow()),
645                 None        => LabelStr(id_name(n).name()),
646             }
647         }
648         fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
649             LabelStr(e.label.into_cow())
650         }
651     }
652
653     impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
654         fn graph_id(&'a self) -> Id<'a> { self.graph.graph_id() }
655         fn node_id(&'a self, n: &Node) -> Id<'a> { self.graph.node_id(n) }
656         fn node_label(&'a self, n: &Node) -> LabelText<'a> {
657             match self.graph.node_label(n) {
658                 LabelStr(s) | EscStr(s) => EscStr(s),
659             }
660         }
661         fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
662             match self.graph.edge_label(e) {
663                 LabelStr(s) | EscStr(s) => EscStr(s),
664             }
665         }
666     }
667
668     impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
669         fn nodes(&'a self) -> Nodes<'a,Node> {
670             range(0u, self.node_labels.len()).collect()
671         }
672         fn edges(&'a self) -> Edges<'a,&'a Edge> {
673             self.edges.iter().collect()
674         }
675         fn source(&'a self, edge: & &'a Edge) -> Node {
676             edge.from
677         }
678         fn target(&'a self, edge: & &'a Edge) -> Node {
679             edge.to
680         }
681     }
682
683     impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
684         fn nodes(&'a self) -> Nodes<'a,Node> {
685             self.graph.nodes()
686         }
687         fn edges(&'a self) -> Edges<'a,&'a Edge> {
688             self.graph.edges()
689         }
690         fn source(&'a self, edge: & &'a Edge) -> Node {
691             edge.from
692         }
693         fn target(&'a self, edge: & &'a Edge) -> Node {
694             edge.to
695         }
696     }
697
698     fn test_input(g: LabelledGraph) -> IoResult<String> {
699         let mut writer = Vec::new();
700         render(&g, &mut writer).unwrap();
701         (&mut writer.as_slice()).read_to_string()
702     }
703
704     // All of the tests use raw-strings as the format for the expected outputs,
705     // so that you can cut-and-paste the content into a .dot file yourself to
706     // see what the graphviz visualizer would produce.
707
708     #[test]
709     fn empty_graph() {
710         let labels : Trivial = UnlabelledNodes(0);
711         let r = test_input(LabelledGraph::new("empty_graph", labels, vec!()));
712         assert_eq!(r.unwrap(),
713 r#"digraph empty_graph {
714 }
715 "#);
716     }
717
718     #[test]
719     fn single_node() {
720         let labels : Trivial = UnlabelledNodes(1);
721         let r = test_input(LabelledGraph::new("single_node", labels, vec!()));
722         assert_eq!(r.unwrap(),
723 r#"digraph single_node {
724     N0[label="N0"];
725 }
726 "#);
727     }
728
729     #[test]
730     fn single_edge() {
731         let labels : Trivial = UnlabelledNodes(2);
732         let result = test_input(LabelledGraph::new("single_edge", labels,
733                                                    vec!(edge(0, 1, "E"))));
734         assert_eq!(result.unwrap(),
735 r#"digraph single_edge {
736     N0[label="N0"];
737     N1[label="N1"];
738     N0 -> N1[label="E"];
739 }
740 "#);
741     }
742
743     #[test]
744     fn test_some_labelled() {
745         let labels : Trivial = SomeNodesLabelled(vec![Some("A"), None]);
746         let result = test_input(LabelledGraph::new("test_some_labelled", labels,
747                                                    vec![edge(0, 1, "A-1")]));
748         assert_eq!(result.unwrap(),
749 r#"digraph test_some_labelled {
750     N0[label="A"];
751     N1[label="N1"];
752     N0 -> N1[label="A-1"];
753 }
754 "#);
755     }
756
757     #[test]
758     fn single_cyclic_node() {
759         let labels : Trivial = UnlabelledNodes(1);
760         let r = test_input(LabelledGraph::new("single_cyclic_node", labels,
761                                               vec!(edge(0, 0, "E"))));
762         assert_eq!(r.unwrap(),
763 r#"digraph single_cyclic_node {
764     N0[label="N0"];
765     N0 -> N0[label="E"];
766 }
767 "#);
768     }
769
770     #[test]
771     fn hasse_diagram() {
772         let labels = AllNodesLabelled(vec!("{x,y}", "{x}", "{y}", "{}"));
773         let r = test_input(LabelledGraph::new(
774             "hasse_diagram", labels,
775             vec!(edge(0, 1, ""), edge(0, 2, ""),
776                  edge(1, 3, ""), edge(2, 3, ""))));
777         assert_eq!(r.unwrap(),
778 r#"digraph hasse_diagram {
779     N0[label="{x,y}"];
780     N1[label="{x}"];
781     N2[label="{y}"];
782     N3[label="{}"];
783     N0 -> N1[label=""];
784     N0 -> N2[label=""];
785     N1 -> N3[label=""];
786     N2 -> N3[label=""];
787 }
788 "#);
789     }
790
791     #[test]
792     fn left_aligned_text() {
793         let labels = AllNodesLabelled(vec!(
794             "if test {\
795            \\l    branch1\
796            \\l} else {\
797            \\l    branch2\
798            \\l}\
799            \\lafterward\
800            \\l",
801             "branch1",
802             "branch2",
803             "afterward"));
804
805         let mut writer = Vec::new();
806
807         let g = LabelledGraphWithEscStrs::new(
808             "syntax_tree", labels,
809             vec!(edge(0, 1, "then"), edge(0, 2, "else"),
810                  edge(1, 3, ";"),    edge(2, 3, ";"   )));
811
812         render(&g, &mut writer).unwrap();
813         let r = (&mut writer.as_slice()).read_to_string();
814
815         assert_eq!(r.unwrap(),
816 r#"digraph syntax_tree {
817     N0[label="if test {\l    branch1\l} else {\l    branch2\l}\lafterward\l"];
818     N1[label="branch1"];
819     N2[label="branch2"];
820     N3[label="afterward"];
821     N0 -> N1[label="then"];
822     N0 -> N2[label="else"];
823     N1 -> N3[label=";"];
824     N2 -> N3[label=";"];
825 }
826 "#);
827     }
828
829     #[test]
830     fn simple_id_construction() {
831         let id1 = Id::new("hello");
832         match id1 {
833             Ok(_) => {;},
834             Err(_) => panic!("'hello' is not a valid value for id anymore")
835         }
836     }
837
838     #[test]
839     fn badly_formatted_id() {
840         let id2 = Id::new("Weird { struct : ure } !!!");
841         match id2 {
842             Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
843             Err(_) => {;}
844         }
845     }
846 }