blob: 23d2a1aa0821c333245a8307339764709d11c54a [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;
David Tolnaydfc886b2018-01-06 08:03:09 -080010use buffer::Cursor;
David Tolnayc5ab8c62017-12-26 16:43:39 -050011use std::fmt::{self, Display};
12
David Tolnayb34f5702018-01-06 19:39:49 -080013/// 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 Tolnay461d98e2018-01-07 11:07:19 -080018///
19/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnayf4aa6b42017-12-31 16:40:33 -050020pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>;
David Tolnayc5ab8c62017-12-26 16:43:39 -050021
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
David Tolnayb34f5702018-01-06 19:39:49 -080029/// 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
David Tolnay461d98e2018-01-07 11:07:19 -080034///
35/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnayc5ab8c62017-12-26 16:43:39 -050036#[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 {
David Tolnayb34f5702018-01-06 19:39:49 -080050 Display::fmt(self.description(), f)
David Tolnayc5ab8c62017-12-26 16:43:39 -050051 }
52}
53
David Tolnayc5ab8c62017-12-26 16:43:39 -050054impl 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}