standalone_syn/error.rs
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
9use std::error::Error;
10use buffer::Cursor;
11use std::fmt::{self, Display};
12
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
18///
19/// *This type is available if Syn is built with the `"parsing"` feature.*
20pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>;
21
22/// An error with a default error message.
23///
24/// NOTE: We should provide better error messages in the future.
25pub fn parse_error<O>() -> PResult<'static, O> {
26 Err(ParseError(None))
27}
28
29/// Error returned when a `Synom` parser cannot parse the input tokens.
30///
31/// Refer to the [module documentation] for details about parsing in Syn.
32///
33/// [module documentation]: index.html
34///
35/// *This type is available if Syn is built with the `"parsing"` feature.*
36#[derive(Debug)]
37pub struct ParseError(Option<String>);
38
39impl Error for ParseError {
40 fn description(&self) -> &str {
41 match self.0 {
42 Some(ref desc) => desc,
43 None => "failed to parse",
44 }
45 }
46}
47
48impl Display for ParseError {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50 Display::fmt(self.description(), f)
51 }
52}
53
54impl ParseError {
55 // For syn use only. Not public API.
56 #[doc(hidden)]
57 pub fn new<T: Into<String>>(msg: T) -> Self {
58 ParseError(Some(msg.into()))
59 }
60}