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