David Tolnay | 5553501 | 2018-01-05 16:39:23 -0800 | [diff] [blame^] | 1 | // Copyright 2018 Syn Developers |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 6 | // option. This file may not be copied, modified, or distributed |
| 7 | // except according to those terms. |
| 8 | |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 9 | use std::error::Error; |
| 10 | use cursor::Cursor; |
| 11 | use std::fmt::{self, Display}; |
| 12 | |
| 13 | /// The result of a parser |
David Tolnay | f4aa6b4 | 2017-12-31 16:40:33 -0500 | [diff] [blame] | 14 | pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 15 | |
| 16 | /// An error with a default error message. |
| 17 | /// |
| 18 | /// NOTE: We should provide better error messages in the future. |
| 19 | pub fn parse_error<O>() -> PResult<'static, O> { |
| 20 | Err(ParseError(None)) |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug)] |
| 24 | pub struct ParseError(Option<String>); |
| 25 | |
| 26 | impl Error for ParseError { |
| 27 | fn description(&self) -> &str { |
| 28 | match self.0 { |
| 29 | Some(ref desc) => desc, |
| 30 | None => "failed to parse", |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | impl Display for ParseError { |
| 36 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 37 | <str as fmt::Display>::fmt(self.description(), f) |
| 38 | } |
| 39 | } |
| 40 | |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 41 | impl ParseError { |
| 42 | // For syn use only. Not public API. |
| 43 | #[doc(hidden)] |
| 44 | pub fn new<T: Into<String>>(msg: T) -> Self { |
| 45 | ParseError(Some(msg.into())) |
| 46 | } |
| 47 | } |