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
use nom::{
branch::alt,
combinator::{map, opt},
multi::many0,
sequence::tuple,
IResult,
};
use super::{blank, graph::Graph, node::Node, Parser};
#[derive(Debug, Clone)]
pub struct Document {
pub graphs: Vec<Graph>,
pub nodes: Vec<Node>,
}
impl Parser for Document {
fn parse(input: &str) -> IResult<&str, Self> {
enum NodeOrGraph {
Node(Node),
Graph(Graph),
}
map(
many0(map(
tuple((
opt(blank),
alt((
map(Node::parse, NodeOrGraph::Node),
map(Graph::parse, NodeOrGraph::Graph),
)),
opt(blank),
)),
|(_, nog, _)| nog,
)),
|nogs| {
let mut graphs = Vec::new();
let mut nodes = Vec::new();
for nog in nogs.into_iter() {
match nog {
NodeOrGraph::Node(node) => nodes.push(node),
NodeOrGraph::Graph(graph) => graphs.push(graph),
}
}
Document { graphs, nodes }
},
)(input)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_document() {
let input = r#"
graph Foo(Bar)
node Bar -> (Baz, Qux) {
#[default = "B::new"]
b: B,
}
node Baz -> Out {
#[default = "C::new"]
c: C,
}
node Qux -> Out {
#[default = "D::new"]
d: D,
}
node Out {
}
"#;
match super::Document::parse(input) {
Ok((remain, doc)) => {
assert_eq!(remain, "");
assert_eq!(doc.graphs.len(), 1);
assert_eq!(doc.nodes.len(), 4);
}
Err(e) => panic!("Error: {e:?}"),
}
}
}