]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_graphviz/src/lib.rs
Rollup merge of #83667 - estebank:cool-bears-hot-tip, r=lcnr
[rust.git] / compiler / rustc_graphviz / src / 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 rustc_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 rustc_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 rustc_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(
275     html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
276     test(attr(allow(unused_variables), deny(warnings)))
277 )]
278 #![feature(nll)]
279
280 use LabelText::*;
281
282 use std::borrow::Cow;
283 use std::io;
284 use std::io::prelude::*;
285
286 /// The text for a graphviz label on a node or edge.
287 pub enum LabelText<'a> {
288     /// This kind of label preserves the text directly as is.
289     ///
290     /// Occurrences of backslashes (`\`) are escaped, and thus appear
291     /// as backslashes in the rendered label.
292     LabelStr(Cow<'a, str>),
293
294     /// This kind of label uses the graphviz label escString type:
295     /// <http://www.graphviz.org/content/attrs#kescString>
296     ///
297     /// Occurrences of backslashes (`\`) are not escaped; instead they
298     /// are interpreted as initiating an escString escape sequence.
299     ///
300     /// Escape sequences of particular interest: in addition to `\n`
301     /// to break a line (centering the line preceding the `\n`), there
302     /// are also the escape sequences `\l` which left-justifies the
303     /// preceding line and `\r` which right-justifies it.
304     EscStr(Cow<'a, str>),
305
306     /// This uses a graphviz [HTML string label][html]. The string is
307     /// printed exactly as given, but between `<` and `>`. **No
308     /// escaping is performed.**
309     ///
310     /// [html]: http://www.graphviz.org/content/node-shapes#html
311     HtmlStr(Cow<'a, str>),
312 }
313
314 /// The style for a node or edge.
315 /// See <http://www.graphviz.org/doc/info/attrs.html#k:style> for descriptions.
316 /// Note that some of these are not valid for edges.
317 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
318 pub enum Style {
319     None,
320     Solid,
321     Dashed,
322     Dotted,
323     Bold,
324     Rounded,
325     Diagonals,
326     Filled,
327     Striped,
328     Wedged,
329 }
330
331 impl Style {
332     pub fn as_slice(self) -> &'static str {
333         match self {
334             Style::None => "",
335             Style::Solid => "solid",
336             Style::Dashed => "dashed",
337             Style::Dotted => "dotted",
338             Style::Bold => "bold",
339             Style::Rounded => "rounded",
340             Style::Diagonals => "diagonals",
341             Style::Filled => "filled",
342             Style::Striped => "striped",
343             Style::Wedged => "wedged",
344         }
345     }
346 }
347
348 // There is a tension in the design of the labelling API.
349 //
350 // For example, I considered making a `Labeller<T>` trait that
351 // provides labels for `T`, and then making the graph type `G`
352 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
353 // not possible without functional dependencies. (One could work
354 // around that, but I did not explore that avenue heavily.)
355 //
356 // Another approach that I actually used for a while was to make a
357 // `Label<Context>` trait that is implemented by the client-specific
358 // Node and Edge types (as well as an implementation on Graph itself
359 // for the overall name for the graph). The main disadvantage of this
360 // second approach (compared to having the `G` type parameter
361 // implement a Labelling service) that I have encountered is that it
362 // makes it impossible to use types outside of the current crate
363 // directly as Nodes/Edges; you need to wrap them in newtype'd
364 // structs. See e.g., the `No` and `Ed` structs in the examples. (In
365 // practice clients using a graph in some other crate would need to
366 // provide some sort of adapter shim over the graph anyway to
367 // interface with this library).
368 //
369 // Another approach would be to make a single `Labeller<N,E>` trait
370 // that provides three methods (graph_label, node_label, edge_label),
371 // and then make `G` implement `Labeller<N,E>`. At first this did not
372 // appeal to me, since I had thought I would need separate methods on
373 // each data variant for dot-internal identifiers versus user-visible
374 // labels. However, the identifier/label distinction only arises for
375 // nodes; graphs themselves only have identifiers, and edges only have
376 // labels.
377 //
378 // So in the end I decided to use the third approach described above.
379
380 /// `Id` is a Graphviz `ID`.
381 pub struct Id<'a> {
382     name: Cow<'a, str>,
383 }
384
385 impl<'a> Id<'a> {
386     /// Creates an `Id` named `name`.
387     ///
388     /// The caller must ensure that the input conforms to an
389     /// identifier format: it must be a non-empty string made up of
390     /// alphanumeric or underscore characters, not beginning with a
391     /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
392     ///
393     /// (Note: this format is a strict subset of the `ID` format
394     /// defined by the DOT language. This function may change in the
395     /// future to accept a broader subset, or the entirety, of DOT's
396     /// `ID` format.)
397     ///
398     /// Passing an invalid string (containing spaces, brackets,
399     /// quotes, ...) will return an empty `Err` value.
400     pub fn new<Name: Into<Cow<'a, str>>>(name: Name) -> Result<Id<'a>, ()> {
401         let name = name.into();
402         match name.chars().next() {
403             Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
404             _ => return Err(()),
405         }
406         if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
407             return Err(());
408         }
409
410         Ok(Id { name })
411     }
412
413     pub fn as_slice(&'a self) -> &'a str {
414         &*self.name
415     }
416 }
417
418 /// Each instance of a type that implements `Label<C>` maps to a
419 /// unique identifier with respect to `C`, which is used to identify
420 /// it in the generated .dot file. They can also provide more
421 /// elaborate (and non-unique) label text that is used in the graphviz
422 /// rendered output.
423
424 /// The graph instance is responsible for providing the DOT compatible
425 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
426 /// edges, as well as an identifier for the graph itself.
427 pub trait Labeller<'a> {
428     type Node;
429     type Edge;
430
431     /// Must return a DOT compatible identifier naming the graph.
432     fn graph_id(&'a self) -> Id<'a>;
433
434     /// Maps `n` to a unique identifier with respect to `self`. The
435     /// implementor is responsible for ensuring that the returned name
436     /// is a valid DOT identifier.
437     fn node_id(&'a self, n: &Self::Node) -> Id<'a>;
438
439     /// Maps `n` to one of the [graphviz `shape` names][1]. If `None`
440     /// is returned, no `shape` attribute is specified.
441     ///
442     /// [1]: http://www.graphviz.org/content/node-shapes
443     fn node_shape(&'a self, _node: &Self::Node) -> Option<LabelText<'a>> {
444         None
445     }
446
447     /// Maps `n` to a label that will be used in the rendered output.
448     /// The label need not be unique, and may be the empty string; the
449     /// default is just the output from `node_id`.
450     fn node_label(&'a self, n: &Self::Node) -> LabelText<'a> {
451         LabelStr(self.node_id(n).name)
452     }
453
454     /// Maps `e` 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 in fact the empty string.
457     fn edge_label(&'a self, _e: &Self::Edge) -> LabelText<'a> {
458         LabelStr("".into())
459     }
460
461     /// Maps `n` to a style that will be used in the rendered output.
462     fn node_style(&'a self, _n: &Self::Node) -> Style {
463         Style::None
464     }
465
466     /// Maps `e` to a style that will be used in the rendered output.
467     fn edge_style(&'a self, _e: &Self::Edge) -> Style {
468         Style::None
469     }
470 }
471
472 /// Escape tags in such a way that it is suitable for inclusion in a
473 /// Graphviz HTML label.
474 pub fn escape_html(s: &str) -> String {
475     s.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;")
476 }
477
478 impl<'a> LabelText<'a> {
479     pub fn label<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
480         LabelStr(s.into())
481     }
482
483     pub fn html<S: Into<Cow<'a, str>>>(s: S) -> LabelText<'a> {
484         HtmlStr(s.into())
485     }
486
487     fn escape_char<F>(c: char, mut f: F)
488     where
489         F: FnMut(char),
490     {
491         match c {
492             // not escaping \\, since Graphviz escString needs to
493             // interpret backslashes; see EscStr above.
494             '\\' => f(c),
495             _ => {
496                 for c in c.escape_default() {
497                     f(c)
498                 }
499             }
500         }
501     }
502     fn escape_str(s: &str) -> String {
503         let mut out = String::with_capacity(s.len());
504         for c in s.chars() {
505             LabelText::escape_char(c, |c| out.push(c));
506         }
507         out
508     }
509
510     /// Renders text as string suitable for a label in a .dot file.
511     /// This includes quotes or suitable delimiters.
512     pub fn to_dot_string(&self) -> String {
513         match *self {
514             LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
515             EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s)),
516             HtmlStr(ref s) => format!("<{}>", s),
517         }
518     }
519
520     /// Decomposes content into string suitable for making EscStr that
521     /// yields same content as self. The result obeys the law
522     /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
523     /// all `lt: LabelText`.
524     fn pre_escaped_content(self) -> Cow<'a, str> {
525         match self {
526             EscStr(s) => s,
527             LabelStr(s) => {
528                 if s.contains('\\') {
529                     (&*s).escape_default().to_string().into()
530                 } else {
531                     s
532                 }
533             }
534             HtmlStr(s) => s,
535         }
536     }
537
538     /// Puts `suffix` on a line below this label, with a blank line separator.
539     pub fn suffix_line(self, suffix: LabelText<'_>) -> LabelText<'static> {
540         let mut prefix = self.pre_escaped_content().into_owned();
541         let suffix = suffix.pre_escaped_content();
542         prefix.push_str(r"\n\n");
543         prefix.push_str(&suffix);
544         EscStr(prefix.into())
545     }
546 }
547
548 pub type Nodes<'a, N> = Cow<'a, [N]>;
549 pub type Edges<'a, E> = Cow<'a, [E]>;
550
551 // (The type parameters in GraphWalk should be associated items,
552 // when/if Rust supports such.)
553
554 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
555 /// made up of node handles `N` and edge handles `E`, where each `E`
556 /// can be mapped to its source and target nodes.
557 ///
558 /// The lifetime parameter `'a` is exposed in this trait (rather than
559 /// introduced as a generic parameter on each method declaration) so
560 /// that a client impl can choose `N` and `E` that have substructure
561 /// that is bound by the self lifetime `'a`.
562 ///
563 /// The `nodes` and `edges` method each return instantiations of
564 /// `Cow<[T]>` to leave implementors the freedom to create
565 /// entirely new vectors or to pass back slices into internally owned
566 /// vectors.
567 pub trait GraphWalk<'a> {
568     type Node: Clone;
569     type Edge: Clone;
570
571     /// Returns all the nodes in this graph.
572     fn nodes(&'a self) -> Nodes<'a, Self::Node>;
573     /// Returns all of the edges in this graph.
574     fn edges(&'a self) -> Edges<'a, Self::Edge>;
575     /// The source node for `edge`.
576     fn source(&'a self, edge: &Self::Edge) -> Self::Node;
577     /// The target node for `edge`.
578     fn target(&'a self, edge: &Self::Edge) -> Self::Node;
579 }
580
581 #[derive(Clone, PartialEq, Eq, Debug)]
582 pub enum RenderOption {
583     NoEdgeLabels,
584     NoNodeLabels,
585     NoEdgeStyles,
586     NoNodeStyles,
587
588     Fontname(String),
589     DarkTheme,
590 }
591
592 /// Renders directed graph `g` into the writer `w` in DOT syntax.
593 /// (Simple wrapper around `render_opts` that passes a default set of options.)
594 pub fn render<'a, N, E, G, W>(g: &'a G, w: &mut W) -> io::Result<()>
595 where
596     N: Clone + 'a,
597     E: Clone + 'a,
598     G: Labeller<'a, Node = N, Edge = E> + GraphWalk<'a, Node = N, Edge = E>,
599     W: Write,
600 {
601     render_opts(g, w, &[])
602 }
603
604 /// Renders directed graph `g` into the writer `w` in DOT syntax.
605 /// (Main entry point for the library.)
606 pub fn render_opts<'a, N, E, G, W>(g: &'a G, w: &mut W, options: &[RenderOption]) -> io::Result<()>
607 where
608     N: Clone + 'a,
609     E: Clone + 'a,
610     G: Labeller<'a, Node = N, Edge = E> + GraphWalk<'a, Node = N, Edge = E>,
611     W: Write,
612 {
613     writeln!(w, "digraph {} {{", g.graph_id().as_slice())?;
614
615     // Global graph properties
616     let mut graph_attrs = Vec::new();
617     let mut content_attrs = Vec::new();
618     let font;
619     if let Some(fontname) = options.iter().find_map(|option| {
620         if let RenderOption::Fontname(fontname) = option { Some(fontname) } else { None }
621     }) {
622         font = format!(r#"fontname="{}""#, fontname);
623         graph_attrs.push(&font[..]);
624         content_attrs.push(&font[..]);
625     }
626     if options.contains(&RenderOption::DarkTheme) {
627         graph_attrs.push(r#"bgcolor="black""#);
628         graph_attrs.push(r#"fontcolor="white""#);
629         content_attrs.push(r#"color="white""#);
630         content_attrs.push(r#"fontcolor="white""#);
631     }
632     if !(graph_attrs.is_empty() && content_attrs.is_empty()) {
633         writeln!(w, r#"    graph[{}];"#, graph_attrs.join(" "))?;
634         let content_attrs_str = content_attrs.join(" ");
635         writeln!(w, r#"    node[{}];"#, content_attrs_str)?;
636         writeln!(w, r#"    edge[{}];"#, content_attrs_str)?;
637     }
638
639     let mut text = Vec::new();
640     for n in g.nodes().iter() {
641         write!(w, "    ")?;
642         let id = g.node_id(n);
643
644         let escaped = &g.node_label(n).to_dot_string();
645
646         write!(text, "{}", id.as_slice()).unwrap();
647
648         if !options.contains(&RenderOption::NoNodeLabels) {
649             write!(text, "[label={}]", escaped).unwrap();
650         }
651
652         let style = g.node_style(n);
653         if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None {
654             write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
655         }
656
657         if let Some(s) = g.node_shape(n) {
658             write!(text, "[shape={}]", &s.to_dot_string()).unwrap();
659         }
660
661         writeln!(text, ";").unwrap();
662         w.write_all(&text[..])?;
663
664         text.clear();
665     }
666
667     for e in g.edges().iter() {
668         let escaped_label = &g.edge_label(e).to_dot_string();
669         write!(w, "    ")?;
670         let source = g.source(e);
671         let target = g.target(e);
672         let source_id = g.node_id(&source);
673         let target_id = g.node_id(&target);
674
675         write!(text, "{} -> {}", source_id.as_slice(), target_id.as_slice()).unwrap();
676
677         if !options.contains(&RenderOption::NoEdgeLabels) {
678             write!(text, "[label={}]", escaped_label).unwrap();
679         }
680
681         let style = g.edge_style(e);
682         if !options.contains(&RenderOption::NoEdgeStyles) && style != Style::None {
683             write!(text, "[style=\"{}\"]", style.as_slice()).unwrap();
684         }
685
686         writeln!(text, ";").unwrap();
687         w.write_all(&text[..])?;
688
689         text.clear();
690     }
691
692     writeln!(w, "}}")
693 }
694
695 #[cfg(test)]
696 mod tests;