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