1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Generate files suitable for use with [Graphviz](http://www.graphviz.org/)
13 //! The `render` function generates output (e.g. an `output.dot` file) for
14 //! use with [Graphviz](http://www.graphviz.org/) by walking a labelled
15 //! graph. (Graphviz can then automatically lay out the nodes and edges
16 //! of the graph, and also optionally render the graph as an image or
17 //! other [output formats](
18 //! http://www.graphviz.org/content/output-formats), such as SVG.)
20 //! Rather than impose some particular graph data structure on clients,
21 //! this library exposes two traits that clients can implement on their
22 //! own structs before handing them over to the rendering function.
24 //! Note: This library does not yet provide access to the full
25 //! expressiveness of the [DOT language](
26 //! http://www.graphviz.org/doc/info/lang.html). For example, there are
27 //! many [attributes](http://www.graphviz.org/content/attrs) related to
28 //! providing layout hints (e.g. left-to-right versus top-down, which
29 //! algorithm to use, etc). The current intention of this library is to
30 //! emit a human-readable .dot file with very regular structure suitable
31 //! for easy post-processing.
35 //! The first example uses a very simple graph representation: a list of
36 //! pairs of ints, representing the edges (the node set is implicit).
37 //! Each node label is derived directly from the int representing the node,
38 //! while the edge labels are all empty strings.
40 //! This example also illustrates how to use `Cow<[T]>` to return
41 //! an owned vector or a borrowed slice as appropriate: we construct the
42 //! node vector from scratch, but borrow the edge list (rather than
43 //! constructing a copy of all the edges from scratch).
45 //! The output from this example renders five nodes, with the first four
46 //! forming a diamond-shaped acyclic graph and then pointing to the fifth
50 //! #![feature(rustc_private, core, into_cow)]
52 //! use std::borrow::IntoCow;
53 //! use std::io::Write;
54 //! use graphviz as dot;
57 //! type Ed = (isize,isize);
58 //! struct Edges(Vec<Ed>);
60 //! pub fn render_to<W: Write>(output: &mut W) {
61 //! let edges = Edges(vec!((0,1), (0,2), (1,3), (2,3), (3,4), (4,4)));
62 //! dot::render(&edges, output).unwrap()
65 //! impl<'a> dot::Labeller<'a, Nd, Ed> for Edges {
66 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
68 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
69 //! dot::Id::new(format!("N{}", *n)).unwrap()
73 //! impl<'a> dot::GraphWalk<'a, Nd, Ed> for Edges {
74 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
75 //! // (assumes that |N| \approxeq |E|)
76 //! let &Edges(ref v) = self;
77 //! let mut nodes = Vec::with_capacity(v.len());
79 //! nodes.push(s); nodes.push(t);
86 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
87 //! let &Edges(ref edges) = self;
88 //! (&edges[..]).into_cow()
91 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
93 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
96 //! # pub fn main() { render_to(&mut Vec::new()) }
100 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
102 //! use std::fs::File;
103 //! let mut f = File::create("example1.dot").unwrap();
104 //! render_to(&mut f)
108 //! Output from first example (in `example1.dot`):
111 //! digraph example1 {
117 //! N0 -> N1[label=""];
118 //! N0 -> N2[label=""];
119 //! N1 -> N3[label=""];
120 //! N2 -> N3[label=""];
121 //! N3 -> N4[label=""];
122 //! N4 -> N4[label=""];
126 //! The second example illustrates using `node_label` and `edge_label` to
127 //! add labels to the nodes and edges in the rendered graph. The graph
128 //! here carries both `nodes` (the label text to use for rendering a
129 //! particular node), and `edges` (again a list of `(source,target)`
132 //! This example also illustrates how to use a type (in this case the edge
133 //! type) that shares substructure with the graph: the edge type here is a
134 //! direct reference to the `(source,target)` pair stored in the graph's
135 //! internal vector (rather than passing around a copy of the pair
136 //! itself). Note that this implies that `fn edges(&'a self)` must
137 //! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
138 //! edges stored in `self`.
140 //! Since both the set of nodes and the set of edges are always
141 //! constructed from scratch via iterators, we use the `collect()` method
142 //! from the `Iterator` trait to collect the nodes and edges into freshly
143 //! constructed growable `Vec` values (rather use the `into_cow`
144 //! from the `IntoCow` trait as was used in the first example
147 //! The output from this example renders four nodes that make up the
148 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
149 //! labelled with the ⊆ character (specified using the HTML character
153 //! #![feature(rustc_private, core, into_cow)]
155 //! use std::borrow::IntoCow;
156 //! use std::io::Write;
157 //! use graphviz as dot;
160 //! type Ed<'a> = &'a (usize, usize);
161 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
163 //! pub fn render_to<W: Write>(output: &mut W) {
164 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
165 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
166 //! let graph = Graph { nodes: nodes, edges: edges };
168 //! dot::render(&graph, output).unwrap()
171 //! impl<'a> dot::Labeller<'a, Nd, Ed<'a>> for Graph {
172 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
173 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
174 //! dot::Id::new(format!("N{}", n)).unwrap()
176 //! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
177 //! dot::LabelText::LabelStr(self.nodes[*n].as_slice().into_cow())
179 //! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
180 //! dot::LabelText::LabelStr("⊆".into_cow())
184 //! impl<'a> dot::GraphWalk<'a, Nd, Ed<'a>> for Graph {
185 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() }
186 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
187 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
188 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
191 //! # pub fn main() { render_to(&mut Vec::new()) }
195 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
197 //! use std::fs::File;
198 //! let mut f = File::create("example2.dot").unwrap();
199 //! render_to(&mut f)
203 //! The third example is similar to the second, except now each node and
204 //! edge now carries a reference to the string label for each node as well
205 //! as that node's index. (This is another illustration of how to share
206 //! structure with the graph itself, and why one might want to do so.)
208 //! The output from this example is the same as the second example: the
209 //! Hasse-diagram for the subsets of the set `{x, y}`.
212 //! #![feature(rustc_private, core, into_cow)]
214 //! use std::borrow::IntoCow;
215 //! use std::io::Write;
216 //! use graphviz as dot;
218 //! type Nd<'a> = (usize, &'a str);
219 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
220 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
222 //! pub fn render_to<W: Write>(output: &mut W) {
223 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
224 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
225 //! let graph = Graph { nodes: nodes, edges: edges };
227 //! dot::render(&graph, output).unwrap()
230 //! impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph {
231 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
232 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
233 //! dot::Id::new(format!("N{}", n.0)).unwrap()
235 //! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
237 //! dot::LabelText::LabelStr(self.nodes[i].into_cow())
239 //! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
240 //! dot::LabelText::LabelStr("⊆".into_cow())
244 //! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
245 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
246 //! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
248 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
249 //! self.edges.iter()
250 //! .map(|&(i,j)|((i, &self.nodes[i][..]),
251 //! (j, &self.nodes[j][..])))
254 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
255 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
258 //! # pub fn main() { render_to(&mut Vec::new()) }
262 //! # pub fn render_to<W:std::io::Write>(output: &mut W) { unimplemented!() }
264 //! use std::fs::File;
265 //! let mut f = File::create("example3.dot").unwrap();
266 //! render_to(&mut f)
272 //! * [Graphviz](http://www.graphviz.org/)
274 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
276 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
277 #![cfg_attr(stage0, feature(custom_attribute))]
278 #![crate_name = "graphviz"]
279 #![unstable(feature = "rustc_private")]
280 #![feature(staged_api)]
282 #![crate_type = "rlib"]
283 #![crate_type = "dylib"]
284 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
285 html_favicon_url
= "https://doc.rust-lang.org/favicon.ico",
286 html_root_url
= "http://doc.rust-lang.org/nightly/")]
288 #![feature(into_cow)]
289 #![feature(str_escape)]
291 use self::LabelText
::*;
293 use std
::borrow
::{IntoCow, Cow}
;
294 use std
::io
::prelude
::*;
297 /// The text for a graphviz label on a node or edge.
298 pub enum LabelText
<'a
> {
299 /// This kind of label preserves the text directly as is.
301 /// Occurrences of backslashes (`\`) are escaped, and thus appear
302 /// as backslashes in the rendered label.
303 LabelStr(Cow
<'a
, str>),
305 /// This kind of label uses the graphviz label escString type:
306 /// http://www.graphviz.org/content/attrs#kescString
308 /// Occurrences of backslashes (`\`) are not escaped; instead they
309 /// are interpreted as initiating an escString escape sequence.
311 /// Escape sequences of particular interest: in addition to `\n`
312 /// to break a line (centering the line preceding the `\n`), there
313 /// are also the escape sequences `\l` which left-justifies the
314 /// preceding line and `\r` which right-justifies it.
315 EscStr(Cow
<'a
, str>),
318 /// The style for a node or edge.
319 /// See http://www.graphviz.org/doc/info/attrs.html#k:style for descriptions.
320 /// Note that some of these are not valid for edges.
321 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
336 pub fn as_slice(self) -> &'
static str {
339 Style
::Solid
=> "solid",
340 Style
::Dashed
=> "dashed",
341 Style
::Dotted
=> "dotted",
342 Style
::Bold
=> "bold",
343 Style
::Rounded
=> "rounded",
344 Style
::Diagonals
=> "diagonals",
345 Style
::Filled
=> "filled",
346 Style
::Striped
=> "striped",
347 Style
::Wedged
=> "wedged",
352 // There is a tension in the design of the labelling API.
354 // For example, I considered making a `Labeller<T>` trait that
355 // provides labels for `T`, and then making the graph type `G`
356 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
357 // not possible without functional dependencies. (One could work
358 // around that, but I did not explore that avenue heavily.)
360 // Another approach that I actually used for a while was to make a
361 // `Label<Context>` trait that is implemented by the client-specific
362 // Node and Edge types (as well as an implementation on Graph itself
363 // for the overall name for the graph). The main disadvantage of this
364 // second approach (compared to having the `G` type parameter
365 // implement a Labelling service) that I have encountered is that it
366 // makes it impossible to use types outside of the current crate
367 // directly as Nodes/Edges; you need to wrap them in newtype'd
368 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
369 // practice clients using a graph in some other crate would need to
370 // provide some sort of adapter shim over the graph anyway to
371 // interface with this library).
373 // Another approach would be to make a single `Labeller<N,E>` trait
374 // that provides three methods (graph_label, node_label, edge_label),
375 // and then make `G` implement `Labeller<N,E>`. At first this did not
376 // appeal to me, since I had thought I would need separate methods on
377 // each data variant for dot-internal identifiers versus user-visible
378 // labels. However, the identifier/label distinction only arises for
379 // nodes; graphs themselves only have identifiers, and edges only have
382 // So in the end I decided to use the third approach described above.
384 /// `Id` is a Graphviz `ID`.
390 /// Creates an `Id` named `name`.
392 /// The caller must ensure that the input conforms to an
393 /// identifier format: it must be a non-empty string made up of
394 /// alphanumeric or underscore characters, not beginning with a
395 /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
397 /// (Note: this format is a strict subset of the `ID` format
398 /// defined by the DOT language. This function may change in the
399 /// future to accept a broader subset, or the entirety, of DOT's
402 /// Passing an invalid string (containing spaces, brackets,
403 /// quotes, ...) will return an empty `Err` value.
404 pub fn new
<Name
: IntoCow
<'a
, str>>(name
: Name
) -> Result
<Id
<'a
>, ()> {
405 let name
= name
.into_cow();
407 let mut chars
= name
.chars();
409 Some(c
) if is_letter_or_underscore(c
) => { ; }
,
412 if !chars
.all(is_constituent
) {
416 return Ok(Id{ name: name }
);
418 fn is_letter_or_underscore(c
: char) -> bool
{
419 in_range('a'
, c
, 'z'
) || in_range('A'
, c
, 'Z'
) || c
== '_'
421 fn is_constituent(c
: char) -> bool
{
422 is_letter_or_underscore(c
) || in_range('
0'
, c
, '
9'
)
424 fn in_range(low
: char, c
: char, high
: char) -> bool
{
425 low
as usize <= c
as usize && c
as usize <= high
as usize
429 pub fn as_slice(&'a
self) -> &'a
str {
433 pub fn name(self) -> Cow
<'a
, str> {
438 /// Each instance of a type that implements `Label<C>` maps to a
439 /// unique identifier with respect to `C`, which is used to identify
440 /// it in the generated .dot file. They can also provide more
441 /// elaborate (and non-unique) label text that is used in the graphviz
444 /// The graph instance is responsible for providing the DOT compatible
445 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
446 /// edges, as well as an identifier for the graph itself.
447 pub trait Labeller
<'a
,N
,E
> {
448 /// Must return a DOT compatible identifier naming the graph.
449 fn graph_id(&'a
self) -> Id
<'a
>;
451 /// Maps `n` to a unique identifier with respect to `self`. The
452 /// implementer is responsible for ensuring that the returned name
453 /// is a valid DOT identifier.
454 fn node_id(&'a
self, n
: &N
) -> Id
<'a
>;
456 /// Maps `n` to a label that will be used in the rendered output.
457 /// The label need not be unique, and may be the empty string; the
458 /// default is just the output from `node_id`.
459 fn node_label(&'a
self, n
: &N
) -> LabelText
<'a
> {
460 LabelStr(self.node_id(n
).name
)
463 /// Maps `e` to a label that will be used in the rendered output.
464 /// The label need not be unique, and may be the empty string; the
465 /// default is in fact the empty string.
466 fn edge_label(&'a
self, e
: &E
) -> LabelText
<'a
> {
468 LabelStr("".into_cow())
471 /// Maps `n` to a style that will be used in the rendered output.
472 fn node_style(&'a
self, _n
: &N
) -> Style
{
476 /// Maps `e` to a style that will be used in the rendered output.
477 fn edge_style(&'a
self, _e
: &E
) -> Style
{
482 impl<'a
> LabelText
<'a
> {
483 pub fn label
<S
:IntoCow
<'a
, str>>(s
: S
) -> LabelText
<'a
> {
484 LabelStr(s
.into_cow())
487 pub fn escaped
<S
:IntoCow
<'a
, str>>(s
: S
) -> LabelText
<'a
> {
491 fn escape_char
<F
>(c
: char, mut f
: F
) where F
: FnMut(char) {
493 // not escaping \\, since Graphviz escString needs to
494 // interpret backslashes; see EscStr above.
496 _
=> for c
in c
.escape_default() { f(c) }
499 fn escape_str(s
: &str) -> String
{
500 let mut out
= String
::with_capacity(s
.len());
502 LabelText
::escape_char(c
, |c
| out
.push(c
));
507 /// Renders text as string suitable for a label in a .dot file.
508 pub fn escape(&self) -> String
{
510 &LabelStr(ref s
) => s
.escape_default(),
511 &EscStr(ref s
) => LabelText
::escape_str(&s
[..]),
515 /// Decomposes content into string suitable for making EscStr that
516 /// yields same content as self. The result obeys the law
517 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
518 /// all `lt: LabelText`.
519 fn pre_escaped_content(self) -> Cow
<'a
, str> {
522 LabelStr(s
) => if s
.contains('
\\'
) {
523 (&*s
).escape_default().into_cow()
530 /// Puts `prefix` on a line above this label, with a blank line separator.
531 pub fn prefix_line(self, prefix
: LabelText
) -> LabelText
<'
static> {
532 prefix
.suffix_line(self)
535 /// Puts `suffix` on a line below this label, with a blank line separator.
536 pub fn suffix_line(self, suffix
: LabelText
) -> LabelText
<'
static> {
537 let mut prefix
= self.pre_escaped_content().into_owned();
538 let suffix
= suffix
.pre_escaped_content();
539 prefix
.push_str(r
"\n\n");
540 prefix
.push_str(&suffix
[..]);
541 EscStr(prefix
.into_cow())
545 pub type Nodes
<'a
,N
> = Cow
<'a
,[N
]>;
546 pub type Edges
<'a
,E
> = Cow
<'a
,[E
]>;
548 // (The type parameters in GraphWalk should be associated items,
549 // when/if Rust supports such.)
551 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
552 /// made up of node handles `N` and edge handles `E`, where each `E`
553 /// can be mapped to its source and target nodes.
555 /// The lifetime parameter `'a` is exposed in this trait (rather than
556 /// introduced as a generic parameter on each method declaration) so
557 /// that a client impl can choose `N` and `E` that have substructure
558 /// that is bound by the self lifetime `'a`.
560 /// The `nodes` and `edges` method each return instantiations of
561 /// `Cow<[T]>` to leave implementers the freedom to create
562 /// entirely new vectors or to pass back slices into internally owned
564 pub trait GraphWalk
<'a
, N
, E
> {
565 /// Returns all the nodes in this graph.
566 fn nodes(&'a
self) -> Nodes
<'a
, N
>;
567 /// Returns all of the edges in this graph.
568 fn edges(&'a
self) -> Edges
<'a
, E
>;
569 /// The source node for `edge`.
570 fn source(&'a
self, edge
: &E
) -> N
;
571 /// The target node for `edge`.
572 fn target(&'a
self, edge
: &E
) -> N
;
575 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
576 pub enum RenderOption
{
583 /// Returns vec holding all the default render options.
584 pub fn default_options() -> Vec
<RenderOption
> { vec![] }
586 /// Renders directed graph `g` into the writer `w` in DOT syntax.
587 /// (Simple wrapper around `render_opts` that passes a default set of options.)
588 pub fn render
<'a
, N
:Clone
+'a
, E
:Clone
+'a
, G
:Labeller
<'a
,N
,E
>+GraphWalk
<'a
,N
,E
>, W
:Write
>(
590 w
: &mut W
) -> io
::Result
<()> {
591 render_opts(g
, w
, &[])
594 /// Renders directed graph `g` into the writer `w` in DOT syntax.
595 /// (Main entry point for the library.)
596 pub fn render_opts
<'a
, N
:Clone
+'a
, E
:Clone
+'a
, G
:Labeller
<'a
,N
,E
>+GraphWalk
<'a
,N
,E
>, W
:Write
>(
599 options
: &[RenderOption
]) -> io
::Result
<()>
601 fn writeln
<W
:Write
>(w
: &mut W
, arg
: &[&str]) -> io
::Result
<()> {
602 for &s
in arg { try!(w.write_all(s.as_bytes())); }
606 fn indent
<W
:Write
>(w
: &mut W
) -> io
::Result
<()> {
610 try
!(writeln(w
, &["digraph ", g
.graph_id().as_slice(), " {"]));
611 for n
in g
.nodes().iter() {
613 let id
= g
.node_id(n
);
615 let escaped
= &g
.node_label(n
).escape();
617 let mut text
= vec
![id
.as_slice()];
619 if !options
.contains(&RenderOption
::NoNodeLabels
) {
620 text
.push("[label=\"");
625 let style
= g
.node_style(n
);
626 if !options
.contains(&RenderOption
::NoNodeStyles
) && style
!= Style
::None
{
627 text
.push("[style=\"");
628 text
.push(style
.as_slice());
633 try
!(writeln(w
, &text
));
636 for e
in g
.edges().iter() {
637 let escaped_label
= &g
.edge_label(e
).escape();
639 let source
= g
.source(e
);
640 let target
= g
.target(e
);
641 let source_id
= g
.node_id(&source
);
642 let target_id
= g
.node_id(&target
);
644 let mut text
= vec
![source_id
.as_slice(), " -> ", target_id
.as_slice()];
646 if !options
.contains(&RenderOption
::NoEdgeLabels
) {
647 text
.push("[label=\"");
648 text
.push(escaped_label
);
652 let style
= g
.edge_style(e
);
653 if !options
.contains(&RenderOption
::NoEdgeStyles
) && style
!= Style
::None
{
654 text
.push("[style=\"");
655 text
.push(style
.as_slice());
660 try
!(writeln(w
, &text
));
668 use self::NodeLabels
::*;
669 use super::{Id, Labeller, Nodes, Edges, GraphWalk, render, Style}
;
670 use super::LabelText
::{self, LabelStr, EscStr}
;
672 use std
::io
::prelude
::*;
673 use std
::borrow
::IntoCow
;
675 /// each node is an index in a vector in the graph.
684 fn edge(from
: usize, to
: usize, label
: &'
static str, style
: Style
) -> Edge
{
685 Edge { from: from, to: to, label: label, style: style }
688 struct LabelledGraph
{
689 /// The name for this graph. Used for labelling generated `digraph`.
692 /// Each node is an index into `node_labels`; these labels are
693 /// used as the label text for each node. (The node *names*,
694 /// which are unique identifiers, are derived from their index
697 /// If a node maps to None here, then just use its name as its
699 node_labels
: Vec
<Option
<&'
static str>>,
701 node_styles
: Vec
<Style
>,
703 /// Each edge relates a from-index to a to-index along with a
704 /// label; `edges` collects them.
708 // A simple wrapper around LabelledGraph that forces the labels to
709 // be emitted as EscStr.
710 struct LabelledGraphWithEscStrs
{
715 AllNodesLabelled(Vec
<L
>),
716 UnlabelledNodes(usize),
717 SomeNodesLabelled(Vec
<Option
<L
>>),
720 type Trivial
= NodeLabels
<&'
static str>;
722 impl NodeLabels
<&'
static str> {
723 fn to_opt_strs(self) -> Vec
<Option
<&'
static str>> {
727 AllNodesLabelled(lbls
)
728 => lbls
.into_iter().map(
729 |l
|Some(l
)).collect(),
730 SomeNodesLabelled(lbls
)
731 => lbls
.into_iter().collect(),
735 fn len(&self) -> usize {
737 &UnlabelledNodes(len
) => len
,
738 &AllNodesLabelled(ref lbls
) => lbls
.len(),
739 &SomeNodesLabelled(ref lbls
) => lbls
.len(),
745 fn new(name
: &'
static str,
746 node_labels
: Trivial
,
748 node_styles
: Option
<Vec
<Style
>>) -> LabelledGraph
{
749 let count
= node_labels
.len();
752 node_labels
: node_labels
.to_opt_strs(),
754 node_styles
: match node_styles
{
755 Some(nodes
) => nodes
,
756 None
=> vec
![Style
::None
; count
],
762 impl LabelledGraphWithEscStrs
{
763 fn new(name
: &'
static str,
764 node_labels
: Trivial
,
765 edges
: Vec
<Edge
>) -> LabelledGraphWithEscStrs
{
766 LabelledGraphWithEscStrs
{
767 graph
: LabelledGraph
::new(name
,
775 fn id_name
<'a
>(n
: &Node
) -> Id
<'a
> {
776 Id
::new(format
!("N{}", *n
)).unwrap()
779 impl<'a
> Labeller
<'a
, Node
, &'a Edge
> for LabelledGraph
{
780 fn graph_id(&'a
self) -> Id
<'a
> {
781 Id
::new(&self.name
[..]).unwrap()
783 fn node_id(&'a
self, n
: &Node
) -> Id
<'a
> {
786 fn node_label(&'a
self, n
: &Node
) -> LabelText
<'a
> {
787 match self.node_labels
[*n
] {
788 Some(ref l
) => LabelStr(l
.into_cow()),
789 None
=> LabelStr(id_name(n
).name()),
792 fn edge_label(&'a
self, e
: & &'a Edge
) -> LabelText
<'a
> {
793 LabelStr(e
.label
.into_cow())
795 fn node_style(&'a
self, n
: &Node
) -> Style
{
798 fn edge_style(&'a
self, e
: & &'a Edge
) -> Style
{
803 impl<'a
> Labeller
<'a
, Node
, &'a Edge
> for LabelledGraphWithEscStrs
{
804 fn graph_id(&'a
self) -> Id
<'a
> { self.graph.graph_id() }
805 fn node_id(&'a
self, n
: &Node
) -> Id
<'a
> { self.graph.node_id(n) }
806 fn node_label(&'a
self, n
: &Node
) -> LabelText
<'a
> {
807 match self.graph
.node_label(n
) {
808 LabelStr(s
) | EscStr(s
) => EscStr(s
),
811 fn edge_label(&'a
self, e
: & &'a Edge
) -> LabelText
<'a
> {
812 match self.graph
.edge_label(e
) {
813 LabelStr(s
) | EscStr(s
) => EscStr(s
),
818 impl<'a
> GraphWalk
<'a
, Node
, &'a Edge
> for LabelledGraph
{
819 fn nodes(&'a
self) -> Nodes
<'a
,Node
> {
820 (0..self.node_labels
.len()).collect()
822 fn edges(&'a
self) -> Edges
<'a
,&'a Edge
> {
823 self.edges
.iter().collect()
825 fn source(&'a
self, edge
: & &'a Edge
) -> Node
{
828 fn target(&'a
self, edge
: & &'a Edge
) -> Node
{
833 impl<'a
> GraphWalk
<'a
, Node
, &'a Edge
> for LabelledGraphWithEscStrs
{
834 fn nodes(&'a
self) -> Nodes
<'a
,Node
> {
837 fn edges(&'a
self) -> Edges
<'a
,&'a Edge
> {
840 fn source(&'a
self, edge
: & &'a Edge
) -> Node
{
843 fn target(&'a
self, edge
: & &'a Edge
) -> Node
{
848 fn test_input(g
: LabelledGraph
) -> io
::Result
<String
> {
849 let mut writer
= Vec
::new();
850 render(&g
, &mut writer
).unwrap();
851 let mut s
= String
::new();
852 try
!(Read
::read_to_string(&mut &*writer
, &mut s
));
856 // All of the tests use raw-strings as the format for the expected outputs,
857 // so that you can cut-and-paste the content into a .dot file yourself to
858 // see what the graphviz visualizer would produce.
862 let labels
: Trivial
= UnlabelledNodes(0);
863 let r
= test_input(LabelledGraph
::new("empty_graph", labels
, vec
![], None
));
864 assert_eq
!(r
.unwrap(),
865 r
#"digraph empty_graph {
872 let labels
: Trivial
= UnlabelledNodes(1);
873 let r
= test_input(LabelledGraph
::new("single_node", labels
, vec
![], None
));
874 assert_eq
!(r
.unwrap(),
875 r
#"digraph single_node {
882 fn single_node_with_style() {
883 let labels
: Trivial
= UnlabelledNodes(1);
884 let styles
= Some(vec
![Style
::Dashed
]);
885 let r
= test_input(LabelledGraph
::new("single_node", labels
, vec
![], styles
));
886 assert_eq
!(r
.unwrap(),
887 r
#"digraph single_node {
888 N0[label="N0"][style="dashed"];
895 let labels
: Trivial
= UnlabelledNodes(2);
896 let result
= test_input(LabelledGraph
::new("single_edge", labels
,
897 vec
![edge(0, 1, "E", Style
::None
)], None
));
898 assert_eq
!(result
.unwrap(),
899 r
#"digraph single_edge {
908 fn single_edge_with_style() {
909 let labels
: Trivial
= UnlabelledNodes(2);
910 let result
= test_input(LabelledGraph
::new("single_edge", labels
,
911 vec
![edge(0, 1, "E", Style
::Bold
)], None
));
912 assert_eq
!(result
.unwrap(),
913 r
#"digraph single_edge {
916 N0 -> N1[label="E"][style="bold"];
922 fn test_some_labelled() {
923 let labels
: Trivial
= SomeNodesLabelled(vec
![Some("A"), None
]);
924 let styles
= Some(vec
![Style
::None
, Style
::Dotted
]);
925 let result
= test_input(LabelledGraph
::new("test_some_labelled", labels
,
926 vec
![edge(0, 1, "A-1", Style
::None
)], styles
));
927 assert_eq
!(result
.unwrap(),
928 r
#"digraph test_some_labelled {
930 N1[label="N1"][style="dotted"];
931 N0 -> N1[label="A-1"];
937 fn single_cyclic_node() {
938 let labels
: Trivial
= UnlabelledNodes(1);
939 let r
= test_input(LabelledGraph
::new("single_cyclic_node", labels
,
940 vec
![edge(0, 0, "E", Style
::None
)], None
));
941 assert_eq
!(r
.unwrap(),
942 r
#"digraph single_cyclic_node {
951 let labels
= AllNodesLabelled(vec
!("{x,y}", "{x}", "{y}", "{}"));
952 let r
= test_input(LabelledGraph
::new(
953 "hasse_diagram", labels
,
954 vec
![edge(0, 1, "", Style
::None
), edge(0, 2, "", Style
::None
),
955 edge(1, 3, "", Style
::None
), edge(2, 3, "", Style
::None
)],
957 assert_eq
!(r
.unwrap(),
958 r
#"digraph hasse_diagram {
972 fn left_aligned_text() {
973 let labels
= AllNodesLabelled(vec
!(
985 let mut writer
= Vec
::new();
987 let g
= LabelledGraphWithEscStrs
::new(
988 "syntax_tree", labels
,
989 vec
![edge(0, 1, "then", Style
::None
), edge(0, 2, "else", Style
::None
),
990 edge(1, 3, ";", Style
::None
), edge(2, 3, ";", Style
::None
)]);
992 render(&g
, &mut writer
).unwrap();
993 let mut r
= String
::new();
994 Read
::read_to_string(&mut &*writer
, &mut r
).unwrap();
997 r
#"digraph syntax_tree {
998 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
1000 N2[label="branch2"];
1001 N3[label="afterward"];
1002 N0 -> N1[label="then"];
1003 N0 -> N2[label="else"];
1004 N1 -> N3[label=";"];
1005 N2 -> N3[label=";"];
1011 fn simple_id_construction() {
1012 let id1
= Id
::new("hello");
1015 Err(..) => panic
!("'hello' is not a valid value for id anymore")
1020 fn badly_formatted_id() {
1021 let id2
= Id
::new("Weird { struct : ure } !!!");
1023 Ok(_
) => panic
!("graphviz id suddenly allows spaces, brackets and stuff"),