blob: d1bb67096660feda898e2f1da1947ad15dd296d3 [file] [log] [blame]
David Tolnayc5ab8c62017-12-26 16:43:39 -05001use proc_macro;
2use proc_macro2;
3use std::error::Error;
4use cursor::Cursor;
5use std::fmt::{self, Display};
6
7/// The result of a parser
8pub 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.
13pub fn parse_error<O>() -> PResult<'static, O> {
14 Err(ParseError(None))
15}
16
17#[derive(Debug)]
18pub struct ParseError(Option<String>);
19
20impl 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
29impl 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
35impl 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
41impl 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
47impl 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