diff --git a/pest/src/error.rs b/pest/src/error.rs index c2ab8066..a83e23a4 100644 --- a/pest/src/error.rs +++ b/pest/src/error.rs @@ -16,6 +16,7 @@ use alloc::string::String; use alloc::string::ToString; use alloc::vec::Vec; use core::cmp; +use core::fmt; use core::mem; use crate::position::Position; @@ -25,8 +26,7 @@ use crate::RuleType; /// Parse-related error type. #[derive(Clone, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "std", derive(thiserror::Error))] -#[cfg_attr(feature = "std", error("{}", self.format()))] -pub struct Error { +pub struct Error { /// Variant of the error pub variant: ErrorVariant, /// Location within the input string @@ -41,9 +41,8 @@ pub struct Error { /// Different kinds of parsing errors. #[derive(Clone, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "std", derive(thiserror::Error))] -pub enum ErrorVariant { +pub enum ErrorVariant { /// Generated parsing error with expected and unexpected `Rule`s - #[cfg_attr(feature = "std", error("parsing error: {}", self.message()))] ParsingError { /// Positive attempts positives: Vec, @@ -51,7 +50,6 @@ pub enum ErrorVariant { negatives: Vec, }, /// Custom error with a message - #[cfg_attr(feature = "std", error("{}", self.message()))] CustomError { /// Short explanation message: String, @@ -520,6 +518,21 @@ impl ErrorVariant { } } +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.format()) + } +} + +impl fmt::Display for ErrorVariant { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ErrorVariant::ParsingError { .. } => write!(f, "parsing error: {}", self.message()), + ErrorVariant::CustomError { .. } => write!(f, "{}", self.message()), + } + } +} + fn visualize_whitespace(input: &str) -> String { input.to_owned().replace('\r', "␍").replace('\n', "␊") }