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