blob: eddb33f32114ab6ee98007aca4179f594a58b798 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// 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 Tolnayc5ab8c62017-12-26 16:43:39 -05009use std::error::Error;
10use cursor::Cursor;
11use std::fmt::{self, Display};
12
13/// The result of a parser
David Tolnayf4aa6b42017-12-31 16:40:33 -050014pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>;
David Tolnayc5ab8c62017-12-26 16:43:39 -050015
16/// An error with a default error message.
17///
18/// NOTE: We should provide better error messages in the future.
19pub fn parse_error<O>() -> PResult<'static, O> {
20 Err(ParseError(None))
21}
22
23#[derive(Debug)]
24pub struct ParseError(Option<String>);
25
26impl 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
35impl 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 Tolnayc5ab8c62017-12-26 16:43:39 -050041impl 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}