1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! `Error` and `Result` types for this crate.

use std::io::Error as IOError;
use std::error::Error as StdError;

use pest::Span;
use pest::Position;
use pest::error::Error as PestError;
use pest::error::InputLocation;
use pest::error::LineColLocation;

use crate::ast::*;
use crate::parser::Rule;

/// An error for cardinality violation.
///
/// This error is highly dependent on the function that returns it: the `name`
/// field can provide more information about the specific clause that errored
/// to the end-user.
#[derive(Debug, Eq, Fail, PartialEq)]
pub enum CardinalityError {
    #[fail(display = "missing {:?} clause", name)]
    MissingClause { name: String },
    #[fail(display = "duplicate {:?} clauses", name)]
    DuplicateClauses { name: String },
    #[fail(display = "invalid single {:?} clause", name)]
    SingleClause { name: String }
}

impl CardinalityError {
    pub(crate) fn missing<S: Into<String>>(name: S) -> Self {
        CardinalityError::MissingClause {
            name: name.into()
        }
    }

    pub(crate) fn duplicate<S: Into<String>>(name: S) -> Self {
        CardinalityError::DuplicateClauses {
            name: name.into()
        }
    }

    pub(crate) fn single<S: Into<String>>(name: S) -> Self {
        CardinalityError::DuplicateClauses {
            name: name.into()
        }
    }
}

/// The error type for this crate.
#[derive(Debug, Fail)]
pub enum Error {
    /// An unexpected rule was used in `FromPair::from_pair`.
    ///
    /// # Example
    /// ```rust
    /// # extern crate fastobo;
    /// # use fastobo::ast::*;
    /// # use fastobo::parser::*;
    /// let pairs = OboParser::parse(Rule::UnquotedString, "hello, world!");
    /// # let err =
    /// QuotedString::from_pair(pairs.unwrap().next().unwrap()).unwrap_err();
    /// # match err {
    /// #   fastobo::error::Error::UnexpectedRule { expected, actual } => {
    /// #       assert_eq!(expected, Rule::QuotedString);
    /// #       assert_eq!(actual, Rule::UnquotedString);
    /// #   }
    /// #   e => panic!("unexpected error: {:?}", e),
    /// # };
    /// ```
    #[fail(display = "unexpected rule: {:?} (expected {:?})", actual, expected)]
    UnexpectedRule { expected: Rule, actual: Rule },

    /// The underlying parser encountered an error.
    ///
    /// # Example
    /// ```rust
    /// # extern crate fastobo;
    /// # use std::str::FromStr;
    /// # use fastobo::ast::*;
    /// # let err =
    /// QuotedString::from_str("definitely not a quoted string").unwrap_err();
    /// # match err {
    /// #   fastobo::error::Error::ParserError { .. } => (),
    /// #   e => panic!("unexpected error: {:?}", e),
    /// # };
    /// ```
    #[fail(display = "parser error: {}", error)]
    ParserError {
        #[cause]
        error: PestError<Rule>
    },

    /// An IO error occurred.
    ///
    /// # Example
    /// ```rust
    /// # extern crate fastobo;
    /// # use fastobo::ast::*;
    /// # let err =
    /// OboDoc::from_file("some/non-existing/path").unwrap_err();
    /// # match err {
    /// #   fastobo::error::Error::IOError { .. } => (),
    /// #   e => panic!("unexpected error: {:?}", e),
    /// # };
    #[fail(display = "IO error: {}", error)]
    IOError {
        #[cause]
        error: IOError
    },

    /// A cardinality-related error occurred.
    #[fail(display = "cardinality error: {}", inner)]
    CardinalityError {
        id: Option<Ident>,
        #[cause]
        inner: CardinalityError
    }
}

impl Error {
    /// Update the line of the error, if needed.
    pub(crate) fn with_offsets(self, line_offset: usize, offset: usize) -> Self {
        use self::Error::*;
        use pest::error::InputLocation;
        use pest::error::LineColLocation;
        match self {
            e @ IOError { .. } => e,
            e @ CardinalityError { .. } => e,
            e @ UnexpectedRule { .. } => e,
            ParserError { mut error } => {
                error.location = match error.location {
                    InputLocation::Pos(s) =>
                        InputLocation::Pos(s + offset),
                    InputLocation::Span((s, e)) =>
                        InputLocation::Span((s + offset, e + offset))
                };
                error.line_col = match error.line_col {
                    LineColLocation::Pos((l, c)) =>
                        LineColLocation::Pos((l + line_offset, c)),
                    LineColLocation::Span((ls, cs), (le, ce)) =>
                        LineColLocation::Span((ls + line_offset, cs), (le + line_offset, ce))
                };
                ParserError { error }
            }
        }
    }

    /// Update the path of the error, if needed.
    pub(crate) fn with_path(self, path: &str) -> Self {
        use self::Error::*;
        match self {
            e @ IOError { .. } => e,
            e @ UnexpectedRule { .. } => e,
            e @ CardinalityError { .. } => e,
            ParserError { error } => ParserError { error: error.with_path(path) },
        }
    }

    /// Update the span of the error, if needed.
    pub(crate) fn with_span<'i>(self, span: Span<'i>) -> Self {
        use self::Error::*;
        match self {
            e @ IOError { .. } => e,
            e @ UnexpectedRule { .. } => e,
            e @ CardinalityError { .. } => e,
            ParserError { error } => {
                // FIXME(@althonos): the new error should be spanned only if
                //                   the original error is spanned, but there
                //                   is no clean way to create an error at
                //                   the right position with `pest::error`.
                ParserError {
                    error: PestError::new_from_span(error.variant, span)
                }
            }
        }
    }
}

impl From<PestError<Rule>> for Error {
    fn from(error: PestError<Rule>) -> Self {
        Error::ParserError { error }
    }
}

impl From<IOError> for Error {
    fn from(error: IOError) -> Self {
        Error::IOError { error }
    }
}

/// The result type for this crate.
pub type Result<T> = std::result::Result<T, Error>;