Skip to main content

eternal_styler/
error.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Parse errors.
6
7use std::fmt;
8
9use cssparser::{BasicParseErrorKind, CowRcStr, ParseError, ParseErrorKind, ToCss, Token};
10use selectors::parser::SelectorParseErrorKind;
11
12/// Something in a stylesheet, declaration block or selector could not be
13/// parsed.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct Error {
16    kind: ErrorKind,
17    line: u32,
18    column: u32,
19}
20
21impl Error {
22    pub fn kind(&self) -> &ErrorKind {
23        &self.kind
24    }
25
26    /// The line the error was found on, starting at 1.
27    pub fn line(&self) -> u32 {
28        self.line
29    }
30
31    /// The column the error was found at, starting at 1 and counted in
32    /// UTF-16 code units, the way editors count.
33    pub fn column(&self) -> u32 {
34        self.column
35    }
36
37    pub(crate) fn from_parse_error(error: ParseError<'_, StyleParseErrorKind<'_>>) -> Self {
38        Self {
39            kind: ErrorKind::from_parse_error_kind(error.kind),
40            line: error.location.line + 1,
41            column: error.location.column,
42        }
43    }
44}
45
46impl fmt::Display for Error {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(
49            f,
50            "line {}, column {}: {}",
51            self.line, self.column, self.kind
52        )
53    }
54}
55
56impl std::error::Error for Error {}
57
58/// What went wrong.
59#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum ErrorKind {
62    /// A property this crate does not know about.
63    UnknownProperty(String),
64    /// A known property with a value it does not accept.
65    InvalidValue {
66        property: String,
67        reason: String,
68    },
69    InvalidSelector(String),
70    /// At-rules (`@media`, `@import`, ...) are not supported.
71    UnsupportedAtRule(String),
72    /// Anything else, such as an unexpected token.
73    Syntax(String),
74}
75
76impl ErrorKind {
77    fn from_parse_error_kind(kind: ParseErrorKind<'_, StyleParseErrorKind<'_>>) -> Self {
78        match kind {
79            ParseErrorKind::Basic(BasicParseErrorKind::AtRuleInvalid(name)) => {
80                Self::UnsupportedAtRule(name.to_string())
81            }
82            ParseErrorKind::Basic(BasicParseErrorKind::QualifiedRuleInvalid) => {
83                Self::InvalidSelector("invalid rule".to_owned())
84            }
85            ParseErrorKind::Basic(basic) => Self::Syntax(describe_basic(&basic)),
86            ParseErrorKind::Custom(custom) => match custom {
87                StyleParseErrorKind::UnknownProperty(name) => {
88                    Self::UnknownProperty(name.to_string())
89                }
90                StyleParseErrorKind::InvalidValue { property, reason } => Self::InvalidValue {
91                    property: property.to_string(),
92                    reason,
93                },
94                StyleParseErrorKind::UnsupportedColorSpace(space) => {
95                    Self::Syntax(format!("unsupported colour space '{space}'"))
96                }
97                StyleParseErrorKind::NegativeValue => {
98                    Self::Syntax("negative values are not allowed here".to_owned())
99                }
100                StyleParseErrorKind::OutOfRange => Self::Syntax("value out of range".to_owned()),
101                StyleParseErrorKind::Selector(kind) => {
102                    Self::InvalidSelector(describe_selector_error(&kind))
103                }
104            },
105        }
106    }
107}
108
109impl fmt::Display for ErrorKind {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        match self {
112            Self::UnknownProperty(name) => write!(f, "unknown property '{name}'"),
113            Self::InvalidValue { property, reason } => {
114                write!(f, "invalid value for '{property}': {reason}")
115            }
116            Self::InvalidSelector(reason) => write!(f, "invalid selector: {reason}"),
117            Self::UnsupportedAtRule(name) => write!(f, "unsupported at-rule '@{name}'"),
118            Self::Syntax(reason) => f.write_str(reason),
119        }
120    }
121}
122
123/// The custom half of cssparser's `ParseError` while parsing.
124#[derive(Debug, Clone, PartialEq)]
125pub(crate) enum StyleParseErrorKind<'i> {
126    UnknownProperty(CowRcStr<'i>),
127    InvalidValue {
128        property: CowRcStr<'i>,
129        reason: String,
130    },
131    UnsupportedColorSpace(&'static str),
132    NegativeValue,
133    OutOfRange,
134    Selector(SelectorParseErrorKind<'i>),
135}
136
137impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> {
138    fn from(kind: SelectorParseErrorKind<'i>) -> Self {
139        Self::Selector(kind)
140    }
141}
142
143/// A parse error carrying this crate's custom error kind.
144pub(crate) type StyleError<'i> = ParseError<'i, StyleParseErrorKind<'i>>;
145
146/// Wraps whatever went wrong inside a property value as an
147/// [`ErrorKind::InvalidValue`] for that property, keeping the location.
148pub(crate) fn value_error<'i>(property: CowRcStr<'i>, error: StyleError<'i>) -> StyleError<'i> {
149    let reason = ErrorKind::from_parse_error_kind(error.kind).to_string();
150    ParseError {
151        kind: ParseErrorKind::Custom(StyleParseErrorKind::InvalidValue { property, reason }),
152        location: error.location,
153    }
154}
155
156fn describe_token(token: &Token<'_>) -> String {
157    match token {
158        Token::WhiteSpace(_) => "whitespace".to_owned(),
159        Token::BadString(_) => "unterminated string".to_owned(),
160        Token::BadUrl(_) => "bad url".to_owned(),
161        token => format!("'{}'", token.to_css_string()),
162    }
163}
164
165fn describe_basic(kind: &BasicParseErrorKind<'_>) -> String {
166    match kind {
167        BasicParseErrorKind::UnexpectedToken(token) => {
168            format!("unexpected {}", describe_token(token))
169        }
170        BasicParseErrorKind::EndOfInput => "unexpected end of input".to_owned(),
171        BasicParseErrorKind::AtRuleInvalid(name) => format!("unsupported at-rule '@{name}'"),
172        BasicParseErrorKind::AtRuleBodyInvalid => "invalid at-rule body".to_owned(),
173        BasicParseErrorKind::QualifiedRuleInvalid => "invalid rule".to_owned(),
174    }
175}
176
177fn describe_selector_error(kind: &SelectorParseErrorKind<'_>) -> String {
178    use SelectorParseErrorKind::*;
179    match kind {
180        EmptySelector => "empty selector".to_owned(),
181        DanglingCombinator => "dangling combinator".to_owned(),
182        NonCompoundSelector => "expected a compound selector".to_owned(),
183        UnsupportedPseudoClassOrElement(name) => {
184            format!("unsupported pseudo-class or pseudo-element ':{name}'")
185        }
186        UnexpectedIdent(name) => format!("unexpected identifier '{name}'"),
187        ExpectedNamespace(name) => format!("unknown namespace '{name}'"),
188        ClassNeedsIdent(token) => {
189            format!("expected a class name, found {}", describe_token(token))
190        }
191        NoQualifiedNameInAttributeSelector(token) => format!(
192            "expected an attribute name, found {}",
193            describe_token(token)
194        ),
195        PseudoElementExpectedColon(token)
196        | PseudoElementExpectedIdent(token)
197        | NoIdentForPseudo(token) => format!(
198            "expected a pseudo-class name, found {}",
199            describe_token(token)
200        ),
201        UnexpectedTokenInAttributeSelector(token)
202        | ExpectedBarInAttr(token)
203        | BadValueInAttr(token)
204        | InvalidQualNameInAttr(token)
205        | ExplicitNamespaceUnexpectedToken(token) => {
206            format!("unexpected {} in selector", describe_token(token))
207        }
208        NonPseudoElementAfterSlotted
209        | InvalidPseudoElementAfterSlotted
210        | InvalidPseudoElementInsideWhere
211        | InvalidState => "invalid selector".to_owned(),
212    }
213}