]> git.lizzy.rs Git - rust.git/blob - src/libgraphviz/lib.rs
/*! -> //!
[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 #![license = "MIT/ASL2"]
269 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
270        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
271        html_root_url = "http://doc.rust-lang.org/nightly/")]
272 #![feature(globs, slicing_syntax)]
273
274 pub use self::LabelText::*;
275
276 use std::io;
277 use std::str::CowString;
278 use std::vec::CowVec;
279
280 pub mod maybe_owned_vec;
281
282 /// The text for a graphviz label on a node or edge.
283 pub enum LabelText<'a> {
284     /// This kind of label preserves the text directly as is.
285     ///
286     /// Occurrences of backslashes (`\`) are escaped, and thus appear
287     /// as backslashes in the rendered label.
288     LabelStr(CowString<'a>),
289
290     /// This kind of label uses the graphviz label escString type:
291     /// http://www.graphviz.org/content/attrs#kescString
292     ///
293     /// Occurrences of backslashes (`\`) are not escaped; instead they
294     /// are interpreted as initiating an escString escape sequence.
295     ///
296     /// Escape sequences of particular interest: in addition to `\n`
297     /// to break a line (centering the line preceding the `\n`), there
298     /// are also the escape sequences `\l` which left-justifies the
299     /// preceding line and `\r` which right-justifies it.
300     EscStr(CowString<'a>),
301 }
302
303 // There is a tension in the design of the labelling API.
304 //
305 // For example, I considered making a `Labeller<T>` trait that
306 // provides labels for `T`, and then making the graph type `G`
307 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
308 // not possible without functional dependencies. (One could work
309 // around that, but I did not explore that avenue heavily.)
310 //
311 // Another approach that I actually used for a while was to make a
312 // `Label<Context>` trait that is implemented by the client-specific
313 // Node and Edge types (as well as an implementation on Graph itself
314 // for the overall name for the graph). The main disadvantage of this
315 // second approach (compared to having the `G` type parameter
316 // implement a Labelling service) that I have encountered is that it
317 // makes it impossible to use types outside of the current crate
318 // directly as Nodes/Edges; you need to wrap them in newtype'd
319 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
320 // practice clients using a graph in some other crate would need to
321 // provide some sort of adapter shim over the graph anyway to
322 // interface with this library).
323 //
324 // Another approach would be to make a single `Labeller<N,E>` trait
325 // that provides three methods (graph_label, node_label, edge_label),
326 // and then make `G` implement `Labeller<N,E>`. At first this did not
327 // appeal to me, since I had thought I would need separate methods on
328 // each data variant for dot-internal identifiers versus user-visible
329 // labels. However, the identifier/label distinction only arises for
330 // nodes; graphs themselves only have identifiers, and edges only have
331 // labels.
332 //
333 // So in the end I decided to use the third approach described above.
334
335 /// `Id` is a Graphviz `ID`.
336 pub struct Id<'a> {
337     name: CowString<'a>,
338 }
339
340 impl<'a> Id<'a> {
341     /// Creates an `Id` named `name`.
342     ///
343     /// The caller must ensure that the input conforms to an
344     /// identifier format: it must be a non-empty string made up of
345     /// alphanumeric or underscore characters, not beginning with a
346     /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
347     ///
348     /// (Note: this format is a strict subset of the `ID` format
349     /// defined by the DOT language.  This function may change in the
350     /// future to accept a broader subset, or the entirety, of DOT's
351     /// `ID` format.)
352     ///
353     /// Passing an invalid string (containing spaces, brackets,
354     /// quotes, ...) will return an empty `Err` value.
355     pub fn new<Name: IntoCow<'a, String, str>>(name: Name) -> Result<Id<'a>, ()> {
356         let name = name.into_cow();
357         {
358             let mut chars = name.chars();
359             match chars.next() {
360                 Some(c) if is_letter_or_underscore(c) => { ; },
361                 _ => return Err(())
362             }
363             if !chars.all(is_constituent) {
364                 return Err(());
365             }
366         }
367         return Ok(Id{ name: name });
368
369         fn is_letter_or_underscore(c: char) -> bool {
370             in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
371         }
372         fn is_constituent(c: char) -> bool {
373             is_letter_or_underscore(c) || in_range('0', c, '9')
374         }
375         fn in_range(low: char, c: char, high: char) -> bool {
376             low as uint <= c as uint && c as uint <= high as uint
377         }
378     }
379
380     pub fn as_slice(&'a self) -> &'a str {
381         &*self.name
382     }
383
384     pub fn name(self) -> CowString<'a> {
385         self.name
386     }
387 }
388
389 /// Each instance of a type that implements `Label<C>` maps to a
390 /// unique identifier with respect to `C`, which is used to identify
391 /// it in the generated .dot file. They can also provide more
392 /// elaborate (and non-unique) label text that is used in the graphviz
393 /// rendered output.
394
395 /// The graph instance is responsible for providing the DOT compatible
396 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
397 /// edges, as well as an identifier for the graph itself.
398 pub trait Labeller<'a,N,E> {
399     /// Must return a DOT compatible identifier naming the graph.
400     fn graph_id(&'a self) -> Id<'a>;
401
402     /// Maps `n` to a unique identifier with respect to `self`. The
403     /// implementer is responsible for ensuring that the returned name
404     /// is a valid DOT identifier.
405     fn node_id(&'a self, n: &N) -> Id<'a>;
406
407     /// Maps `n` to a label that will be used in the rendered output.
408     /// The label need not be unique, and may be the empty string; the
409     /// default is just the output from `node_id`.
410     fn node_label(&'a self, n: &N) -> LabelText<'a> {
411         LabelStr(self.node_id(n).name)
412     }
413
414     /// Maps `e` to a label that will be used in the rendered output.
415     /// The label need not be unique, and may be the empty string; the
416     /// default is in fact the empty string.
417     fn edge_label(&'a self, e: &E) -> LabelText<'a> {
418         let _ignored = e;
419         LabelStr("".into_cow())
420     }
421 }
422
423 impl<'a> LabelText<'a> {
424     fn escape_char(c: char, f: |char|) {
425         match c {
426             // not escaping \\, since Graphviz escString needs to
427             // interpret backslashes; see EscStr above.
428             '\\' => f(c),
429             _ => for c in c.escape_default() { f(c) }
430         }
431     }
432     fn escape_str(s: &str) -> String {
433         let mut out = String::with_capacity(s.len());
434         for c in s.chars() {
435             LabelText::escape_char(c, |c| out.push(c));
436         }
437         out
438     }
439
440     /// Renders text as string suitable for a label in a .dot file.
441     pub fn escape(&self) -> String {
442         match self {
443             &LabelStr(ref s) => s.as_slice().escape_default(),
444             &EscStr(ref s) => LabelText::escape_str(s.as_slice()),
445         }
446     }
447
448     /// Decomposes content into string suitable for making EscStr that
449     /// yields same content as self.  The result obeys the law
450     /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
451     /// all `lt: LabelText`.
452     fn pre_escaped_content(self) -> CowString<'a> {
453         match self {
454             EscStr(s) => s,
455             LabelStr(s) => if s.contains_char('\\') {
456                 s.escape_default().into_cow()
457             } else {
458                 s
459             },
460         }
461     }
462
463     /// Puts `prefix` on a line above this label, with a blank line separator.
464     pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
465         prefix.suffix_line(self)
466     }
467
468     /// Puts `suffix` on a line below this label, with a blank line separator.
469     pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
470         let mut prefix = self.pre_escaped_content().into_string();
471         let suffix = suffix.pre_escaped_content();
472         prefix.push_str(r"\n\n");
473         prefix.push_str(suffix.as_slice());
474         EscStr(prefix.into_cow())
475     }
476 }
477
478 pub type Nodes<'a,N> = CowVec<'a,N>;
479 pub type Edges<'a,E> = CowVec<'a,E>;
480
481 // (The type parameters in GraphWalk should be associated items,
482 // when/if Rust supports such.)
483
484 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
485 /// made up of node handles `N` and edge handles `E`, where each `E`
486 /// can be mapped to its source and target nodes.
487 ///
488 /// The lifetime parameter `'a` is exposed in this trait (rather than
489 /// introduced as a generic parameter on each method declaration) so
490 /// that a client impl can choose `N` and `E` that have substructure
491 /// that is bound by the self lifetime `'a`.
492 ///
493 /// The `nodes` and `edges` method each return instantiations of
494 /// `CowVec` to leave implementers the freedom to create
495 /// entirely new vectors or to pass back slices into internally owned
496 /// vectors.
497 pub trait GraphWalk<'a, N, E> {
498     /// Returns all the nodes in this graph.
499     fn nodes(&'a self) -> Nodes<'a, N>;
500     /// Returns all of the edges in this graph.
501     fn edges(&'a self) -> Edges<'a, E>;
502     /// The source node for `edge`.
503     fn source(&'a self, edge: &E) -> N;
504     /// The target node for `edge`.
505     fn target(&'a self, edge: &E) -> N;
506 }
507
508 /// Renders directed graph `g` into the writer `w` in DOT syntax.
509 /// (Main entry point for the library.)
510 pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>(
511               g: &'a G,
512               w: &mut W) -> io::IoResult<()>
513 {
514     fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> io::IoResult<()> {
515         for &s in arg.iter() { try!(w.write_str(s)); }
516         w.write_char('\n')
517     }
518
519     fn indent<W:Writer>(w: &mut W) -> io::IoResult<()> {
520         w.write_str("    ")
521     }
522
523     try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"]));
524     for n in g.nodes().iter() {
525         try!(indent(w));
526         let id = g.node_id(n);
527         let escaped = g.node_label(n).escape();
528         try!(writeln(w, &[id.as_slice(),
529                           "[label=\"", escaped.as_slice(), "\"];"]));
530     }
531
532     for e in g.edges().iter() {
533         let escaped_label = g.edge_label(e).escape();
534         try!(indent(w));
535         let source = g.source(e);
536         let target = g.target(e);
537         let source_id = g.node_id(&source);
538         let target_id = g.node_id(&target);
539         try!(writeln(w, &[source_id.as_slice(), " -> ", target_id.as_slice(),
540                           "[label=\"", escaped_label.as_slice(), "\"];"]));
541     }
542
543     writeln(w, &["}"])
544 }
545
546 #[cfg(test)]
547 mod tests {
548     use self::NodeLabels::*;
549     use super::{Id, LabelText, LabelStr, EscStr, Labeller};
550     use super::{Nodes, Edges, GraphWalk, render};
551     use std::io::{BufReader, IoResult};
552     use std::str;
553
554     /// each node is an index in a vector in the graph.
555     type Node = uint;
556     struct Edge {
557         from: uint, to: uint, label: &'static str
558     }
559
560     fn edge(from: uint, to: uint, label: &'static str) -> Edge {
561         Edge { from: from, to: to, label: label }
562     }
563
564     struct LabelledGraph {
565         /// The name for this graph. Used for labelling generated `digraph`.
566         name: &'static str,
567
568         /// Each node is an index into `node_labels`; these labels are
569         /// used as the label text for each node. (The node *names*,
570         /// which are unique identifiers, are derived from their index
571         /// in this array.)
572         ///
573         /// If a node maps to None here, then just use its name as its
574         /// text.
575         node_labels: Vec<Option<&'static str>>,
576
577         /// Each edge relates a from-index to a to-index along with a
578         /// label; `edges` collects them.
579         edges: Vec<Edge>,
580     }
581
582     // A simple wrapper around LabelledGraph that forces the labels to
583     // be emitted as EscStr.
584     struct LabelledGraphWithEscStrs {
585         graph: LabelledGraph
586     }
587
588     enum NodeLabels<L> {
589         AllNodesLabelled(Vec<L>),
590         UnlabelledNodes(uint),
591         SomeNodesLabelled(Vec<Option<L>>),
592     }
593
594     type Trivial = NodeLabels<&'static str>;
595
596     impl NodeLabels<&'static str> {
597         fn to_opt_strs(self) -> Vec<Option<&'static str>> {
598             match self {
599                 UnlabelledNodes(len)
600                     => Vec::from_elem(len, None).into_iter().collect(),
601                 AllNodesLabelled(lbls)
602                     => lbls.into_iter().map(
603                         |l|Some(l)).collect(),
604                 SomeNodesLabelled(lbls)
605                     => lbls.into_iter().collect(),
606             }
607         }
608     }
609
610     impl LabelledGraph {
611         fn new(name: &'static str,
612                node_labels: Trivial,
613                edges: Vec<Edge>) -> LabelledGraph {
614             LabelledGraph {
615                 name: name,
616                 node_labels: node_labels.to_opt_strs(),
617                 edges: edges
618             }
619         }
620     }
621
622     impl LabelledGraphWithEscStrs {
623         fn new(name: &'static str,
624                node_labels: Trivial,
625                edges: Vec<Edge>) -> LabelledGraphWithEscStrs {
626             LabelledGraphWithEscStrs {
627                 graph: LabelledGraph::new(name, node_labels, edges)
628             }
629         }
630     }
631
632     fn id_name<'a>(n: &Node) -> Id<'a> {
633         Id::new(format!("N{}", *n)).unwrap()
634     }
635
636     impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
637         fn graph_id(&'a self) -> Id<'a> {
638             Id::new(self.name.as_slice()).unwrap()
639         }
640         fn node_id(&'a self, n: &Node) -> Id<'a> {
641             id_name(n)
642         }
643         fn node_label(&'a self, n: &Node) -> LabelText<'a> {
644             match self.node_labels[*n] {
645                 Some(ref l) => LabelStr(l.into_cow()),
646                 None        => LabelStr(id_name(n).name()),
647             }
648         }
649         fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
650             LabelStr(e.label.into_cow())
651         }
652     }
653
654     impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
655         fn graph_id(&'a self) -> Id<'a> { self.graph.graph_id() }
656         fn node_id(&'a self, n: &Node) -> Id<'a> { self.graph.node_id(n) }
657         fn node_label(&'a self, n: &Node) -> LabelText<'a> {
658             match self.graph.node_label(n) {
659                 LabelStr(s) | EscStr(s) => EscStr(s),
660             }
661         }
662         fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
663             match self.graph.edge_label(e) {
664                 LabelStr(s) | EscStr(s) => EscStr(s),
665             }
666         }
667     }
668
669     impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
670         fn nodes(&'a self) -> Nodes<'a,Node> {
671             range(0u, self.node_labels.len()).collect()
672         }
673         fn edges(&'a self) -> Edges<'a,&'a Edge> {
674             self.edges.iter().collect()
675         }
676         fn source(&'a self, edge: & &'a Edge) -> Node {
677             edge.from
678         }
679         fn target(&'a self, edge: & &'a Edge) -> Node {
680             edge.to
681         }
682     }
683
684     impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
685         fn nodes(&'a self) -> Nodes<'a,Node> {
686             self.graph.nodes()
687         }
688         fn edges(&'a self) -> Edges<'a,&'a Edge> {
689             self.graph.edges()
690         }
691         fn source(&'a self, edge: & &'a Edge) -> Node {
692             edge.from
693         }
694         fn target(&'a self, edge: & &'a Edge) -> Node {
695             edge.to
696         }
697     }
698
699     fn test_input(g: LabelledGraph) -> IoResult<String> {
700         let mut writer = Vec::new();
701         render(&g, &mut writer).unwrap();
702         let mut r = BufReader::new(writer[]);
703         r.read_to_string()
704     }
705
706     // All of the tests use raw-strings as the format for the expected outputs,
707     // so that you can cut-and-paste the content into a .dot file yourself to
708     // see what the graphviz visualizer would produce.
709
710     #[test]
711     fn empty_graph() {
712         let labels : Trivial = UnlabelledNodes(0);
713         let r = test_input(LabelledGraph::new("empty_graph", labels, vec!()));
714         assert_eq!(r.unwrap().as_slice(),
715 r#"digraph empty_graph {
716 }
717 "#);
718     }
719
720     #[test]
721     fn single_node() {
722         let labels : Trivial = UnlabelledNodes(1);
723         let r = test_input(LabelledGraph::new("single_node", labels, vec!()));
724         assert_eq!(r.unwrap().as_slice(),
725 r#"digraph single_node {
726     N0[label="N0"];
727 }
728 "#);
729     }
730
731     #[test]
732     fn single_edge() {
733         let labels : Trivial = UnlabelledNodes(2);
734         let result = test_input(LabelledGraph::new("single_edge", labels,
735                                                    vec!(edge(0, 1, "E"))));
736         assert_eq!(result.unwrap().as_slice(),
737 r#"digraph single_edge {
738     N0[label="N0"];
739     N1[label="N1"];
740     N0 -> N1[label="E"];
741 }
742 "#);
743     }
744
745     #[test]
746     fn test_some_labelled() {
747         let labels : Trivial = SomeNodesLabelled(vec![Some("A"), None]);
748         let result = test_input(LabelledGraph::new("test_some_labelled", labels,
749                                                    vec![edge(0, 1, "A-1")]));
750         assert_eq!(result.unwrap().as_slice(),
751 r#"digraph test_some_labelled {
752     N0[label="A"];
753     N1[label="N1"];
754     N0 -> N1[label="A-1"];
755 }
756 "#);
757     }
758
759     #[test]
760     fn single_cyclic_node() {
761         let labels : Trivial = UnlabelledNodes(1);
762         let r = test_input(LabelledGraph::new("single_cyclic_node", labels,
763                                               vec!(edge(0, 0, "E"))));
764         assert_eq!(r.unwrap().as_slice(),
765 r#"digraph single_cyclic_node {
766     N0[label="N0"];
767     N0 -> N0[label="E"];
768 }
769 "#);
770     }
771
772     #[test]
773     fn hasse_diagram() {
774         let labels = AllNodesLabelled(vec!("{x,y}", "{x}", "{y}", "{}"));
775         let r = test_input(LabelledGraph::new(
776             "hasse_diagram", labels,
777             vec!(edge(0, 1, ""), edge(0, 2, ""),
778                  edge(1, 3, ""), edge(2, 3, ""))));
779         assert_eq!(r.unwrap().as_slice(),
780 r#"digraph hasse_diagram {
781     N0[label="{x,y}"];
782     N1[label="{x}"];
783     N2[label="{y}"];
784     N3[label="{}"];
785     N0 -> N1[label=""];
786     N0 -> N2[label=""];
787     N1 -> N3[label=""];
788     N2 -> N3[label=""];
789 }
790 "#);
791     }
792
793     #[test]
794     fn left_aligned_text() {
795         let labels = AllNodesLabelled(vec!(
796             "if test {\
797            \\l    branch1\
798            \\l} else {\
799            \\l    branch2\
800            \\l}\
801            \\lafterward\
802            \\l",
803             "branch1",
804             "branch2",
805             "afterward"));
806
807         let mut writer = Vec::new();
808
809         let g = LabelledGraphWithEscStrs::new(
810             "syntax_tree", labels,
811             vec!(edge(0, 1, "then"), edge(0, 2, "else"),
812                  edge(1, 3, ";"),    edge(2, 3, ";"   )));
813
814         render(&g, &mut writer).unwrap();
815         let mut r = BufReader::new(writer[]);
816         let r = r.read_to_string();
817
818         assert_eq!(r.unwrap().as_slice(),
819 r#"digraph syntax_tree {
820     N0[label="if test {\l    branch1\l} else {\l    branch2\l}\lafterward\l"];
821     N1[label="branch1"];
822     N2[label="branch2"];
823     N3[label="afterward"];
824     N0 -> N1[label="then"];
825     N0 -> N2[label="else"];
826     N1 -> N3[label=";"];
827     N2 -> N3[label=";"];
828 }
829 "#);
830     }
831
832     #[test]
833     fn simple_id_construction() {
834         let id1 = Id::new("hello");
835         match id1 {
836             Ok(_) => {;},
837             Err(_) => panic!("'hello' is not a valid value for id anymore")
838         }
839     }
840
841     #[test]
842     fn badly_formatted_id() {
843         let id2 = Id::new("Weird { struct : ure } !!!");
844         match id2 {
845             Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
846             Err(_) => {;}
847         }
848     }
849 }