yapcol 0.3.0

Yet Another Parser Combinator Library - YAPCoL
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Core parser trait and string parser alias.
//!
//! This module defines the [`Parser`] trait, which is the central abstraction of the `yapcol`
//! crate. A [`Parser`] is any function (or closure) that takes a mutable reference to an
//! [`Input`] and returns a `Result` containing either a successfully parsed value or an
//! [`Error`].
//!
//! The trait is automatically implemented for any function with the signature
//! `Fn(&mut Input<IT>) -> Result<Output, Error>`, so you can use plain functions or closures as
//! parsers without any boilerplate.
//!
//! # Combinators
//!
//! The [`Parser`] trait exposes some built-in utility methods that let you transform and chain
//! parsers:
//!
//! - [`map`](Parser::map): transforms the output of a parser with a function.
//! - [`and_then`](Parser::and_then): chains two parsers, where the second depends on the output
//!   of the first.
//! - [`and`](Parser::and): sequences two parsers, discarding the output of the first.
//!
//! # String Parsing
//!
//! For the common case of parsing character streams, this module also provides the [`StringParser`]
//! convenience trait, which is a specialization of [`Parser`] for char-based input. It is
//! automatically implemented for any function `Fn(&mut StringInput) -> Result<Output, Error>`.

use crate::Mismatch;
use crate::combinators::*;
use crate::error::{Error, MismatchElement};
use crate::input::{CharToken, Input, InputToken, StringInput};

/// The core trait of the `yapcol` crate, representing a parser.
///
/// A `Parser` is a function (or any type that implements `Fn`) that takes a mutable reference
/// to an [`Input`] and returns a `Result` containing either the successfully parsed output
/// of type `O` or an [`Error`].
///
/// This trait is automatically implemented for any function with the signature
/// `Fn(&mut Input<I>) -> Result<Output, Error>`.
///
/// # Type Parameters
///
/// - `IT`: The parser's input token, which implements the [`InputToken`] trait.
/// - `O`: The type of the value produced by the parser on success.
///
/// # Examples
///
/// You can define a custom parser as a function:
///
/// ```
/// use std::str::Chars;
/// use yapcol::{Error, Input, StringInput, is};
///
/// fn my_uppercase_parser(input: &mut StringInput) -> Result<char, Error> {
/// 	// You can use existing parsers inside your custom parser
/// 	is('A')(input)
/// }
///
/// let mut input = Input::new_from_chars("Abc".chars(), None);
/// assert_eq!(my_uppercase_parser(&mut input), Ok('A'));
/// ```
///
/// Most of the time, you will use the built-in combinators which return `impl Parser`:
///
/// ```
/// use yapcol::{Input, is};
///
/// let mut input = Input::new_from_chars("Abc".chars(), None);
/// let mut parser = is('A');
/// assert_eq!(parser(&mut input), Ok('A'));
/// ```
pub trait Parser<IT, O>: Fn(&mut Input<IT>) -> Result<O, Error>
where
	IT: InputToken,
{
	/// Overrides the expectation in the potential error returned by the current parser in the case
	/// of failure.
	///
	/// When a parser fails, the error may contain information about what was expected. This method
	/// replaces that expectation with the provided value, which is useful for producing clearer
	/// error messages.
	///
	/// # Parameters
	/// - `self`: The current parser.
	/// - `expectation`: The value to use as the new expectation in any error produced by the
	///   current parser.
	///
	/// # Returns
	/// A new parser that behaves identically to the current one on success, but replaces the
	/// expectation in any error with `expectation`.
	///
	/// # Examples
	/// ```rust
	/// use yapcol::{Input, Parser, is};
	///
	/// let parser = is('A').with_expectation("uppercase A");
	///
	/// let mut input = Input::new_from_chars("B".chars(), None);
	/// let error = parser(&mut input).unwrap_err();
	/// assert!(error.to_string().contains("uppercase A"));
	/// ```
	///
	/// # Errors
	/// If the current parser fails, the error is returned with its expectation replaced by
	/// `expectation`.
	fn with_expectation<E>(self, expectation: E) -> impl Parser<IT, O>
	where
		E: MismatchElement + Clone + 'static,
		Self: Sized,
	{
		move |input| match self(input) {
			Ok(result) => Ok(result),
			Err(Error::EndOfInput(Some(_))) => {
				// Replace the expectation.
				Err(Error::EndOfInput(Some(Box::new(expectation.clone()))))
			}
			Err(Error::EndOfInput(None)) => {
				Err(Error::EndOfInput(Some(Box::new(expectation.clone()))))
			}
			Err(Error::UnexpectedToken(s, p, Some(mut mismatch))) => {
				mismatch.replace_expectation(expectation.clone());
				Err(Error::UnexpectedToken(s, p, Some(mismatch)))
			}
			Err(Error::UnexpectedToken(s, p, None)) => {
				let mismatch = Mismatch::without_found(expectation.clone());
				Err(Error::UnexpectedToken(s, p, Some(mismatch)))
			}
			Err(error) => Err(error),
		}
	}

	/// Transforms the output of the current parser using the provided function.
	///
	/// # Parameters
	/// - `self`: The current parser.
	/// - `f`: A closure or function that maps the previous output of the parser to a new output
	///   type.
	///
	/// # Returns
	/// A new parser that applies the mapping function `f` to the output of the current parser.
	///
	/// # Examples
	/// ```rust
	/// use yapcol::{Input, Parser, any, satisfy};
	///
	/// let is_digit = |c: &char| if c.is_ascii_digit() { Some(*c) } else { None };
	/// let parser = satisfy(is_digit).map(|c| c.to_digit(10));
	///
	/// let mut input = Input::new_from_chars("1".chars(), None);
	/// let result = parser(&mut input);
	/// assert_eq!(result, Ok(Some(1)));
	/// ```
	///
	/// # Errors
	/// If the current parser fails, the error is returned as is without invoking the mapping
	/// function `f`.
	fn map<F, MO>(self, f: F) -> impl Parser<IT, MO>
	where
		F: Fn(O) -> MO,
		Self: Sized,
	{
		move |input| match self(input) {
			Ok(value) => Ok(f(value)),
			Err(e) => Err(e),
		}
	}

	/// Applies a function to the output of the current parser to produce a new parser, then runs
	/// that new parser on the same input.
	///
	/// This is useful for chaining parsers where the next parser depends on the result of the
	/// previous one.
	///
	/// # Parameters
	/// - `self`: The current parser.
	/// - `f`: A closure or function that takes the output of the current parser and returns a new
	///   parser.
	///
	/// # Returns
	/// A new parser that first runs the current parser, then passes its output to `f` to obtain
	/// a second parser, and finally runs that second parser on the same input.
	///
	/// # Examples
	/// ```rust
	/// use yapcol::{Input, Parser, is};
	///
	/// // Parse 'a' twice.
	/// let twice_parser = is('a').and_then(is);
	/// let mut input = Input::new_from_chars("aa".chars(), None);
	/// assert_eq!(twice_parser(&mut input), Ok('a'));
	///
	/// let mut input = Input::new_from_chars("ac".chars(), None);
	/// assert!(twice_parser(&mut input).is_err());
	/// ```
	///
	/// # Errors
	/// If the current parser fails, the error is returned as is without invoking `f`. If the
	/// parser returned by `f` fails, its error is returned.
	fn and_then<F, P, NO>(self, f: F) -> impl Parser<IT, NO>
	where
		F: Fn(O) -> P,
		P: Parser<IT, NO>,
		Self: Sized,
	{
		move |input| match self(input) {
			Ok(value) => f(value)(input),
			Err(e) => Err(e),
		}
	}

	/// Runs the current parser, discards its output, then runs `other` on the same input and
	/// returns its result.
	///
	/// This is useful when you want to assert that a certain token or pattern is present without
	/// caring about its value and then continue parsing with a second parser.
	///
	/// # Parameters
	/// - `self`: The current parser whose output is discarded on success.
	/// - `other`: The parser to run after `self` succeeds.
	///
	/// # Returns
	/// A new parser that first runs `self`, discards its output, then runs `other` on the same
	/// input and returns its result.
	///
	/// # Examples
	/// ```rust
	/// use yapcol::{Input, Parser, any, is};
	///
	/// // Skip 'a', then parse any character.
	/// let parser = is('a').and(any());
	/// let mut input = Input::new_from_chars("ab".chars(), None);
	/// assert_eq!(parser(&mut input), Ok('b'));
	///
	/// // Fails if the first parser fails.
	/// let parser = is('a').and(any());
	/// let mut input = Input::new_from_chars("xb".chars(), None);
	/// assert!(parser(&mut input).is_err());
	/// ```
	///
	/// # Errors
	/// If `self` fails, its error is returned and `other` is never run.
	fn and<P, NO>(self, other: P) -> impl Parser<IT, NO>
	where
		P: Parser<IT, NO>,
		Self: Sized,
	{
		move |input| match self(input) {
			Ok(_) => other(input),
			Err(e) => Err(e),
		}
	}

	/// A shortcut for the [`end_of_input`] combinator applied after this parser.
	///
	/// Runs this parser and then asserts that the entire input has been consumed. Fails if any
	/// tokens remain in the input after this parser succeeds.
	///
	/// # Examples
	///
	/// ```
	/// use yapcol::{Error, Input, Parser, any};
	///
	/// let mut input = Input::new_from_chars("a".chars(), None);
	/// assert!(any().exhaustive()(&mut input).is_ok());
	///
	/// let mut input = Input::new_from_chars("ab".chars(), None);
	/// assert!(any().exhaustive()(&mut input).is_err()); // 'b' was not consumed.
	/// ```
	fn exhaustive(self) -> impl Parser<IT, O>
	where
		Self: Sized,
	{
		move |input| {
			let output = self(input)?;
			end_of_input()(input)?;
			Ok(output)
		}
	}

	/// A shortcut for the [`attempt`] combinator.
	fn attempt(self) -> impl Parser<IT, O>
	where
		Self: Sized,
	{
		move |input| attempt(&self)(input)
	}

	/// A shortcut for the [`maybe`] combinator.
	fn maybe(self) -> impl Parser<IT, Option<O>>
	where
		Self: Sized,
	{
		move |input| maybe(&self)(input)
	}

	/// A shortcut for the [`many0`] combinator.
	fn many0(self) -> impl Parser<IT, Vec<O>>
	where
		Self: Sized,
	{
		move |input| many0(&self)(input)
	}

	/// A shortcut for the [`many1`] combinator.
	fn many1(self) -> impl Parser<IT, Vec<O>>
	where
		Self: Sized,
	{
		move |input| many1(&self)(input)
	}

	/// A shortcut for the [`between`] combinator where the callee parser is the one in between.
	fn between<PO, PC, OO, OC>(self, open: &PO, close: &PC) -> impl Parser<IT, O>
	where
		PO: Parser<IT, OO>,
		PC: Parser<IT, OC>,
		Self: Sized,
	{
		move |input| between(open, &self, close)(input)
	}

	/// A shortcut for the [`count`] combinator.
	fn count(self, c: usize) -> impl Parser<IT, Vec<O>>
	where
		Self: Sized,
	{
		move |input| count(&self, c)(input)
	}

	// A shortcut for the [`many0_up_to`] combinator
	fn many0_up_to(self, max_count: usize) -> impl Parser<IT, Vec<O>>
	where
		Self: Sized,
	{
		move |input| many0_up_to(&self, max_count)(input)
	}

	// A shortcut for the [`many1_up_to`] combinator
	fn many1_up_to(self, max_count: usize) -> impl Parser<IT, Vec<O>>
	where
		Self: Sized,
	{
		move |input| many1_up_to(&self, max_count)(input)
	}
}

impl<IT, O, X> Parser<IT, O> for X
where
	X: Fn(&mut Input<IT>) -> Result<O, Error>,
	IT: InputToken,
{
}

/// A convenience alias for [`Parser`] specialized to character-stream input.
///
/// `StringParser<O>` is equivalent to `Parser<CharToken, O>` and is automatically implemented
/// for any function `Fn(&mut StringInput) -> Result<Output, Error>`. It exists purely to reduce
/// type-annotation noise when working with string-based parsers.
pub trait StringParser<O>: Parser<CharToken, O> {}

impl<O, X> StringParser<O> for X where X: Fn(&mut StringInput) -> Result<O, Error> {}

#[cfg(test)]
mod tests {
	mod map {
		use crate::input::Position;
		use crate::*;

		#[test]
		fn empty() {
			let parser = is('2').map(|c: char| c.to_digit(10));
			let mut input = Input::new_from_chars("".chars(), None);
			assert_eq!(
				parser(&mut input),
				Err(Error::EndOfInput(Some(Box::new('2'))))
			);
		}

		#[test]
		fn success_simple() {
			let parser = is('2').map(|c: char| c.to_digit(10));
			let mut input = Input::new_from_chars("2".chars(), None);
			assert_eq!(parser(&mut input), Ok(Some(2)));
			assert!(end_of_input()(&mut input).is_ok()); // Ensure that the input was consumed.
		}

		#[test]
		fn success_chained() {
			let parser = is('2')
				.map(|c: char| c.to_digit(10))
				.map(|o| o.unwrap())
				.map(|x| x * 3);
			let mut input = Input::new_from_chars("2".chars(), None);
			assert_eq!(parser(&mut input), Ok(6));
			assert!(end_of_input()(&mut input).is_ok()); // Ensure that the input was consumed.
		}

		#[test]
		fn fail_simple() {
			let parser = is('2').map(|c: char| c.to_digit(10));
			let mut input = Input::new_from_chars("3".chars(), None);
			let mismatch = Mismatch::new('2', '3');
			assert_eq!(
				parser(&mut input),
				Err(Error::UnexpectedToken(
					None,
					Position::new(1, 1),
					Some(mismatch)
				))
			);
			assert!(end_of_input()(&mut input).is_err()); // Ensure that the input was NOT consumed.
		}

		#[test]
		fn fail_chained() {
			let parser = is('5')
				.map(|c: char| c.to_digit(10))
				.map(|o| o.unwrap())
				.map(|x| x * 7);
			let mut input = Input::new_from_chars("3".chars(), None);
			let mismatch = Mismatch::new('5', '3');
			assert_eq!(
				parser(&mut input),
				Err(Error::UnexpectedToken(
					None,
					Position::new(1, 1),
					Some(mismatch)
				))
			);
			assert!(end_of_input()(&mut input).is_err()); // Ensure that the input was NOT consumed.
		}
	}

	mod and_then {
		use crate::input::Position;
		use crate::*;

		#[test]
		fn empty() {
			let double_parser = is('2').and_then(is);
			let mut input = Input::new_from_chars("".chars(), None);
			assert_eq!(
				double_parser(&mut input),
				Err(Error::EndOfInput(Some(Box::new('2'))))
			);
		}

		#[test]
		fn success_simple() {
			let double_parser = is('2').and_then(is);
			let mut input = Input::new_from_chars("22".chars(), None);
			assert_eq!(double_parser(&mut input), Ok('2'));
			assert!(end_of_input()(&mut input).is_ok()); // Ensure that the input was consumed.
		}

		#[test]
		fn success_chained() {
			let triple_parser = is('2').and_then(is).and_then(is);
			let mut input = Input::new_from_chars("222".chars(), None);
			assert_eq!(triple_parser(&mut input), Ok('2'));
			assert!(end_of_input()(&mut input).is_ok()); // Ensure that the input was consumed.
		}

		#[test]
		fn fail_simple() {
			let double_parser = is('2').and_then(is);
			let mut input = Input::new_from_chars("23".chars(), None);
			let mismatch = Mismatch::new('2', '3');
			assert_eq!(
				double_parser(&mut input),
				Err(Error::UnexpectedToken(
					None,
					Position::new(1, 2),
					Some(mismatch)
				))
			);
			assert!(end_of_input()(&mut input).is_err()); // Ensure that the input was NOT consumed.
		}

		#[test]
		fn fail_chained() {
			let triple_parser = is('2').and_then(is).and_then(is);
			let mut input = Input::new_from_chars("223".chars(), None);
			let mismatch = Mismatch::new('2', '3');
			assert_eq!(
				triple_parser(&mut input),
				Err(Error::UnexpectedToken(
					None,
					Position::new(1, 3),
					Some(mismatch)
				))
			);
			assert!(end_of_input()(&mut input).is_err()); // Ensure that the input was NOT consumed.
		}
	}

	mod and {
		use crate::input::Position;
		use crate::*;

		#[test]
		fn empty() {
			let double_parser = is('2').and(is('3'));
			let mut input = Input::new_from_chars("".chars(), None);
			assert_eq!(
				double_parser(&mut input),
				Err(Error::EndOfInput(Some(Box::new('2'))))
			);
		}

		#[test]
		fn success_simple() {
			let double_parser = is('2').and(is('3'));
			let mut input = Input::new_from_chars("23".chars(), None);
			assert_eq!(double_parser(&mut input), Ok('3'));
			assert!(end_of_input()(&mut input).is_ok()); // Ensure that the input was consumed.
		}

		#[test]
		fn success_chained() {
			let triple_parser = is('2').and(is('3')).and(is('4'));
			let mut input = Input::new_from_chars("234".chars(), None);
			assert_eq!(triple_parser(&mut input), Ok('4'));
			assert!(end_of_input()(&mut input).is_ok()); // Ensure that the input was consumed.
		}

		#[test]
		fn fail_simple() {
			let double_parser = is('2').and(is('3'));
			let mut input = Input::new_from_chars("22".chars(), None);
			let mismatch = Mismatch::new('3', '2');
			assert_eq!(
				double_parser(&mut input),
				Err(Error::UnexpectedToken(
					None,
					Position::new(1, 2),
					Some(mismatch)
				))
			);
			assert!(end_of_input()(&mut input).is_err()); // Ensure that the input was NOT consumed.
		}

		#[test]
		fn fail_chained() {
			let triple_parser = is('2').and(is('3')).and(is('4'));
			let mut input = Input::new_from_chars("233".chars(), None);
			let mismatch = Mismatch::new('4', '3');
			assert_eq!(
				triple_parser(&mut input),
				Err(Error::UnexpectedToken(
					None,
					Position::new(1, 3),
					Some(mismatch)
				))
			);
			assert!(end_of_input()(&mut input).is_err()); // Ensure that the input was NOT consumed.
		}
	}

	mod exhaustive {
		use crate::input::Position;
		use crate::*;

		#[test]
		fn empty() {
			let parser = is('a').exhaustive();
			let mut input = Input::new_from_chars("".chars(), None);
			let expected = Box::new("a");
			assert_eq!(parser(&mut input), Err(Error::EndOfInput(Some(expected))));
		}

		#[test]
		fn leftover() {
			let parser = is('a').exhaustive();
			let mut input = Input::new_from_chars("aa".chars(), None);
			let position = Position::new(1, 2);
			let mismatch = Mismatch::new("end of input", "a");
			assert_eq!(
				parser(&mut input),
				Err(Error::UnexpectedToken(None, position, Some(mismatch)))
			);
		}

		#[test]
		fn success_simple() {
			let parser = is('a').exhaustive();
			let mut input = Input::new_from_chars("a".chars(), None);
			assert_eq!(parser(&mut input), Ok('a'));
		}

		#[test]
		fn success_separated_by_1() {
			let is_digit = |c: &char| c.to_digit(10);
			let parse_number = satisfy(is_digit);
			let parse_comma = is(',');
			let parser = separated_by1(&parse_number, &parse_comma);
			let parser = parser.exhaustive();
			let mut input = Input::new_from_chars("1,1,1,1,1".chars(), None);
			assert_eq!(parser(&mut input), Ok(vec![1, 1, 1, 1, 1]));
		}

		#[test]
		fn fail_separated_by_1() {
			let is_digit = |c: &char| c.to_digit(10);
			let parse_number = satisfy(is_digit);
			let parse_comma = is(',');
			let parser = separated_by1(&parse_number, &parse_comma);
			let parser = parser.exhaustive();
			let mut input = Input::new_from_chars("1,1,1,1,1#".chars(), None);
			let position = Position::new(1, 10);
			let mismatch = Mismatch::new("end of input", '#');
			assert_eq!(
				parser(&mut input),
				Err(Error::UnexpectedToken(None, position, Some(mismatch)))
			);
		}
	}
}