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