This repository has been archived by the owner on Apr 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.rs
301 lines (273 loc) · 8.22 KB
/
utils.rs
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use nom::types::{CompleteByteSlice, CompleteStr, Input};
use std::ops::{Bound, RangeBounds};
/// Recognizes at least 1 character while a predicate holds true
pub fn while_predicate1<T, F>(input: T, predicate: F) -> nom::IResult<T, T>
where
F: Fn(char) -> bool,
T: nom::InputTakeAtPosition,
<T as nom::InputTakeAtPosition>::Item: nom::AsChar,
{
use nom::AsChar;
input.split_at_position1(
|item| !predicate(item.as_char()),
nom::ErrorKind::AlphaNumeric,
)
}
pub trait SliceBoundary<R>: nom::Slice<R> + Sized
where
R: RangeBounds<usize>,
{
/// Indicate if an `index` is the start and/or end of some boundary
///
/// For example, in an implementation for a `&str`, this might be start
/// and/or end of a UTF-8 code point sequence
/// (see [`str::is_char_boundary`](https://doc.rust-lang.org/std/primitive.str.html#method.is_char_boundary)).
fn is_slice_boundary(&self, index: usize) -> bool;
/// Safe slicing. The start and the end of the range (if bounded) must be
/// at a boundary
///
/// If they are unsafe, then the implementation will return `None`.
fn safe_slice(&self, range: R) -> Option<Self> {
if !match range.start_bound() {
Bound::Included(start) => self.is_slice_boundary(*start),
// No such Range exist
Bound::Excluded(start) => self.is_slice_boundary(start + 1),
Bound::Unbounded => true,
} {
return None;
}
if !match range.end_bound() {
Bound::Included(end) => self.is_slice_boundary(end + 1),
Bound::Excluded(end) => self.is_slice_boundary(*end),
Bound::Unbounded => true,
} {
return None;
}
Some(self.slice(range))
}
}
impl<'a, R> SliceBoundary<R> for &'a str
where
R: RangeBounds<usize>,
&'a str: nom::Slice<R>,
{
fn is_slice_boundary(&self, index: usize) -> bool {
self.is_char_boundary(index)
}
}
impl<'a, R> SliceBoundary<R> for CompleteStr<'a>
where
R: RangeBounds<usize>,
CompleteStr<'a>: nom::Slice<R>,
{
fn is_slice_boundary(&self, index: usize) -> bool {
self.is_char_boundary(index)
}
}
impl<'a, R, T> SliceBoundary<R> for &'a [T]
where
R: RangeBounds<usize>,
&'a [T]: nom::Slice<R>,
{
fn is_slice_boundary(&self, _index: usize) -> bool {
// Always true for arbitrary slices
true
}
}
impl<R, T> SliceBoundary<R> for Input<T>
where
R: RangeBounds<usize>,
Input<T>: nom::Slice<R>,
T: nom::Slice<R>,
{
fn is_slice_boundary(&self, _index: usize) -> bool {
// Always true for arbitrary slices
true
}
}
impl<'a, R> SliceBoundary<R> for CompleteByteSlice<'a>
where
R: RangeBounds<usize>,
CompleteByteSlice<'a>: nom::Slice<R>,
{
fn is_slice_boundary(&self, _index: usize) -> bool {
// Always true for arbitrary bytes
true
}
}
// From https://github.com/Geal/nom/issues/709#issuecomment-475958529
/// Take bytes until the child parser succeeds
///
/// `take_till_match!(I -> IResult<I, O>) => I -> IResult<I, (I, O)>`
///
/// ```rust
/// # use ferrous_chloride::take_till_match;
/// use nom::{alt, named, tag};
///
/// named!(test<&str, (&str, &str)>, take_till_match!(alt!(tag!("John") | tag!("Amanda"))));
///
/// assert_eq!(test("Hello, Amanda and Tim"), Ok((" and Tim", ("Hello, ", "Amanda"))));
/// ```
#[macro_export]
macro_rules! take_till_match(
(__impl $i:expr, $submac2:ident!( $($args2:tt)* )) => (
{
use nom::{Needed, need_more_err, ErrorKind};
use nom::InputTake;
use $crate::utils::SliceBoundary;
let ret;
let input = $i;
let mut index = 0;
loop {
let slice = input.safe_slice(index..);
match slice {
None => {
index += 1;
if index >= input.len() {
// XXX: this error is dramatically wrong
ret = need_more_err(input, Needed::Size(0), ErrorKind::TakeUntil::<u32>);
break;
}
else {
continue;
}
},
Some(slice) => {
match $submac2!(slice, $($args2)*) {
Ok((i, o)) => {
let (_, start) = input.take_split(index);
ret = Ok((i, (start, o)));
break;
},
Err(_e1) => {
if index >= input.len() {
// XXX: this error is dramatically wrong
ret = need_more_err(input, Needed::Size(0), ErrorKind::TakeUntil::<u32>);
break;
} else {
index += 1;
}
},
}
}
}
}
ret
}
);
($i:expr, $submac2:ident!( $($args2:tt)* )) => (
take_till_match!(__impl $i, $submac2!($($args2)*));
);
($i:expr, $g:expr) => (
take_till_match!(__impl $i, call!($g));
);
($i:expr, $submac2:ident!( $($args2:tt)* )) => (
take_till_match!(__impl $i, $submac2!($($args2)*));
);
($i:expr, $g: expr) => (
take_till_match!(__impl $i, call!($g));
);
);
#[cfg(test)]
mod test_utils {
use nom::{IResult, InputLength};
use std::borrow::Borrow;
use std::fmt::Debug;
pub(crate) trait ResultUtils<O> {
/// Unwraps the Output from `IResult`
///
/// # Panics
///
/// Panics if there is an error
fn unwrap_output(self) -> O;
}
/// Duplicated trait because there is no specialisation!
pub(crate) trait ResultUtilsString<O> {
/// Unwraps the Output from `IResult`
///
/// # Panics
///
/// Panics if there is an error
fn unwrap_output(self) -> O;
}
impl<I, O> ResultUtils<O> for IResult<I, O>
where
I: nom::AsBytes + Debug + InputLength,
{
fn unwrap_output(self) -> O {
match self {
Err(e) => {
let e = crate::Error::from_err_bytes(&e);
panic!("{:#}", e)
}
Ok((remaining, output)) => {
assert!(remaining.input_len() == 0, "Remaining: {:#?}", remaining);
output
}
}
}
}
impl<I, O> ResultUtilsString<O> for IResult<I, O>
where
I: nom::AsBytes + AsRef<str> + std::fmt::Debug + InputLength,
{
fn unwrap_output(self) -> O {
match self {
Err(e) => {
let e = crate::Error::from_err_str(&e);
panic!("{:#}", e)
}
Ok((remaining, output)) => {
assert!(
remaining.input_len() == 0,
"Remaining: {}",
remaining.as_ref()
);
output
}
}
}
}
pub(crate) fn assert_list_eq<B1, B2, T1, T2, L1, L2>(left: L1, right: L2)
where
B1: Borrow<T1>,
B2: Borrow<T2>,
T1: PartialEq<T2>,
T2: PartialEq<T1>,
L1: IntoIterator<Item = B1> + Debug,
L2: IntoIterator<Item = B2> + Debug,
{
println!(
r#"Checking `(left == right)`
left: `{:#?}`,
right: `{:#?}`"#,
left, right
);
let equal = left
.into_iter()
.zip(right)
.all(|(left, right)| left.borrow().eq(right.borrow()));
if !equal {
panic!("left != right");
}
}
}
#[cfg(test)]
pub(crate) use test_utils::*;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strings_are_sliced_safely() {
let s = "Löwe 老虎 Léopard";
assert_eq!(Some(s), s.safe_slice(..));
assert_eq!(Some("Löwe "), s.safe_slice(0..6));
assert_eq!(Some("Löwe "), s.safe_slice(..6));
assert_eq!(Some("老"), s.safe_slice(6..9));
assert_eq!(Some("老虎 Léopard"), s.safe_slice(6..));
// "老" is bytes 6 to 8
assert_eq!(None, s.safe_slice(6..8));
assert_eq!(None, s.safe_slice(7..));
assert_eq!(None, s.safe_slice(..7));
}
}