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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use super::{
	comment::{mightbespace, shouldbespace},
	error::ParseError,
	IResult,
};
use nom::{
	branch::alt,
	bytes::complete::{take_while, take_while_m_n},
	character::complete::char,
	combinator::map_res,
	multi::many1,
	Err, InputLength, Parser,
};
use std::ops::RangeBounds;

pub fn colons(i: &str) -> IResult<&str, ()> {
	let (i, _) = mightbespace(i)?;
	let (i, _) = many1(char(';'))(i)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, ()))
}

pub fn commas(i: &str) -> IResult<&str, ()> {
	let (i, _) = mightbespace(i)?;
	let (i, _) = char(',')(i)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, ()))
}

pub fn verbar(i: &str) -> IResult<&str, ()> {
	let (i, _) = mightbespace(i)?;
	let (i, _) = char('|')(i)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, ()))
}

pub fn commasorspace(i: &str) -> IResult<&str, ()> {
	alt((commas, shouldbespace))(i)
}

pub fn openparentheses(s: &str) -> IResult<&str, &str> {
	let (i, _) = char('(')(s)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, s))
}

pub fn closeparentheses(i: &str) -> IResult<&str, &str> {
	let (s, _) = mightbespace(i)?;
	let (i, _) = char(')')(s)?;
	Ok((i, s))
}

pub fn openbraces(s: &str) -> IResult<&str, &str> {
	let (i, _) = char('{')(s)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, s))
}

pub fn closebraces(i: &str) -> IResult<&str, &str> {
	let (s, _) = mightbespace(i)?;
	let (i, _) = char('}')(s)?;
	Ok((i, s))
}

pub fn openbracket(s: &str) -> IResult<&str, &str> {
	let (i, _) = char('[')(s)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, s))
}

pub fn closebracket(i: &str) -> IResult<&str, &str> {
	let (s, _) = mightbespace(i)?;
	let (i, _) = char(']')(s)?;
	Ok((i, s))
}

pub fn openchevron(s: &str) -> IResult<&str, &str> {
	let (i, _) = char('<')(s)?;
	let (i, _) = mightbespace(i)?;
	Ok((i, s))
}

pub fn closechevron(i: &str) -> IResult<&str, &str> {
	let (s, _) = mightbespace(i)?;
	let (i, _) = char('>')(s)?;
	Ok((i, s))
}

#[inline]
pub fn is_hex(chr: char) -> bool {
	chr.is_ascii_hexdigit()
}

#[inline]
pub fn is_digit(chr: char) -> bool {
	chr.is_ascii_digit()
}

#[inline]
pub fn val_char(chr: char) -> bool {
	chr.is_ascii_alphanumeric() || chr == '_'
}

pub fn take_u64(i: &str) -> IResult<&str, u64> {
	map_res(take_while(is_digit), |s: &str| s.parse::<u64>())(i)
}

pub fn take_u32_len(i: &str) -> IResult<&str, (u32, usize)> {
	map_res(take_while(is_digit), |s: &str| s.parse::<u32>().map(|x| (x, s.len())))(i)
}

pub fn take_digits(i: &str, n: usize) -> IResult<&str, u32> {
	map_res(take_while_m_n(n, n, is_digit), |s: &str| s.parse::<u32>())(i)
}

pub fn take_digits_range(i: &str, n: usize, range: impl RangeBounds<u32>) -> IResult<&str, u32> {
	let (i, v) = take_while_m_n(n, n, is_digit)(i)?;
	match v.parse::<u32>() {
		Ok(v) => {
			if range.contains(&v) {
				Ok((i, v))
			} else {
				Result::Err(Err::Error(ParseError::RangeError {
					tried: i,
					lower: range.start_bound().cloned(),
					upper: range.end_bound().cloned(),
				}))
			}
		}
		Err(error) => Result::Err(Err::Error(ParseError::ParseInt {
			tried: v,
			error,
		})),
	}
}

/// Parses a parser delimited by two other parsers.
///
/// This parser fails (not errors) if the second delimiting parser returns an error.
pub fn expect_delimited<I, D, V, T, O, O1>(
	mut prefix: D,
	mut value: V,
	mut terminator: T,
) -> impl FnMut(I) -> IResult<I, O, ParseError<I>>
where
	I: Clone + InputLength,
	V: Parser<I, O, ParseError<I>>,
	D: Parser<I, I, ParseError<I>>,
	T: Parser<I, O1, ParseError<I>>,
{
	move |i| {
		let (i, s) = prefix.parse(i)?;
		let (i, res) = value.parse(i)?;
		match terminator.parse(i) {
			Ok((i, _)) => Result::Ok((i, res)),
			Result::Err(Err::Failure(e)) | Result::Err(Err::Error(e)) => {
				Result::Err(Err::Failure(ParseError::MissingDelimiter {
					opened: s,
					tried: e.tried(),
				}))
			}
			Result::Err(Err::Incomplete(e)) => Result::Err(Err::Incomplete(e)),
		}
	}
}

pub fn expect_terminator<P, I, O>(
	open_span: I,
	mut terminator: P,
) -> impl FnMut(I) -> IResult<I, O, ParseError<I>>
where
	I: Clone,
	P: Parser<I, O, ParseError<I>>,
{
	move |i| match terminator.parse(i) {
		Ok((i, x)) => Ok((i, x)),
		Result::Err(Err::Failure(e)) | Result::Err(Err::Error(e)) => {
			Result::Err(Err::Failure(ParseError::MissingDelimiter {
				opened: open_span.clone(),
				tried: e.tried(),
			}))
		}
		Result::Err(Err::Incomplete(e)) => Result::Err(Err::Incomplete(e)),
	}
}

/// Parses a delimited list with an option trailing separator in the form of:
///
///```text
/// PREFIX $(PARSER)SEPARATOR* $(SEPARATOR)? TERMINATOR
///```
///
/// Which parsers productions like
/// (a,b,c,) or [a,b]
///
/// First parses the prefix and returns it's error if there is one.
/// The tries to parse the terminator. If there is one the parser completes else it tries to parse
/// the value, else it returns the parsed values.
/// Then it tries to parse the separator, if there is one it start again trying to parse the
/// terminator followed by a value if there is no terminator. Else it tries to parse the terminator
/// and if there is none it returns a failure. Otherwise completes with an vec of the parsed
/// values.
///
pub fn delimited_list0<I, D, S, V, T, O, O1, O2>(
	mut prefix: D,
	mut separator: S,
	mut value: V,
	mut terminator: T,
) -> impl FnMut(I) -> IResult<I, Vec<O>, ParseError<I>>
where
	I: Clone + InputLength,
	V: Parser<I, O, ParseError<I>>,
	D: Parser<I, I, ParseError<I>>,
	S: Parser<I, O1, ParseError<I>>,
	T: Parser<I, O2, ParseError<I>>,
{
	move |i| {
		let (i, s) = prefix.parse(i)?;
		let mut res = Vec::new();
		let mut input = i;
		loop {
			match terminator.parse(input.clone()) {
				Err(Err::Error(_)) => {}
				Err(e) => return Err(e),
				Ok((i, _)) => {
					input = i;
					break;
				}
			}
			let (i, value) = value.parse(input)?;
			res.push(value);
			match separator.parse(i.clone()) {
				Ok((i, _)) => {
					input = i;
				}
				Err(Err::Error(_)) => match terminator.parse(i.clone()) {
					Ok((i, _)) => {
						input = i;
						break;
					}
					Result::Err(Err::Error(_)) => {
						return Err(Err::Failure(ParseError::MissingDelimiter {
							opened: s,
							tried: i,
						}))
					}
					Result::Err(e) => return Err(e),
				},
				Err(e) => return Err(e),
			}
		}
		Ok((input, res))
	}
}

/// Parses a delimited list with an option trailing separator in the form of:
///
///```text
/// PREFIX $(PARSER)SEPARATOR+ $(SEPARATOR)? TERMINATOR
///```
///
/// Which parsers productions like
/// (a,b,c,) or [a,b] but not empty lists
///
/// First parses the prefix and returns it's error if there is one.
/// The tries to parse the terminator. If there is one the parser completes else it tries to parse
/// the value, else it returns the parsed values.
/// Then it tries to parse the separator, if there is one it start again trying to parse the
/// terminator followed by a value if there is no terminator. Else it tries to parse the terminator
/// and if there is none it returns a failure. Otherwise completes with an vec of the parsed
/// values.
///
pub fn delimited_list1<I, D, S, V, T, O, O1, O2>(
	mut prefix: D,
	mut separator: S,
	mut value: V,
	mut terminator: T,
) -> impl FnMut(I) -> IResult<I, Vec<O>, ParseError<I>>
where
	I: Clone + InputLength,
	V: Parser<I, O, ParseError<I>>,
	D: Parser<I, I, ParseError<I>>,
	S: Parser<I, O1, ParseError<I>>,
	T: Parser<I, O2, ParseError<I>>,
{
	move |i| {
		let (i, s) = prefix.parse(i)?;
		let mut input = i;
		let (i, v) = value.parse(input)?;
		let mut res = vec![v];

		match separator.parse(i.clone()) {
			Ok((i, _)) => {
				input = i;
			}
			Err(Err::Error(_)) => match terminator.parse(i.clone()) {
				Ok((i, _)) => return Ok((i, res)),
				Result::Err(Err::Error(_)) => {
					return Err(Err::Failure(ParseError::MissingDelimiter {
						opened: s,
						tried: i,
					}))
				}
				Result::Err(e) => return Err(e),
			},
			Err(e) => return Err(e),
		}

		loop {
			match terminator.parse(input.clone()) {
				Err(Err::Error(_)) => {}
				Err(e) => return Err(e),
				Ok((i, _)) => {
					input = i;
					break;
				}
			}
			let (i, v) = value.parse(input)?;
			res.push(v);
			match separator.parse(i.clone()) {
				Ok((i, _)) => {
					input = i;
				}
				Err(Err::Error(_)) => match terminator.parse(i.clone()) {
					Ok((i, _)) => {
						input = i;
						break;
					}
					Result::Err(Err::Error(_)) => {
						return Err(Err::Failure(ParseError::MissingDelimiter {
							opened: s,
							tried: i,
						}))
					}
					Result::Err(e) => return Err(e),
				},
				Err(e) => return Err(e),
			}
		}
		Ok((input, res))
	}
}