Skip to main content

gp_runtime/
gp_type.rs

1use std::{fmt, ops::Range};
2
3use annotate_snippets::{Level, Snippet, AnnotationKind, Renderer};
4
5pub trait FromGp: Sized {
6    fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>>;
7    fn name() -> &'static str;
8}
9
10pub trait IntoGp {
11    fn into(&self) -> String;
12}
13
14pub struct ParseError<'s> {
15    error: Box<dyn fmt::Display>,
16    input: &'s str,
17    name: &'static str,
18    location: Option<Range<usize>>
19}
20
21impl<'s> ParseError<'s> {
22    pub fn new<T>(error: T, input: &'s str, name: &'static str, mut location: Range<usize>) -> Self
23        where T: fmt::Display + 'static
24    {
25        location.start = location.start.clamp(0, input.len());
26        location.end   = location.end.clamp(location.start, input.len());
27
28        Self {
29            error: Box::new(error),
30            input, name,
31            location: (!location.is_empty()).then_some(location)
32        }
33    }
34
35    pub fn without_location<T>(error: T, input: &'s str, name: &'static str) -> Self
36        where T: fmt::Display + 'static
37    {
38        Self { error: Box::new(error), input, name, location: None }
39    }
40
41    pub fn pretty(&self, location: &str) -> String {
42        let message = format!("could not parse {} at {location}", self.name);
43
44        let snippet = Level::ERROR.primary_title(message).element({
45            Snippet::source(self.input)
46                .annotation(
47                    AnnotationKind::Primary.span(self.location.clone().unwrap_or(0..0))
48                        .label(self.error.to_string())
49                )
50        });
51
52        Renderer::styled().anonymized_line_numbers(true).render(&[snippet]).to_string()
53    }
54}
55
56impl fmt::Display for ParseError<'_> {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        if let Some(ref location) = self.location {
59            write!(f, "{} at `{}`", self.error, &self.input[location.clone()])
60        } else {
61            write!(f, "{} at `{}`", self.error, self.input)
62        }
63    }
64}
65
66impl<T: IntoGp + ?Sized> IntoGp for &T {
67    fn into(&self) -> String {
68        (*self).into()
69    }
70}
71
72#[cfg(feature = "num")]
73mod implement_rational {
74    use std::fmt::Display;
75    use num_rational::Ratio;
76    use num_integer::Integer;
77    use super::*;
78
79    impl<T> FromGp for Ratio<T>
80        where T: FromGp + Clone + Integer
81    {
82        fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
83            let (num, remainder): (T, &_) = FromGp::try_from(input)?;
84            let (den, remainder) = if let Some(rem) = remainder.trim_start().strip_prefix('/') {
85                let (den, new_rem): (T, &_) = FromGp::try_from(rem.trim_start())?;
86
87                if den.is_zero() {
88                    return Err(ParseError::without_location(
89                        "rational has zero denominator", input, Self::name()
90                    ));
91                } else {
92                    (den, new_rem)
93                }
94            } else {
95                return Ok((Ratio::from_integer(num), remainder))
96            };
97
98            Ok((Ratio::new(num, den), remainder))
99        }
100
101        fn name() -> &'static str {
102            "Rational"
103        }
104    }
105
106    impl<T> IntoGp for Ratio<T>
107        where T: IntoGp + Display + Clone + Integer
108    {
109        fn into(&self) -> String {
110            self.to_string()
111        }
112    }
113}
114
115mod implement_primitives {
116    use nom::{
117        error::{Error, ErrorKind, ParseError as NomParseError},
118        Parser, IResult, Err,
119        multi::separated_list0,
120        sequence::delimited,
121        character::complete::{char, multispace0},
122    };
123    use super::*;
124
125    impl<'s> NomParseError<&'s str> for ParseError<'s> {
126        fn from_error_kind(input: &'s str, kind: ErrorKind) -> Self {
127            ParseError::without_location(
128                kind.description().to_string(), input, "Unknown"
129            )
130        }
131
132        fn append(_: &'s str, _: ErrorKind, other: Self) -> Self {
133            other
134        }
135    } 
136
137    fn parser<'s, T: FromGp>(input: &'s str) -> IResult<&'s str, T, ParseError<'s>> {
138        FromGp::try_from(input)
139            .map(|(ret, remainder)| (remainder, ret))
140            .map_err(Err::Error)
141    }
142
143    fn parse_err<'s>(err: Err<ParseError<'s>>, name: &'static str) -> ParseError<'s> {
144        match err {
145            Err::Error(mut err) | Err::Failure(mut err) => {
146                err.name = name;
147                err
148            },
149            _ => unreachable!(),
150        }
151    }
152
153    impl<T: FromGp> FromGp for Vec<T> {
154        fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
155            delimited(
156                char('['),
157                separated_list0(
158                    char(','),
159                    delimited(
160                        multispace0,
161                        parser::<T>,
162                        multispace0,
163                    )
164                ),
165                char(']')
166            ).parse(input).map(|(i, o)| (o, i)).map_err(|err| parse_err(err, Self::name()))
167        }
168
169        fn name() -> &'static str {
170            "Vec<_>"
171        }
172    }
173
174    impl<T: IntoGp> IntoGp for Vec<T> {
175        fn into(&self) -> String {
176            format!("[{}]", self.iter().map(|item| item.into()).collect::<Vec<_>>().join(", "))
177        }
178    }
179
180    macro_rules! impl_primitive {
181        ($($primitive:ident)+) => {
182            $(
183        impl FromGp for $primitive {
184            fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
185                let (remainder, value) = nom::character::complete::$primitive(input)
186                    .map_err(
187                        |err: nom::Err<Error<&'s str>>|
188                            ParseError::without_location(err.to_string(), input, Self::name())
189                    )?;
190                
191                Ok((value, remainder))
192            }
193
194            fn name() -> &'static str {
195                stringify!($primitive)
196            }
197        }
198
199        impl IntoGp for $primitive {
200            fn into(&self) -> String {
201                self.to_string()
202            }
203        }
204            )+
205        }
206    }
207
208    impl_primitive!{ i8 u8 i16 u16 i32 u32 i64 u64 i128 u128 usize isize }
209}