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