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