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
use crate::not_containing;
use chumsky::prelude::*;
#[allow(clippy::type_complexity)]
pub struct Branch<'a, T, E> {
branches: Vec<(&'a str, Box<dyn Parser<char, T, Error = E> + 'a>)>
}
pub fn branch<'a, P, T>(begin: &'a str, parser: P) -> Branch<'a, T, P::Error>
where
P: Parser<char, T> + 'a
{
Branch {
branches: vec![(begin, Box::new(parser))]
}
}
impl<'a, T, E> Branch<'a, T, E>
where
E: chumsky::Error<char> + 'a
{
pub fn or_branch<P>(mut self, begin: &'a str, parser: P) -> Self
where
P: Parser<char, T, Error = E> + 'a
{
self.branches.push((begin, Box::new(parser)));
self
}
pub fn or_else<B>(self, branch: B) -> Box<dyn Parser<char, T, Error = E> + 'a>
where
B: Fn(String) -> T + 'a,
T: 'a
{
let mut parser: Box<dyn Parser<char, T, Error = E> + 'a> = Box::new(
not_containing(
self.branches
.iter()
.map(|(pattern, _)| *pattern)
.collect::<Vec<_>>()
)
.map(branch)
);
for (pattern, branch) in self.branches {
parser = Box::new(choice((parser, just(pattern).ignore_then(branch))));
}
parser
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Eq, PartialEq)]
enum Token {
Foo,
Bar,
Comment,
Verbatim(String)
}
fn test_lexer() -> impl Parser<char, Token, Error = Simple<char>> {
branch(
"{{",
just("foo").then_ignore(just("}}")).map(|_| Token::Foo)
)
.or_branch(
"{%",
just("bar").then_ignore(just("%}")).map(|_| Token::Bar)
)
.or_branch(
"/*",
just("TODO").then_ignore(just("*/")).map(|_| Token::Comment)
)
.or_else(Token::Verbatim)
.then_ignore(end())
}
#[test]
fn parse_foo() {
let token = test_lexer().parse("{{foo}}");
assert_eq!(token, Ok(Token::Foo));
}
#[test]
fn parse_bar() {
let token = test_lexer().parse("{%bar%}");
assert_eq!(token, Ok(Token::Bar));
}
#[test]
fn parse_comment() {
let token = test_lexer().parse("/*TODO*/");
assert_eq!(token, Ok(Token::Comment));
}
#[test]
fn parse_verbatim() {
let token = test_lexer().parse("just some random text");
assert_eq!(
token,
Ok(Token::Verbatim("just some random text".to_owned()))
);
}
#[test]
fn parse_foo_unclosed() {
let token = test_lexer().parse("{{foo}");
assert_matches!(token, Err(_));
}
#[test]
fn parse_bar_unclosed() {
let token = test_lexer().parse("{%foo%");
assert_matches!(token, Err(_));
}
#[test]
fn parse_comment_unclosed() {
let token = test_lexer().parse("/*TODO//");
assert_matches!(token, Err(_));
}
#[test]
fn parse_invalid() {
let token = test_lexer().parse("foo{{bar");
assert_matches!(token, Err(_));
}
}