Skip to content

Commit

Permalink
basic std::error::Error implementations for Error and VerboseError
Browse files Browse the repository at this point in the history
  • Loading branch information
Geal committed Aug 24, 2020
1 parent 981d036 commit bf83d5d
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ impl<I> ParseError<I> for Error<I> {

impl<I> ContextError<I> for Error<I> {}

/// The Display implementation allows the std::error::Error implementation
impl<I: std::fmt::Display> std::fmt::Display for Error<I> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "error {:?} at: {}", self.code, self.input)
}
}
impl<I: std::fmt::Debug+std::fmt::Display> std::error::Error for Error<I> { }

// for backward compatibility, keep those trait implementations
// for the previously used error type
impl<I> ParseError<I> for (I, ErrorKind) {
fn from_error_kind(input: I, kind: ErrorKind) -> Self {
(input, kind)
Expand Down Expand Up @@ -155,6 +165,21 @@ impl<I> ContextError<I> for VerboseError<I> {
}
}

impl<I: std::fmt::Display> std::fmt::Display for VerboseError<I> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Parse error:\n")?;
for (input, error) in &self.errors {
match error {
VerboseErrorKind::Nom(e) => write!(f, "{:?} at: {}\n", e, input)?,
VerboseErrorKind::Char(c) => write!(f, "expected '{}' at: {}\n", c, input)?,
VerboseErrorKind::Context(s) => write!(f, "in section '{}', at: {}\n", s, input)?,
}
}

Ok(())
}
}

use crate::internal::{Err, IResult};

/// Create a new error from an input position, a static string and an existing error.
Expand Down

0 comments on commit bf83d5d

Please sign in to comment.