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