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 fmt::Debug for ParseError<'_> {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("ParseError")
69 .field("error", &self.error.to_string())
70 .field("input", &self.input)
71 .field("name", &self.name)
72 .field("location", &self.location)
73 .finish()
74 }
75}
76
77impl<T: IntoGp + ?Sized> IntoGp for &T {
78 fn into(&self) -> String {
79 (*self).into()
80 }
81}
82
83#[cfg(feature = "num")]
84mod implement_rational {
85 use std::fmt::Display;
86 use num_bigint::BigInt;
87 use num_rational::Ratio;
88 use num_integer::Integer;
89 use super::*;
90
91 impl FromGp for BigInt {
92 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
93 let remainder = input.trim_start_matches(['+', '-'])
94 .trim_start_matches(char::is_numeric);
95
96 let input = &input[0..(input.len() - remainder.len())];
97
98 let value = input.parse::<BigInt>()
99 .map_err(
100 |err| ParseError::without_location(err.to_string(), input, Self::name())
101 )?;
102
103 Ok((value, remainder))
104 }
105
106 fn name() -> &'static str {
107 "BigInt"
108 }
109 }
110
111 impl IntoGp for BigInt {
112 fn into(&self) -> String {
113 self.to_string()
114 }
115 }
116
117 impl<T> FromGp for Ratio<T>
118 where T: FromGp + Clone + Integer
119 {
120 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
121 let (num, remainder): (T, &_) = FromGp::try_from(input)?;
122 let (den, remainder) = if let Some(rem) = remainder.trim_start().strip_prefix('/') {
123 let (den, new_rem): (T, &_) = FromGp::try_from(rem.trim_start())?;
124
125 if den.is_zero() {
126 return Err(ParseError::without_location(
127 "rational has zero denominator", input, Self::name()
128 ));
129 } else {
130 (den, new_rem)
131 }
132 } else {
133 return Ok((Ratio::from_integer(num), remainder))
134 };
135
136 Ok((Ratio::new(num, den), remainder))
137 }
138
139 fn name() -> &'static str {
140 "Rational"
141 }
142 }
143
144 impl<T> IntoGp for Ratio<T>
145 where T: IntoGp + Display + Clone + Integer
146 {
147 fn into(&self) -> String {
148 self.to_string()
149 }
150 }
151}
152
153mod implement_primitives {
154 use nom::{
155 error::{Error, ErrorKind, ParseError as NomParseError},
156 Parser, IResult, Err,
157 multi::separated_list0,
158 sequence::{delimited, separated_pair},
159 character::complete::{char, multispace0, none_of},
160 bytes::complete::escaped,
161 };
162 use super::*;
163
164 impl<'s> NomParseError<&'s str> for ParseError<'s> {
165 fn from_error_kind(input: &'s str, kind: ErrorKind) -> Self {
166 ParseError::without_location(
167 kind.description().to_string(), input, "Unknown"
168 )
169 }
170
171 fn append(_: &'s str, _: ErrorKind, other: Self) -> Self {
172 other
173 }
174 }
175
176 fn parser<'s, T: FromGp>(input: &'s str) -> IResult<&'s str, T, ParseError<'s>> {
177 FromGp::try_from(input)
178 .map(|(ret, remainder)| (remainder, ret))
179 .map_err(Err::Error)
180 }
181
182 fn parse_err<'s>(err: Err<ParseError<'s>>, name: &'static str) -> ParseError<'s> {
183 match err {
184 Err::Error(mut err) | Err::Failure(mut err) => {
185 err.name = name;
186 err
187 },
188 _ => unreachable!(),
189 }
190 }
191
192 impl FromGp for String {
193 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
194 delimited(
195 char('"'),
196 escaped(none_of("\\\""), '\\', char('"')),
197 char('"'),
198 ).parse(input)
199 .map(|(i, o)| (o.to_string(), i))
200 .map_err(|err| parse_err(err, Self::name()))
201 }
202
203 fn name() -> &'static str {
204 "String"
205 }
206 }
207
208 impl IntoGp for String {
209 fn into(&self) -> String {
210 format!("\"{self}\"")
211 }
212 }
213
214 impl<T: FromGp> FromGp for Vec<T> {
215 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
216 delimited(
217 char('['),
218 separated_list0(
219 char(','),
220 delimited(
221 multispace0,
222 parser::<T>,
223 multispace0,
224 )
225 ),
226 char(']')
227 ).parse(input).map(|(i, o)| (o, i)).map_err(|err| parse_err(err, Self::name()))
228 }
229
230 fn name() -> &'static str {
231 "Vec<_>"
232 }
233 }
234
235 impl<T: IntoGp> IntoGp for Vec<T> {
236 fn into(&self) -> String {
237 IntoGp::into(self.as_slice())
238 }
239 }
240
241 impl<T: IntoGp> IntoGp for [T] {
242 fn into(&self) -> String {
243 format!("[{}]", self.iter().map(|item| item.into()).collect::<Vec<_>>().join(", "))
244 }
245 }
246
247 impl<T, U> FromGp for (T, U)
248 where T: FromGp, U: FromGp
249 {
250 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
251 delimited(
252 char('['),
253 separated_pair(
254 delimited(multispace0, parser::<T>, multispace0),
255 char(','),
256 delimited(multispace0, parser::<U>, multispace0),
257 ),
258 char(']')
259 ).parse(input).map(|(i, o)| (o, i)).map_err(|err| parse_err(err, Self::name()))
260 }
261
262 fn name() -> &'static str {
263 "(_, _)"
264 }
265 }
266
267 impl<T, U> IntoGp for (T, U)
268 where T: IntoGp, U: IntoGp
269 {
270 fn into(&self) -> String {
271 format!(
272 "[{}, {}]",
273 IntoGp::into(&self.0), IntoGp::into(&self.1)
274 )
275 }
276 }
277
278 impl<T, U, V> IntoGp for (T, U, V)
279 where T: IntoGp, U: IntoGp, V: IntoGp
280 {
281 fn into(&self) -> String {
282 format!(
283 "[{}, {}, {}]",
284 IntoGp::into(&self.0), IntoGp::into(&self.1), IntoGp::into(&self.2)
285 )
286 }
287 }
288
289 impl<T, U, V> FromGp for (T, U, V)
290 where T: FromGp, U: FromGp, V: FromGp
291 {
292 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
293 delimited(
294 char('['),
295 separated_pair(
296 delimited(multispace0, parser::<T>, multispace0),
297 char(','),
298 separated_pair(
299 delimited(multispace0, parser::<U>, multispace0),
300 char(','),
301 delimited(multispace0, parser::<V>, multispace0),
302 ),
303 ),
304 char(']')
305 ).parse(input)
306 .map(|(i, (t, (u, v)))| ((t, u, v), i))
307 .map_err(|err| parse_err(err, Self::name()))
308 }
309
310 fn name() -> &'static str {
311 "(_, _, _)"
312 }
313 }
314
315 macro_rules! impl_primitive {
316 ($($primitive:ident)+) => {
317 $(
318 impl FromGp for $primitive {
319 fn try_from<'s>(input: &'s str) -> Result<(Self, &'s str), ParseError<'s>> {
320 let (remainder, value) = nom::character::complete::$primitive(input)
321 .map_err(
322 |err: nom::Err<Error<&'s str>>|
323 ParseError::without_location(err.to_string(), input, Self::name())
324 )?;
325
326 Ok((value, remainder))
327 }
328
329 fn name() -> &'static str {
330 stringify!($primitive)
331 }
332 }
333
334 impl IntoGp for $primitive {
335 fn into(&self) -> String {
336 self.to_string()
337 }
338 }
339 )+
340 }
341 }
342
343 impl_primitive!{ i8 u8 i16 u16 i32 u32 i64 u64 i128 u128 usize isize }
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349 use num_bigint::BigInt;
350 use num_rational::Ratio;
351
352 fn verify<T: FromGp + IntoGp>(s: &str) {
353 let (parsed, _) = match T::try_from(s) {
354 Ok(n) => n,
355 Err(_) => panic!("failed to parse `{s}` into {}", T::name())
356 };
357
358 let as_str = <T as IntoGp>::into(&parsed);
359
360 assert_eq!(s, as_str);
361 }
362
363 #[test]
364 fn parse_num() {
365 let s = "9253845923452346502602680120245100230505000005606";
366
367 for i in 2..s.len() {
368 let input = &s[0..i];
369 let minus = format!("-{input}");
370 let minput = −
371
372 if i < 2 { verify::<u8>(input); verify::<i8>(input); verify::<i8>(minput); }
373 if i < 4 { verify::<u16>(input); verify::<i16>(input); verify::<i16>(minput); }
374 if i < 9 { verify::<u32>(input); verify::<i32>(input); verify::<i32>(minput); }
375 if i < 18 { verify::<u64>(input); verify::<i64>(input); verify::<i64>(minput); }
376 if i < 38 { verify::<u128>(input); verify::<i128>(input); verify::<i128>(minput); }
377
378 verify::<BigInt>(input); verify::<BigInt>(minput);
379 verify::<Ratio<BigInt>>(input); verify::<Ratio<BigInt>>(minput);
380 }
381 }
382
383 #[test]
384 fn parse_str() {
385 verify::<String>("\"test\"");
386 }
387}