blob: 2abfbc4710412d65c682cb50ac5436e4f397b056 [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 Tolnayf4aa6b42017-12-31 16:40:33 -050018pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>;
David Tolnayc5ab8c62017-12-26 16:43:39 -050019
20/// An error with a default error message.
21///
22/// NOTE: We should provide better error messages in the future.
23pub fn parse_error<O>() -> PResult<'static, O> {
24 Err(ParseError(None))
25}
26
David Tolnayb34f5702018-01-06 19:39:49 -080027/// 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 Tolnayc5ab8c62017-12-26 16:43:39 -050032#[derive(Debug)]
33pub struct ParseError(Option<String>);
34
35impl 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
44impl Display for ParseError {
45 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnayb34f5702018-01-06 19:39:49 -080046 Display::fmt(self.description(), f)
David Tolnayc5ab8c62017-12-26 16:43:39 -050047 }
48}
49
David Tolnayc5ab8c62017-12-26 16:43:39 -050050impl 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}