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