markab_parser/gen_parser/
error.rs

1use crate::{
2	gen_parser::GenParserRequirement,
3	Error,
4	Parser,
5};
6use either::{
7	Either,
8	Left,
9	Right,
10};
11use std::fmt::{
12	Display,
13	Formatter,
14	Result as FmtResult,
15};
16
17#[derive(Debug)]
18pub struct GenParserError<'a, P1, P2>
19where
20	P1: Parser<'a>,
21	P2: Parser<'a>,
22{
23	from: usize,
24	requirement: GenParserRequirement<'a, P1, P2>,
25	cause: Either<P1::Error, P2::Error>,
26}
27
28impl<'a, P1, P2> GenParserError<'a, P1, P2>
29where
30	P1: Parser<'a>,
31	P2: Parser<'a>,
32{
33	pub fn new(
34		from: usize,
35		requirement: GenParserRequirement<'a, P1, P2>,
36		cause: Either<P1::Error, P2::Error>,
37	) -> Self
38	{
39		Self {
40			from,
41			requirement,
42			cause,
43		}
44	}
45}
46
47impl<'a, P1, P2> Error for GenParserError<'a, P1, P2>
48where
49	P1: Parser<'a>,
50	P2: Parser<'a>,
51{
52	fn from(&self, f: &mut Formatter) -> FmtResult
53	{
54		write!(f, "{}", self.from)
55	}
56
57	fn requirement(&self, f: &mut Formatter) -> FmtResult
58	{
59		write!(f, "{}", self.requirement)
60	}
61
62	fn result(&self, f: &mut Formatter) -> FmtResult
63	{
64		match &self.cause
65		{
66			Left(_) => write!(f, "failed to parse {}", self.requirement.first()),
67			Right(_) => write!(f, "failed to parse {}", self.requirement.second().unwrap()),
68		}
69	}
70
71	fn causes(&self, f: &mut Formatter, depth: usize) -> FmtResult
72	{
73		match &self.cause
74		{
75			Left(err) => err.print(f, depth),
76			Right(err) => err.print(f, depth),
77		}
78	}
79}
80
81impl<'a, P1, P2> Display for GenParserError<'a, P1, P2>
82where
83	P1: Parser<'a>,
84	P2: Parser<'a>,
85{
86	fn fmt(&self, f: &mut Formatter) -> FmtResult
87	{
88		self.print(f, 0)
89	}
90}