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
#![deny(missing_docs)]
extern crate pest;
#[allow(unused_imports)]
#[macro_use]
extern crate derive;
use pest::{
iterators::{Pair, Pairs},
RuleType,
};
use std::iter::Peekable;
pub use derive::*;
pub trait FromPest<'a>: Sized {
type Rule: RuleType;
const RULE: Self::Rule;
fn from_pest(pest: Pair<'a, Self::Rule>) -> Self;
}
pub trait PestDeconstruct<'i> {
type Rule: RuleType;
fn deconstruct(self) -> PestDeconstructor<'i, Self::Rule>;
}
impl<'i, R: RuleType> PestDeconstruct<'i> for Pair<'i, R> {
type Rule = R;
fn deconstruct(self) -> PestDeconstructor<'i, R> {
PestDeconstructor {
pairs: self.into_inner().peekable(),
}
}
}
#[derive(Clone, Debug)]
pub struct PestDeconstructor<'i, R: RuleType> {
pairs: Peekable<Pairs<'i, R>>,
}
impl<'i, R: RuleType> Drop for PestDeconstructor<'i, R> {
fn drop(&mut self) {
assert_eq!(
self.next_untyped(),
None,
"PestDeconstructor was not fully exhausted"
)
}
}
impl<'i, R: RuleType> PestDeconstructor<'i, R> {
pub fn next<T: FromPest<'i, Rule = R>>(&mut self) -> T {
T::from_pest(self.next_pair(T::RULE))
}
pub fn next_opt<T: FromPest<'i, Rule = R>>(&mut self) -> Option<T> {
self.next_pair_opt(T::RULE).map(T::from_pest)
}
pub fn next_many<T: FromPest<'i, Rule = R>>(&mut self) -> Vec<T> {
let mut children = vec![];
while let Some(child) = self.next_opt() {
children.push(child);
}
children
}
pub fn next_pair(&mut self, rule: R) -> Pair<'i, R> {
self.next_pair_opt(rule).unwrap_or_else(|| {
panic!(
"Expected {:?} child, got {:?}",
rule,
self.pairs.peek().map(Pair::as_rule)
)
})
}
pub fn next_pair_opt(&mut self, rule: R) -> Option<Pair<'i, R>> {
if self
.pairs
.peek()
.filter(|pair| pair.as_rule() == rule)
.is_some()
{
self.next_untyped()
} else {
None
}
}
pub fn next_pair_many(&mut self, rule: R) -> Vec<Pair<'i, R>> {
let mut children = vec![];
while let Some(child) = self.next_pair_opt(rule) {
children.push(child);
}
children
}
pub fn next_untyped(&mut self) -> Option<Pair<'i, R>> {
self.pairs.next()
}
pub fn discard(mut self) {
let mut pairs = unsafe { std::mem::uninitialized() };
std::mem::swap(&mut self.pairs, &mut pairs);
std::mem::forget(self);
}
}