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