Skip to content

Commit fbf6e37

Browse files
committed
Implement std::error::Error for errors
1 parent 088093f commit fbf6e37

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/parser.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
use cow_rc_str::CowRcStr;
66
use smallvec::SmallVec;
7+
use std::error::Error;
8+
use std::fmt;
79
use std::ops::BitOr;
810
use std::ops::Range;
911
use tokenizer::{SourceLocation, SourcePosition, Token, Tokenizer};
@@ -53,6 +55,18 @@ pub enum BasicParseErrorKind<'i> {
5355
QualifiedRuleInvalid,
5456
}
5557

58+
impl<'i> BasicParseErrorKind<'i> {
59+
fn description(&self) -> &'static str {
60+
match self {
61+
BasicParseErrorKind::UnexpectedToken(_) => "Unexpected token",
62+
BasicParseErrorKind::EndOfInput => "End of input",
63+
BasicParseErrorKind::AtRuleInvalid(_) => "Invalid @ rule",
64+
BasicParseErrorKind::AtRuleBodyInvalid => "Invalid @ rule body",
65+
BasicParseErrorKind::QualifiedRuleInvalid => "Invalid qualified rule",
66+
}
67+
}
68+
}
69+
5670
/// The funamental parsing errors that can be triggered by built-in parsing routines.
5771
#[derive(Clone, Debug, PartialEq)]
5872
pub struct BasicParseError<'i> {
@@ -62,6 +76,14 @@ pub struct BasicParseError<'i> {
6276
pub location: SourceLocation,
6377
}
6478

79+
impl<'i> fmt::Display for BasicParseError<'i> {
80+
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
81+
write!(formatter, "{}", self.kind.description())
82+
}
83+
}
84+
85+
impl<'i> Error for BasicParseError<'i> {}
86+
6587
impl<'i, T> From<BasicParseError<'i>> for ParseError<'i, T> {
6688
#[inline]
6789
fn from(this: BasicParseError<'i>) -> ParseError<'i, T> {
@@ -156,6 +178,17 @@ impl<'i, T> ParseError<'i, T> {
156178
}
157179
}
158180

181+
impl<'i, T> fmt::Display for ParseError<'i, T> {
182+
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
183+
write!(formatter, "{}", match &self.kind {
184+
ParseErrorKind::Basic(basic_kind) => basic_kind.description(),
185+
ParseErrorKind::Custom(_) => "custom",
186+
})
187+
}
188+
}
189+
190+
impl<'i, T> Error for ParseError<'i, T> where T: fmt::Debug {}
191+
159192
/// The owned input for a parser.
160193
pub struct ParserInput<'i> {
161194
tokenizer: Tokenizer<'i>,

0 commit comments

Comments
 (0)