fast-rustc-ap-graphviz 1.0.0

Automatically published version of the package `graphviz` in the rust-lang/rust repository from commit 15812785344d913d779d9738fe3cca8de56f71d5 The publishing script for this crate lives at: https://github.com/alexcrichton/rustc-auto-publish
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use super::LabelText::{self, EscStr, HtmlStr, LabelStr};
use super::{render, Edges, GraphWalk, Id, Labeller, Nodes, Style};
use std::io;
use std::io::prelude::*;
use NodeLabels::*;

/// each node is an index in a vector in the graph.
type Node = usize;
struct Edge {
    from: usize,
    to: usize,
    label: &'static str,
    style: Style,
}

fn edge(from: usize, to: usize, label: &'static str, style: Style) -> Edge {
    Edge { from, to, label, style }
}

struct LabelledGraph {
    /// The name for this graph. Used for labeling generated `digraph`.
    name: &'static str,

    /// Each node is an index into `node_labels`; these labels are
    /// used as the label text for each node. (The node *names*,
    /// which are unique identifiers, are derived from their index
    /// in this array.)
    ///
    /// If a node maps to None here, then just use its name as its
    /// text.
    node_labels: Vec<Option<&'static str>>,

    node_styles: Vec<Style>,

    /// Each edge relates a from-index to a to-index along with a
    /// label; `edges` collects them.
    edges: Vec<Edge>,
}

// A simple wrapper around LabelledGraph that forces the labels to
// be emitted as EscStr.
struct LabelledGraphWithEscStrs {
    graph: LabelledGraph,
}

enum NodeLabels<L> {
    AllNodesLabelled(Vec<L>),
    UnlabelledNodes(usize),
    SomeNodesLabelled(Vec<Option<L>>),
}

type Trivial = NodeLabels<&'static str>;

impl NodeLabels<&'static str> {
    fn to_opt_strs(self) -> Vec<Option<&'static str>> {
        match self {
            UnlabelledNodes(len) => vec![None; len],
            AllNodesLabelled(lbls) => lbls.into_iter().map(|l| Some(l)).collect(),
            SomeNodesLabelled(lbls) => lbls.into_iter().collect(),
        }
    }

    fn len(&self) -> usize {
        match self {
            &UnlabelledNodes(len) => len,
            &AllNodesLabelled(ref lbls) => lbls.len(),
            &SomeNodesLabelled(ref lbls) => lbls.len(),
        }
    }
}

impl LabelledGraph {
    fn new(
        name: &'static str,
        node_labels: Trivial,
        edges: Vec<Edge>,
        node_styles: Option<Vec<Style>>,
    ) -> LabelledGraph {
        let count = node_labels.len();
        LabelledGraph {
            name,
            node_labels: node_labels.to_opt_strs(),
            edges,
            node_styles: match node_styles {
                Some(nodes) => nodes,
                None => vec![Style::None; count],
            },
        }
    }
}

impl LabelledGraphWithEscStrs {
    fn new(name: &'static str, node_labels: Trivial, edges: Vec<Edge>) -> LabelledGraphWithEscStrs {
        LabelledGraphWithEscStrs { graph: LabelledGraph::new(name, node_labels, edges, None) }
    }
}

fn id_name<'a>(n: &Node) -> Id<'a> {
    Id::new(format!("N{}", *n)).unwrap()
}

impl<'a> Labeller<'a> for LabelledGraph {
    type Node = Node;
    type Edge = &'a Edge;
    fn graph_id(&'a self) -> Id<'a> {
        Id::new(self.name).unwrap()
    }
    fn node_id(&'a self, n: &Node) -> Id<'a> {
        id_name(n)
    }
    fn node_label(&'a self, n: &Node) -> LabelText<'a> {
        match self.node_labels[*n] {
            Some(l) => LabelStr(l.into()),
            None => LabelStr(id_name(n).name()),
        }
    }
    fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
        LabelStr(e.label.into())
    }
    fn node_style(&'a self, n: &Node) -> Style {
        self.node_styles[*n]
    }
    fn edge_style(&'a self, e: &&'a Edge) -> Style {
        e.style
    }
}

impl<'a> Labeller<'a> for LabelledGraphWithEscStrs {
    type Node = Node;
    type Edge = &'a Edge;
    fn graph_id(&'a self) -> Id<'a> {
        self.graph.graph_id()
    }
    fn node_id(&'a self, n: &Node) -> Id<'a> {
        self.graph.node_id(n)
    }
    fn node_label(&'a self, n: &Node) -> LabelText<'a> {
        match self.graph.node_label(n) {
            LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
        }
    }
    fn edge_label(&'a self, e: &&'a Edge) -> LabelText<'a> {
        match self.graph.edge_label(e) {
            LabelStr(s) | EscStr(s) | HtmlStr(s) => EscStr(s),
        }
    }
}

impl<'a> GraphWalk<'a> for LabelledGraph {
    type Node = Node;
    type Edge = &'a Edge;
    fn nodes(&'a self) -> Nodes<'a, Node> {
        (0..self.node_labels.len()).collect()
    }
    fn edges(&'a self) -> Edges<'a, &'a Edge> {
        self.edges.iter().collect()
    }
    fn source(&'a self, edge: &&'a Edge) -> Node {
        edge.from
    }
    fn target(&'a self, edge: &&'a Edge) -> Node {
        edge.to
    }
}

impl<'a> GraphWalk<'a> for LabelledGraphWithEscStrs {
    type Node = Node;
    type Edge = &'a Edge;
    fn nodes(&'a self) -> Nodes<'a, Node> {
        self.graph.nodes()
    }
    fn edges(&'a self) -> Edges<'a, &'a Edge> {
        self.graph.edges()
    }
    fn source(&'a self, edge: &&'a Edge) -> Node {
        edge.from
    }
    fn target(&'a self, edge: &&'a Edge) -> Node {
        edge.to
    }
}

fn test_input(g: LabelledGraph) -> io::Result<String> {
    let mut writer = Vec::new();
    render(&g, &mut writer).unwrap();
    let mut s = String::new();
    Read::read_to_string(&mut &*writer, &mut s)?;
    Ok(s)
}

// All of the tests use raw-strings as the format for the expected outputs,
// so that you can cut-and-paste the content into a .dot file yourself to
// see what the graphviz visualizer would produce.

#[test]
fn empty_graph() {
    let labels: Trivial = UnlabelledNodes(0);
    let r = test_input(LabelledGraph::new("empty_graph", labels, vec![], None));
    assert_eq!(
        r.unwrap(),
        r#"digraph empty_graph {
}
"#
    );
}

#[test]
fn single_node() {
    let labels: Trivial = UnlabelledNodes(1);
    let r = test_input(LabelledGraph::new("single_node", labels, vec![], None));
    assert_eq!(
        r.unwrap(),
        r#"digraph single_node {
    N0[label="N0"];
}
"#
    );
}

#[test]
fn single_node_with_style() {
    let labels: Trivial = UnlabelledNodes(1);
    let styles = Some(vec![Style::Dashed]);
    let r = test_input(LabelledGraph::new("single_node", labels, vec![], styles));
    assert_eq!(
        r.unwrap(),
        r#"digraph single_node {
    N0[label="N0"][style="dashed"];
}
"#
    );
}

#[test]
fn single_edge() {
    let labels: Trivial = UnlabelledNodes(2);
    let result = test_input(LabelledGraph::new(
        "single_edge",
        labels,
        vec![edge(0, 1, "E", Style::None)],
        None,
    ));
    assert_eq!(
        result.unwrap(),
        r#"digraph single_edge {
    N0[label="N0"];
    N1[label="N1"];
    N0 -> N1[label="E"];
}
"#
    );
}

#[test]
fn single_edge_with_style() {
    let labels: Trivial = UnlabelledNodes(2);
    let result = test_input(LabelledGraph::new(
        "single_edge",
        labels,
        vec![edge(0, 1, "E", Style::Bold)],
        None,
    ));
    assert_eq!(
        result.unwrap(),
        r#"digraph single_edge {
    N0[label="N0"];
    N1[label="N1"];
    N0 -> N1[label="E"][style="bold"];
}
"#
    );
}

#[test]
fn test_some_labelled() {
    let labels: Trivial = SomeNodesLabelled(vec![Some("A"), None]);
    let styles = Some(vec![Style::None, Style::Dotted]);
    let result = test_input(LabelledGraph::new(
        "test_some_labelled",
        labels,
        vec![edge(0, 1, "A-1", Style::None)],
        styles,
    ));
    assert_eq!(
        result.unwrap(),
        r#"digraph test_some_labelled {
    N0[label="A"];
    N1[label="N1"][style="dotted"];
    N0 -> N1[label="A-1"];
}
"#
    );
}

#[test]
fn single_cyclic_node() {
    let labels: Trivial = UnlabelledNodes(1);
    let r = test_input(LabelledGraph::new(
        "single_cyclic_node",
        labels,
        vec![edge(0, 0, "E", Style::None)],
        None,
    ));
    assert_eq!(
        r.unwrap(),
        r#"digraph single_cyclic_node {
    N0[label="N0"];
    N0 -> N0[label="E"];
}
"#
    );
}

#[test]
fn hasse_diagram() {
    let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]);
    let r = test_input(LabelledGraph::new(
        "hasse_diagram",
        labels,
        vec![
            edge(0, 1, "", Style::None),
            edge(0, 2, "", Style::None),
            edge(1, 3, "", Style::None),
            edge(2, 3, "", Style::None),
        ],
        None,
    ));
    assert_eq!(
        r.unwrap(),
        r#"digraph hasse_diagram {
    N0[label="{x,y}"];
    N1[label="{x}"];
    N2[label="{y}"];
    N3[label="{}"];
    N0 -> N1[label=""];
    N0 -> N2[label=""];
    N1 -> N3[label=""];
    N2 -> N3[label=""];
}
"#
    );
}

#[test]
fn left_aligned_text() {
    let labels = AllNodesLabelled(vec![
        "if test {\
       \\l    branch1\
       \\l} else {\
       \\l    branch2\
       \\l}\
       \\lafterward\
       \\l",
        "branch1",
        "branch2",
        "afterward",
    ]);

    let mut writer = Vec::new();

    let g = LabelledGraphWithEscStrs::new(
        "syntax_tree",
        labels,
        vec![
            edge(0, 1, "then", Style::None),
            edge(0, 2, "else", Style::None),
            edge(1, 3, ";", Style::None),
            edge(2, 3, ";", Style::None),
        ],
    );

    render(&g, &mut writer).unwrap();
    let mut r = String::new();
    Read::read_to_string(&mut &*writer, &mut r).unwrap();

    assert_eq!(
        r,
        r#"digraph syntax_tree {
    N0[label="if test {\l    branch1\l} else {\l    branch2\l}\lafterward\l"];
    N1[label="branch1"];
    N2[label="branch2"];
    N3[label="afterward"];
    N0 -> N1[label="then"];
    N0 -> N2[label="else"];
    N1 -> N3[label=";"];
    N2 -> N3[label=";"];
}
"#
    );
}

#[test]
fn simple_id_construction() {
    let id1 = Id::new("hello");
    match id1 {
        Ok(_) => {}
        Err(..) => panic!("'hello' is not a valid value for id anymore"),
    }
}

#[test]
fn badly_formatted_id() {
    let id2 = Id::new("Weird { struct : ure } !!!");
    match id2 {
        Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
        Err(..) => {}
    }
}