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; |
David Tolnay | dfc886b | 2018-01-06 08:03:09 -0800 | [diff] [blame] | 10 | use buffer::Cursor; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 11 | use std::fmt::{self, Display}; |
| 12 | |
David Tolnay | b34f570 | 2018-01-06 19:39:49 -0800 | [diff] [blame^] | 13 | /// The result of a `Synom` parser. |
| 14 | /// |
| 15 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 16 | /// |
| 17 | /// [module documentation]: index.html |
David Tolnay | f4aa6b4 | 2017-12-31 16:40:33 -0500 | [diff] [blame] | 18 | pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 19 | |
| 20 | /// An error with a default error message. |
| 21 | /// |
| 22 | /// NOTE: We should provide better error messages in the future. |
| 23 | pub fn parse_error<O>() -> PResult<'static, O> { |
| 24 | Err(ParseError(None)) |
| 25 | } |
| 26 | |
David Tolnay | b34f570 | 2018-01-06 19:39:49 -0800 | [diff] [blame^] | 27 | /// Error returned when a `Synom` parser cannot parse the input tokens. |
| 28 | /// |
| 29 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 30 | /// |
| 31 | /// [module documentation]: index.html |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 32 | #[derive(Debug)] |
| 33 | pub struct ParseError(Option<String>); |
| 34 | |
| 35 | impl Error for ParseError { |
| 36 | fn description(&self) -> &str { |
| 37 | match self.0 { |
| 38 | Some(ref desc) => desc, |
| 39 | None => "failed to parse", |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl Display for ParseError { |
| 45 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
David Tolnay | b34f570 | 2018-01-06 19:39:49 -0800 | [diff] [blame^] | 46 | Display::fmt(self.description(), f) |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 47 | } |
| 48 | } |
| 49 | |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 50 | impl ParseError { |
| 51 | // For syn use only. Not public API. |
| 52 | #[doc(hidden)] |
| 53 | pub fn new<T: Into<String>>(msg: T) -> Self { |
| 54 | ParseError(Some(msg.into())) |
| 55 | } |
| 56 | } |