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