css_to_xpath/translate/error.rs
1//! Error types for selector translation.
2//!
3//! Errors always name the selector and the construct. The exact wording
4//! here is part of this crate's output contract and is pinned by tests.
5
6#[derive(Clone, Debug, Eq, PartialEq)]
7pub enum Error {
8 /// The selector is not valid CSS (as judged by Servo's parser).
9 /// The second field is the 1-indexed byte column of the error within the
10 /// selector string, used to render a caret pointer.
11 Parse(String, u32),
12 /// The selector is valid CSS, but uses a construct outside the
13 /// supported set: this crate errors rather than approximating.
14 Unsupported(String),
15}
16
17impl Error {
18 /// Render the user-facing message, naming the offending selector.
19 pub fn into_message(self, selector: &str) -> String {
20 match self {
21 Error::Parse(detail, column) => {
22 let caret_pos = (column as usize).saturating_sub(1).min(selector.len());
23 let caret_line = format!("{}{}", " ".repeat(caret_pos), "^");
24 format!(
25 "Unable to parse the CSS selector {selector:?}: {detail}\n |\n | {selector}\n | {caret_line}"
26 )
27 }
28 Error::Unsupported(construct) => format!(
29 "The CSS selector {selector:?} uses {construct}, which this translator does not support"
30 ),
31 }
32 }
33}