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
#[doc(hidden)]
pub extern crate pest;
extern crate void;
#[doc(inline)]
pub use void::Void;
use {
pest::{
iterators::{Pair, Pairs},
RuleType,
},
std::marker::PhantomData,
};
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum ConversionError<FatalError> {
NoMatch,
Malformed(FatalError),
}
pub trait FromPest<'pest>: Sized {
type Rule: RuleType;
type FatalError;
fn from_pest(
pest: &mut Pairs<'pest, Self::Rule>,
) -> Result<Self, ConversionError<Self::FatalError>>;
}
impl<'pest, Rule: RuleType, T: FromPest<'pest, Rule = Rule>> FromPest<'pest> for PhantomData<T> {
type Rule = Rule;
type FatalError = T::FatalError;
fn from_pest(pest: &mut Pairs<'pest, Rule>) -> Result<Self, ConversionError<T::FatalError>> {
T::from_pest(pest).map(|_| PhantomData)
}
}
impl<'pest, Rule: RuleType, T: FromPest<'pest, Rule = Rule>> FromPest<'pest> for Box<T> {
type Rule = Rule;
type FatalError = T::FatalError;
fn from_pest(pest: &mut Pairs<'pest, Rule>) -> Result<Self, ConversionError<T::FatalError>> {
T::from_pest(pest).map(Box::new)
}
}
impl<'pest, Rule: RuleType, T: FromPest<'pest, Rule = Rule>> FromPest<'pest> for Option<T> {
type Rule = Rule;
type FatalError = T::FatalError;
fn from_pest(pest: &mut Pairs<'pest, Rule>) -> Result<Self, ConversionError<T::FatalError>> {
match T::from_pest(pest) {
Err(ConversionError::NoMatch) => Ok(None),
result => result.map(Some),
}
}
}
impl<'pest, Rule: RuleType, T: FromPest<'pest, Rule = Rule>> FromPest<'pest> for Vec<T> {
type Rule = Rule;
type FatalError = T::FatalError;
fn from_pest(pest: &mut Pairs<'pest, Rule>) -> Result<Self, ConversionError<T::FatalError>> {
let mut acc = vec![];
loop {
match T::from_pest(pest) {
Ok(t) => acc.push(t),
Err(ConversionError::NoMatch) => break,
Err(error @ ConversionError::Malformed(_)) => return Err(error),
}
}
Ok(acc)
}
}
impl<'pest, Rule: RuleType> FromPest<'pest> for Pair<'pest, Rule> {
type Rule = Rule;
type FatalError = Void;
fn from_pest(pest: &mut Pairs<'pest, Rule>) -> Result<Self, ConversionError<Void>> {
pest.next().ok_or(ConversionError::NoMatch)
}
}