1 // Copyright 2014 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 `CowVec` 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 //! use graphviz as dot;
53 //! type Ed = (int,int);
54 //! struct Edges(Vec<Ed>);
56 //! pub fn render_to<W:Writer>(output: &mut W) {
57 //! let edges = Edges(vec!((0,1), (0,2), (1,3), (2,3), (3,4), (4,4)));
58 //! dot::render(&edges, output).unwrap()
61 //! impl<'a> dot::Labeller<'a, Nd, Ed> for Edges {
62 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example1").unwrap() }
64 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
65 //! dot::Id::new(format!("N{}", *n)).unwrap()
69 //! impl<'a> dot::GraphWalk<'a, Nd, Ed> for Edges {
70 //! fn nodes(&self) -> dot::Nodes<'a,Nd> {
71 //! // (assumes that |N| \approxeq |E|)
72 //! let &Edges(ref v) = self;
73 //! let mut nodes = Vec::with_capacity(v.len());
74 //! for &(s,t) in v.iter() {
75 //! nodes.push(s); nodes.push(t);
82 //! fn edges(&'a self) -> dot::Edges<'a,Ed> {
83 //! let &Edges(ref edges) = self;
84 //! edges.as_slice().into_cow()
87 //! fn source(&self, e: &Ed) -> Nd { let &(s,_) = e; s }
89 //! fn target(&self, e: &Ed) -> Nd { let &(_,t) = e; t }
92 //! # pub fn main() { render_to(&mut Vec::new()) }
96 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
98 //! use std::io::File;
99 //! let mut f = File::create(&Path::new("example1.dot"));
100 //! render_to(&mut f)
104 //! Output from first example (in `example1.dot`):
107 //! digraph example1 {
113 //! N0 -> N1[label=""];
114 //! N0 -> N2[label=""];
115 //! N1 -> N3[label=""];
116 //! N2 -> N3[label=""];
117 //! N3 -> N4[label=""];
118 //! N4 -> N4[label=""];
122 //! The second example illustrates using `node_label` and `edge_label` to
123 //! add labels to the nodes and edges in the rendered graph. The graph
124 //! here carries both `nodes` (the label text to use for rendering a
125 //! particular node), and `edges` (again a list of `(source,target)`
128 //! This example also illustrates how to use a type (in this case the edge
129 //! type) that shares substructure with the graph: the edge type here is a
130 //! direct reference to the `(source,target)` pair stored in the graph's
131 //! internal vector (rather than passing around a copy of the pair
132 //! itself). Note that this implies that `fn edges(&'a self)` must
133 //! construct a fresh `Vec<&'a (uint,uint)>` from the `Vec<(uint,uint)>`
134 //! edges stored in `self`.
136 //! Since both the set of nodes and the set of edges are always
137 //! constructed from scratch via iterators, we use the `collect()` method
138 //! from the `Iterator` trait to collect the nodes and edges into freshly
139 //! constructed growable `Vec` values (rather use the `into_cow`
140 //! from the `IntoCow` trait as was used in the first example
143 //! The output from this example renders four nodes that make up the
144 //! Hasse-diagram for the subsets of the set `{x, y}`. Each edge is
145 //! labelled with the ⊆ character (specified using the HTML character
149 //! use graphviz as dot;
152 //! type Ed<'a> = &'a (uint, uint);
153 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
155 //! pub fn render_to<W:Writer>(output: &mut W) {
156 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
157 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
158 //! let graph = Graph { nodes: nodes, edges: edges };
160 //! dot::render(&graph, output).unwrap()
163 //! impl<'a> dot::Labeller<'a, Nd, Ed<'a>> for Graph {
164 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example2").unwrap() }
165 //! fn node_id(&'a self, n: &Nd) -> dot::Id<'a> {
166 //! dot::Id::new(format!("N{}", n)).unwrap()
168 //! fn node_label<'a>(&'a self, n: &Nd) -> dot::LabelText<'a> {
169 //! dot::LabelStr(self.nodes[*n].as_slice().into_cow())
171 //! fn edge_label<'a>(&'a self, _: &Ed) -> dot::LabelText<'a> {
172 //! dot::LabelStr("⊆".into_cow())
176 //! impl<'a> dot::GraphWalk<'a, Nd, Ed<'a>> for Graph {
177 //! fn nodes(&self) -> dot::Nodes<'a,Nd> { range(0,self.nodes.len()).collect() }
178 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> { self.edges.iter().collect() }
179 //! fn source(&self, e: &Ed) -> Nd { let & &(s,_) = e; s }
180 //! fn target(&self, e: &Ed) -> Nd { let & &(_,t) = e; t }
183 //! # pub fn main() { render_to(&mut Vec::new()) }
187 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
189 //! use std::io::File;
190 //! let mut f = File::create(&Path::new("example2.dot"));
191 //! render_to(&mut f)
195 //! The third example is similar to the second, except now each node and
196 //! edge now carries a reference to the string label for each node as well
197 //! as that node's index. (This is another illustration of how to share
198 //! structure with the graph itself, and why one might want to do so.)
200 //! The output from this example is the same as the second example: the
201 //! Hasse-diagram for the subsets of the set `{x, y}`.
204 //! use graphviz as dot;
206 //! type Nd<'a> = (uint, &'a str);
207 //! type Ed<'a> = (Nd<'a>, Nd<'a>);
208 //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
210 //! pub fn render_to<W:Writer>(output: &mut W) {
211 //! let nodes = vec!("{x,y}","{x}","{y}","{}");
212 //! let edges = vec!((0,1), (0,2), (1,3), (2,3));
213 //! let graph = Graph { nodes: nodes, edges: edges };
215 //! dot::render(&graph, output).unwrap()
218 //! impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph {
219 //! fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() }
220 //! fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> {
221 //! dot::Id::new(format!("N{}", n.val0())).unwrap()
223 //! fn node_label<'a>(&'a self, n: &Nd<'a>) -> dot::LabelText<'a> {
225 //! dot::LabelStr(self.nodes[i].as_slice().into_cow())
227 //! fn edge_label<'a>(&'a self, _: &Ed<'a>) -> dot::LabelText<'a> {
228 //! dot::LabelStr("⊆".into_cow())
232 //! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
233 //! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
234 //! self.nodes.iter().map(|s|s.as_slice()).enumerate().collect()
236 //! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
237 //! self.edges.iter()
238 //! .map(|&(i,j)|((i, self.nodes[i].as_slice()),
239 //! (j, self.nodes[j].as_slice())))
242 //! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
243 //! fn target(&self, e: &Ed<'a>) -> Nd<'a> { let &(_,t) = e; t }
246 //! # pub fn main() { render_to(&mut Vec::new()) }
250 //! # pub fn render_to<W:Writer>(output: &mut W) { unimplemented!() }
252 //! use std::io::File;
253 //! let mut f = File::create(&Path::new("example3.dot"));
254 //! render_to(&mut f)
260 //! * [Graphviz](http://www.graphviz.org/)
262 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
264 #![crate_name = "graphviz"]
266 #![crate_type = "rlib"]
267 #![crate_type = "dylib"]
268 #![license = "MIT/ASL2"]
269 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
270 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
271 html_root_url = "http://doc.rust-lang.org/nightly/")]
272 #![feature(globs, slicing_syntax)]
274 pub use self::LabelText::*;
277 use std::str::CowString;
278 use std::vec::CowVec;
280 pub mod maybe_owned_vec;
282 /// The text for a graphviz label on a node or edge.
283 pub enum LabelText<'a> {
284 /// This kind of label preserves the text directly as is.
286 /// Occurrences of backslashes (`\`) are escaped, and thus appear
287 /// as backslashes in the rendered label.
288 LabelStr(CowString<'a>),
290 /// This kind of label uses the graphviz label escString type:
291 /// http://www.graphviz.org/content/attrs#kescString
293 /// Occurrences of backslashes (`\`) are not escaped; instead they
294 /// are interpreted as initiating an escString escape sequence.
296 /// Escape sequences of particular interest: in addition to `\n`
297 /// to break a line (centering the line preceding the `\n`), there
298 /// are also the escape sequences `\l` which left-justifies the
299 /// preceding line and `\r` which right-justifies it.
300 EscStr(CowString<'a>),
303 // There is a tension in the design of the labelling API.
305 // For example, I considered making a `Labeller<T>` trait that
306 // provides labels for `T`, and then making the graph type `G`
307 // implement `Labeller<Node>` and `Labeller<Edge>`. However, this is
308 // not possible without functional dependencies. (One could work
309 // around that, but I did not explore that avenue heavily.)
311 // Another approach that I actually used for a while was to make a
312 // `Label<Context>` trait that is implemented by the client-specific
313 // Node and Edge types (as well as an implementation on Graph itself
314 // for the overall name for the graph). The main disadvantage of this
315 // second approach (compared to having the `G` type parameter
316 // implement a Labelling service) that I have encountered is that it
317 // makes it impossible to use types outside of the current crate
318 // directly as Nodes/Edges; you need to wrap them in newtype'd
319 // structs. See e.g. the `No` and `Ed` structs in the examples. (In
320 // practice clients using a graph in some other crate would need to
321 // provide some sort of adapter shim over the graph anyway to
322 // interface with this library).
324 // Another approach would be to make a single `Labeller<N,E>` trait
325 // that provides three methods (graph_label, node_label, edge_label),
326 // and then make `G` implement `Labeller<N,E>`. At first this did not
327 // appeal to me, since I had thought I would need separate methods on
328 // each data variant for dot-internal identifiers versus user-visible
329 // labels. However, the identifier/label distinction only arises for
330 // nodes; graphs themselves only have identifiers, and edges only have
333 // So in the end I decided to use the third approach described above.
335 /// `Id` is a Graphviz `ID`.
341 /// Creates an `Id` named `name`.
343 /// The caller must ensure that the input conforms to an
344 /// identifier format: it must be a non-empty string made up of
345 /// alphanumeric or underscore characters, not beginning with a
346 /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
348 /// (Note: this format is a strict subset of the `ID` format
349 /// defined by the DOT language. This function may change in the
350 /// future to accept a broader subset, or the entirety, of DOT's
353 /// Passing an invalid string (containing spaces, brackets,
354 /// quotes, ...) will return an empty `Err` value.
355 pub fn new<Name: IntoCow<'a, String, str>>(name: Name) -> Result<Id<'a>, ()> {
356 let name = name.into_cow();
358 let mut chars = name.chars();
360 Some(c) if is_letter_or_underscore(c) => { ; },
363 if !chars.all(is_constituent) {
367 return Ok(Id{ name: name });
369 fn is_letter_or_underscore(c: char) -> bool {
370 in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
372 fn is_constituent(c: char) -> bool {
373 is_letter_or_underscore(c) || in_range('0', c, '9')
375 fn in_range(low: char, c: char, high: char) -> bool {
376 low as uint <= c as uint && c as uint <= high as uint
380 pub fn as_slice(&'a self) -> &'a str {
384 pub fn name(self) -> CowString<'a> {
389 /// Each instance of a type that implements `Label<C>` maps to a
390 /// unique identifier with respect to `C`, which is used to identify
391 /// it in the generated .dot file. They can also provide more
392 /// elaborate (and non-unique) label text that is used in the graphviz
395 /// The graph instance is responsible for providing the DOT compatible
396 /// identifiers for the nodes and (optionally) rendered labels for the nodes and
397 /// edges, as well as an identifier for the graph itself.
398 pub trait Labeller<'a,N,E> {
399 /// Must return a DOT compatible identifier naming the graph.
400 fn graph_id(&'a self) -> Id<'a>;
402 /// Maps `n` to a unique identifier with respect to `self`. The
403 /// implementer is responsible for ensuring that the returned name
404 /// is a valid DOT identifier.
405 fn node_id(&'a self, n: &N) -> Id<'a>;
407 /// Maps `n` to a label that will be used in the rendered output.
408 /// The label need not be unique, and may be the empty string; the
409 /// default is just the output from `node_id`.
410 fn node_label(&'a self, n: &N) -> LabelText<'a> {
411 LabelStr(self.node_id(n).name)
414 /// Maps `e` to a label that will be used in the rendered output.
415 /// The label need not be unique, and may be the empty string; the
416 /// default is in fact the empty string.
417 fn edge_label(&'a self, e: &E) -> LabelText<'a> {
419 LabelStr("".into_cow())
423 impl<'a> LabelText<'a> {
424 fn escape_char(c: char, f: |char|) {
426 // not escaping \\, since Graphviz escString needs to
427 // interpret backslashes; see EscStr above.
429 _ => for c in c.escape_default() { f(c) }
432 fn escape_str(s: &str) -> String {
433 let mut out = String::with_capacity(s.len());
435 LabelText::escape_char(c, |c| out.push(c));
440 /// Renders text as string suitable for a label in a .dot file.
441 pub fn escape(&self) -> String {
443 &LabelStr(ref s) => s.as_slice().escape_default(),
444 &EscStr(ref s) => LabelText::escape_str(s.as_slice()),
448 /// Decomposes content into string suitable for making EscStr that
449 /// yields same content as self. The result obeys the law
450 /// render(`lt`) == render(`EscStr(lt.pre_escaped_content())`) for
451 /// all `lt: LabelText`.
452 fn pre_escaped_content(self) -> CowString<'a> {
455 LabelStr(s) => if s.contains_char('\\') {
456 s.escape_default().into_cow()
463 /// Puts `prefix` on a line above this label, with a blank line separator.
464 pub fn prefix_line(self, prefix: LabelText) -> LabelText<'static> {
465 prefix.suffix_line(self)
468 /// Puts `suffix` on a line below this label, with a blank line separator.
469 pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
470 let mut prefix = self.pre_escaped_content().into_string();
471 let suffix = suffix.pre_escaped_content();
472 prefix.push_str(r"\n\n");
473 prefix.push_str(suffix.as_slice());
474 EscStr(prefix.into_cow())
478 pub type Nodes<'a,N> = CowVec<'a,N>;
479 pub type Edges<'a,E> = CowVec<'a,E>;
481 // (The type parameters in GraphWalk should be associated items,
482 // when/if Rust supports such.)
484 /// GraphWalk is an abstraction over a directed graph = (nodes,edges)
485 /// made up of node handles `N` and edge handles `E`, where each `E`
486 /// can be mapped to its source and target nodes.
488 /// The lifetime parameter `'a` is exposed in this trait (rather than
489 /// introduced as a generic parameter on each method declaration) so
490 /// that a client impl can choose `N` and `E` that have substructure
491 /// that is bound by the self lifetime `'a`.
493 /// The `nodes` and `edges` method each return instantiations of
494 /// `CowVec` to leave implementers the freedom to create
495 /// entirely new vectors or to pass back slices into internally owned
497 pub trait GraphWalk<'a, N, E> {
498 /// Returns all the nodes in this graph.
499 fn nodes(&'a self) -> Nodes<'a, N>;
500 /// Returns all of the edges in this graph.
501 fn edges(&'a self) -> Edges<'a, E>;
502 /// The source node for `edge`.
503 fn source(&'a self, edge: &E) -> N;
504 /// The target node for `edge`.
505 fn target(&'a self, edge: &E) -> N;
508 /// Renders directed graph `g` into the writer `w` in DOT syntax.
509 /// (Main entry point for the library.)
510 pub fn render<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N,E>, W:Writer>(
512 w: &mut W) -> io::IoResult<()>
514 fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> io::IoResult<()> {
515 for &s in arg.iter() { try!(w.write_str(s)); }
519 fn indent<W:Writer>(w: &mut W) -> io::IoResult<()> {
523 try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"]));
524 for n in g.nodes().iter() {
526 let id = g.node_id(n);
527 let escaped = g.node_label(n).escape();
528 try!(writeln(w, &[id.as_slice(),
529 "[label=\"", escaped.as_slice(), "\"];"]));
532 for e in g.edges().iter() {
533 let escaped_label = g.edge_label(e).escape();
535 let source = g.source(e);
536 let target = g.target(e);
537 let source_id = g.node_id(&source);
538 let target_id = g.node_id(&target);
539 try!(writeln(w, &[source_id.as_slice(), " -> ", target_id.as_slice(),
540 "[label=\"", escaped_label.as_slice(), "\"];"]));
548 use self::NodeLabels::*;
549 use super::{Id, LabelText, LabelStr, EscStr, Labeller};
550 use super::{Nodes, Edges, GraphWalk, render};
551 use std::io::{BufReader, IoResult};
554 /// each node is an index in a vector in the graph.
557 from: uint, to: uint, label: &'static str
560 fn edge(from: uint, to: uint, label: &'static str) -> Edge {
561 Edge { from: from, to: to, label: label }
564 struct LabelledGraph {
565 /// The name for this graph. Used for labelling generated `digraph`.
568 /// Each node is an index into `node_labels`; these labels are
569 /// used as the label text for each node. (The node *names*,
570 /// which are unique identifiers, are derived from their index
573 /// If a node maps to None here, then just use its name as its
575 node_labels: Vec<Option<&'static str>>,
577 /// Each edge relates a from-index to a to-index along with a
578 /// label; `edges` collects them.
582 // A simple wrapper around LabelledGraph that forces the labels to
583 // be emitted as EscStr.
584 struct LabelledGraphWithEscStrs {
589 AllNodesLabelled(Vec<L>),
590 UnlabelledNodes(uint),
591 SomeNodesLabelled(Vec<Option<L>>),
594 type Trivial = NodeLabels<&'static str>;
596 impl NodeLabels<&'static str> {
597 fn to_opt_strs(self) -> Vec<Option<&'static str>> {
600 => Vec::from_elem(len, None).into_iter().collect(),
601 AllNodesLabelled(lbls)
602 => lbls.into_iter().map(
603 |l|Some(l)).collect(),
604 SomeNodesLabelled(lbls)
605 => lbls.into_iter().collect(),
611 fn new(name: &'static str,
612 node_labels: Trivial,
613 edges: Vec<Edge>) -> LabelledGraph {
616 node_labels: node_labels.to_opt_strs(),
622 impl LabelledGraphWithEscStrs {
623 fn new(name: &'static str,
624 node_labels: Trivial,
625 edges: Vec<Edge>) -> LabelledGraphWithEscStrs {
626 LabelledGraphWithEscStrs {
627 graph: LabelledGraph::new(name, node_labels, edges)
632 fn id_name<'a>(n: &Node) -> Id<'a> {
633 Id::new(format!("N{}", *n)).unwrap()
636 impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph {
637 fn graph_id(&'a self) -> Id<'a> {
638 Id::new(self.name.as_slice()).unwrap()
640 fn node_id(&'a self, n: &Node) -> Id<'a> {
643 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
644 match self.node_labels[*n] {
645 Some(ref l) => LabelStr(l.into_cow()),
646 None => LabelStr(id_name(n).name()),
649 fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
650 LabelStr(e.label.into_cow())
654 impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
655 fn graph_id(&'a self) -> Id<'a> { self.graph.graph_id() }
656 fn node_id(&'a self, n: &Node) -> Id<'a> { self.graph.node_id(n) }
657 fn node_label(&'a self, n: &Node) -> LabelText<'a> {
658 match self.graph.node_label(n) {
659 LabelStr(s) | EscStr(s) => EscStr(s),
662 fn edge_label(&'a self, e: & &'a Edge) -> LabelText<'a> {
663 match self.graph.edge_label(e) {
664 LabelStr(s) | EscStr(s) => EscStr(s),
669 impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraph {
670 fn nodes(&'a self) -> Nodes<'a,Node> {
671 range(0u, self.node_labels.len()).collect()
673 fn edges(&'a self) -> Edges<'a,&'a Edge> {
674 self.edges.iter().collect()
676 fn source(&'a self, edge: & &'a Edge) -> Node {
679 fn target(&'a self, edge: & &'a Edge) -> Node {
684 impl<'a> GraphWalk<'a, Node, &'a Edge> for LabelledGraphWithEscStrs {
685 fn nodes(&'a self) -> Nodes<'a,Node> {
688 fn edges(&'a self) -> Edges<'a,&'a Edge> {
691 fn source(&'a self, edge: & &'a Edge) -> Node {
694 fn target(&'a self, edge: & &'a Edge) -> Node {
699 fn test_input(g: LabelledGraph) -> IoResult<String> {
700 let mut writer = Vec::new();
701 render(&g, &mut writer).unwrap();
702 let mut r = BufReader::new(writer[]);
706 // All of the tests use raw-strings as the format for the expected outputs,
707 // so that you can cut-and-paste the content into a .dot file yourself to
708 // see what the graphviz visualizer would produce.
712 let labels : Trivial = UnlabelledNodes(0);
713 let r = test_input(LabelledGraph::new("empty_graph", labels, vec!()));
714 assert_eq!(r.unwrap().as_slice(),
715 r#"digraph empty_graph {
722 let labels : Trivial = UnlabelledNodes(1);
723 let r = test_input(LabelledGraph::new("single_node", labels, vec!()));
724 assert_eq!(r.unwrap().as_slice(),
725 r#"digraph single_node {
733 let labels : Trivial = UnlabelledNodes(2);
734 let result = test_input(LabelledGraph::new("single_edge", labels,
735 vec!(edge(0, 1, "E"))));
736 assert_eq!(result.unwrap().as_slice(),
737 r#"digraph single_edge {
746 fn test_some_labelled() {
747 let labels : Trivial = SomeNodesLabelled(vec![Some("A"), None]);
748 let result = test_input(LabelledGraph::new("test_some_labelled", labels,
749 vec![edge(0, 1, "A-1")]));
750 assert_eq!(result.unwrap().as_slice(),
751 r#"digraph test_some_labelled {
754 N0 -> N1[label="A-1"];
760 fn single_cyclic_node() {
761 let labels : Trivial = UnlabelledNodes(1);
762 let r = test_input(LabelledGraph::new("single_cyclic_node", labels,
763 vec!(edge(0, 0, "E"))));
764 assert_eq!(r.unwrap().as_slice(),
765 r#"digraph single_cyclic_node {
774 let labels = AllNodesLabelled(vec!("{x,y}", "{x}", "{y}", "{}"));
775 let r = test_input(LabelledGraph::new(
776 "hasse_diagram", labels,
777 vec!(edge(0, 1, ""), edge(0, 2, ""),
778 edge(1, 3, ""), edge(2, 3, ""))));
779 assert_eq!(r.unwrap().as_slice(),
780 r#"digraph hasse_diagram {
794 fn left_aligned_text() {
795 let labels = AllNodesLabelled(vec!(
807 let mut writer = Vec::new();
809 let g = LabelledGraphWithEscStrs::new(
810 "syntax_tree", labels,
811 vec!(edge(0, 1, "then"), edge(0, 2, "else"),
812 edge(1, 3, ";"), edge(2, 3, ";" )));
814 render(&g, &mut writer).unwrap();
815 let mut r = BufReader::new(writer[]);
816 let r = r.read_to_string();
818 assert_eq!(r.unwrap().as_slice(),
819 r#"digraph syntax_tree {
820 N0[label="if test {\l branch1\l} else {\l branch2\l}\lafterward\l"];
823 N3[label="afterward"];
824 N0 -> N1[label="then"];
825 N0 -> N2[label="else"];
833 fn simple_id_construction() {
834 let id1 = Id::new("hello");
837 Err(_) => panic!("'hello' is not a valid value for id anymore")
842 fn badly_formatted_id() {
843 let id2 = Id::new("Weird { struct : ure } !!!");
845 Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),