sysml_parser/
syntax_error.rs

1// This is free and unencumbered software released into the public domain.
2
3use crate::{
4    prelude::{fmt, vec, Vec},
5    Span,
6};
7
8#[cfg(feature = "std")]
9extern crate std;
10
11pub type SyntaxResult<'a, T, E = SyntaxError<'a>> = Result<T, Err<'a, E>>;
12
13pub type Err<'a, E = SyntaxError<'a>> = nom::Err<E>;
14
15#[derive(Clone, Debug, PartialEq)]
16pub enum SyntaxErrorKind {
17    Context(&'static str),
18    Char(char),
19    Combinator(nom::error::ErrorKind),
20}
21
22#[derive(Clone, Debug, Default, PartialEq)]
23pub struct SyntaxError<'a> {
24    pub errors: Vec<(SyntaxErrorKind, Span<'a>)>,
25}
26
27impl<'a> SyntaxError<'a> {
28    pub fn new() -> Self {
29        Self::default()
30    }
31}
32
33#[cfg(feature = "std")]
34impl<'a> std::error::Error for SyntaxError<'a> {}
35
36impl<'a> fmt::Display for SyntaxError<'a> {
37    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
38        fmt.write_str("parse error") // TODO
39    }
40}
41
42// #[cfg(feature = "std")]
43// impl From<std::io::Error> for ParseError<'_> {
44//     fn from(error: std::io::Error) -> Self {
45//         //nom::error::FromExternalError<Span<'a>>::from_ext error
46//         todo!()
47//     }
48// }
49
50impl<'a> Into<nom::Err<SyntaxError<'a>>> for SyntaxError<'a> {
51    fn into(self) -> nom::Err<SyntaxError<'a>> {
52        nom::Err::Failure(self)
53    }
54}
55
56impl<'a> nom::error::ContextError<Span<'a>> for SyntaxError<'a> {
57    fn add_context(input: Span<'a>, ctx: &'static str, mut other: Self) -> Self {
58        other.errors.push((SyntaxErrorKind::Context(ctx), input));
59        other
60    }
61}
62
63impl<'a, E> nom::error::FromExternalError<Span<'a>, E> for SyntaxError<'a> {
64    fn from_external_error(input: Span<'a>, kind: nom::error::ErrorKind, _e: E) -> Self {
65        use nom::error::ParseError as _;
66        Self::from_error_kind(input, kind)
67    }
68}
69
70impl<'a> nom::error::ParseError<Span<'a>> for SyntaxError<'a> {
71    fn from_error_kind(input: Span<'a>, kind: nom::error::ErrorKind) -> Self {
72        Self {
73            errors: vec![(SyntaxErrorKind::Combinator(kind), input)],
74        }
75    }
76
77    fn append(input: Span<'a>, kind: nom::error::ErrorKind, mut other: Self) -> Self {
78        other
79            .errors
80            .push((SyntaxErrorKind::Combinator(kind), input));
81        other
82    }
83
84    fn from_char(input: Span<'a>, c: char) -> Self {
85        Self {
86            errors: vec![(SyntaxErrorKind::Char(c), input)],
87        }
88    }
89}
90
91#[cfg(all(feature = "error-stack", not(feature = "std")))]
92impl error_stack::Context for SyntaxError<'static> {}