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
use crate::{
	gen_parser::GenParser,
	map_parser::MapParser,
	order_parser::OrderParser,
	repetition_parser::RepetitionParser,
	sequence_parser::SequenceParser,
	stringify_parser::StringifyParser,
	Error,
};
use std::{
	fmt::{
		Debug,
		Display,
	},
	usize::MAX,
};

pub trait Parser<'a>: Debug
{
	type Error: Error;
	type Output;
	type Requirement: Debug + Display;
	type RequirementContext;

	fn parse(&self, src: &'a str, pos: &mut usize) -> Result<Self::Output, Self::Error>;

	fn skip(&self, src: &'a str, pos: &mut usize) -> Result<(), Self::Error>
	{
		self.parse(src, pos).map(|_| ())
	}

	fn requirement(&self, context: Option<&Self::RequirementContext>) -> Self::Requirement;

	fn and_then<P>(self, next: P) -> SequenceParser<'a, Self, P>
	where
		Self: Sized,
		P: Parser<'a>,
	{
		SequenceParser::new(self, next)
	}

	fn or<P>(self, next: P) -> OrderParser<'a, Self, P>
	where
		Self: Sized,
		P: Parser<'a>,
	{
		OrderParser::new(self, next)
	}

	fn map<R>(self, mapper: &'a Fn(Self::Output) -> R) -> MapParser<'a, Self, R>
	where
		Self: Sized,
	{
		MapParser::new(self, mapper)
	}

	fn and_gen<P>(self, generator: &'a Fn(&Self::Output) -> P) -> GenParser<'a, Self, P>
	where
		Self: Sized,
		P: Parser<'a>,
	{
		GenParser::new(self, generator)
	}

	fn repeat(self, min: usize, max: usize) -> RepetitionParser<'a, Self>
	where
		Self: Sized,
	{
		RepetitionParser::new(self, min, max)
	}

	fn zero_or_more(self) -> RepetitionParser<'a, Self>
	where
		Self: Sized,
	{
		RepetitionParser::new(self, 0, MAX)
	}

	fn one_or_more(self) -> RepetitionParser<'a, Self>
	where
		Self: Sized,
	{
		RepetitionParser::new(self, 1, MAX)
	}

	fn stringify(self) -> StringifyParser<'a, Self>
	where
		Self: Sized,
	{
		StringifyParser::new(self)
	}
}