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
|
use chumsky::prelude::*;
use crate::ast::Val;
pub fn parser<'a>() -> impl Parser<char, Vec<Val>, Error = Simple<char>> {
recursive(|val| {
let string = just('"')
.ignore_then(none_of('"').repeated())
.then_ignore(just('"'))
.collect::<String>()
.map(Val::String)
.padded();
let atom = filter(|c: &char| c.is_alphanumeric())
.map(Some)
.chain::<char, _, _>(filter(|c: &char| c.is_alphanumeric()).repeated())
.collect::<String>()
.map(Val::Atom)
.padded();
let number = just('-')
.or_not()
.chain::<char, _, _>(text::int(10))
.collect::<String>()
.from_str()
.unwrapped()
.map(Val::I64)
.labelled("number");
choice((
string, //
number,
atom,
val.delimited_by(just('('), just(')')).map(Val::List),
))
.repeated()
})
.then_ignore(end())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_atom() {
assert_eq!(
Ok(vec!(Val::Atom("foo".to_string()))),
parser().parse("foo")
);
}
#[test]
fn parse_string() {
assert_eq!(
Ok(vec!(Val::String("foo".to_string()))),
parser().parse("\"foo\"")
);
}
#[test]
fn parse_i64() {
assert_eq!(Ok(vec!(Val::I64(123))), parser().parse("123"));
assert_eq!(Ok(vec!(Val::I64(-643))), parser().parse("-643"));
}
#[test]
fn parse_list() {
assert_eq!(
Ok(vec!(Val::List(vec!(
Val::Atom("a".to_string()),
Val::Atom("b".to_string())
)))),
parser().parse("(a b)")
);
}
}
|