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