David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 1 | use std::error::Error; |
| 2 | use cursor::Cursor; |
| 3 | use std::fmt::{self, Display}; |
| 4 | |
| 5 | /// The result of a parser |
David Tolnay | f4aa6b4 | 2017-12-31 16:40:33 -0500 | [diff] [blame] | 6 | pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 7 | |
| 8 | /// An error with a default error message. |
| 9 | /// |
| 10 | /// NOTE: We should provide better error messages in the future. |
| 11 | pub fn parse_error<O>() -> PResult<'static, O> { |
| 12 | Err(ParseError(None)) |
| 13 | } |
| 14 | |
| 15 | #[derive(Debug)] |
| 16 | pub struct ParseError(Option<String>); |
| 17 | |
| 18 | impl Error for ParseError { |
| 19 | fn description(&self) -> &str { |
| 20 | match self.0 { |
| 21 | Some(ref desc) => desc, |
| 22 | None => "failed to parse", |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl Display for ParseError { |
| 28 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 29 | <str as fmt::Display>::fmt(self.description(), f) |
| 30 | } |
| 31 | } |
| 32 | |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 33 | impl ParseError { |
| 34 | // For syn use only. Not public API. |
| 35 | #[doc(hidden)] |
| 36 | pub fn new<T: Into<String>>(msg: T) -> Self { |
| 37 | ParseError(Some(msg.into())) |
| 38 | } |
| 39 | } |