styled_str/
errors.rs

1//! Error types.
2
3use core::{fmt, ops, str};
4
5use compile_fmt::{Ascii, compile_panic};
6
7/// Error parsing hexadecimal RGB color.
8#[derive(Debug)]
9#[non_exhaustive]
10pub enum HexColorError {
11    /// Color string doesn't start with a hash `#`.
12    NoHash,
13    /// Color string has unexpected length (not 4 or 7).
14    InvalidLen,
15    /// Color string contains an invalid hex digit.
16    InvalidHexDigit,
17}
18
19impl fmt::Display for HexColorError {
20    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
21        formatter.write_str(self.as_str())
22    }
23}
24
25impl HexColorError {
26    const fn as_str(&self) -> &'static str {
27        match self {
28            Self::NoHash => "color string doesn't start with a hash `#`",
29            Self::InvalidLen => "color string has unexpected length (not 4 or 7)",
30            Self::InvalidHexDigit => "color string contains an invalid hex digit",
31        }
32    }
33}
34
35impl core::error::Error for HexColorError {}
36
37/// Kind of a [`ParseError`].
38#[derive(Debug)]
39#[non_exhaustive]
40pub enum ParseErrorKind {
41    /// Unfinished style, e.g. in `[[red`.
42    UnfinishedStyle,
43    /// Unsupported token in style, e.g. `[[what]]`.
44    UnsupportedStyle,
45    /// Error parsing a hexadecimal color spec, e.g. in `#c0g`.
46    HexColor(HexColorError),
47    /// Unfinished color specification, e.g. `color(`.
48    UnfinishedColor,
49    /// Invalid index color, e.g. `1234`.
50    InvalidIndexColor,
51    /// `on` token without the following color.
52    UnfinishedBackground,
53    /// Bogus delimiter encountered, e.g. in `[[red] on white]]`.
54    BogusDelimiter,
55    /// `*` token (copying previously used style) must be the first token in the spec.
56    NonInitialCopy,
57    /// `/` token (clearing style) must be the only token in the spec.
58    NonIsolatedClear,
59    /// Unsupported effect in a negation, e.g. `[[* -red]]`.
60    UnsupportedEffect,
61    /// Negation
62    NegationWithoutCopy,
63    /// Duplicate specified for the same property, like `[[bold bold]]` or `[[red green]]`.
64    DuplicateSpecifier,
65    /// Redundant negation, e.g. in `[[* -bold -bold]]`.
66    RedundantNegation,
67    /// ANSI escape char `\u{1b}` encountered in the text.
68    EscapeInText,
69
70    #[doc(hidden)] // should not occur unless private APIs are used
71    SpanOverflow,
72    #[doc(hidden)] // should not occur unless private APIs are used
73    TextOverflow,
74}
75
76impl ParseErrorKind {
77    pub(crate) const fn with_pos(self, pos: ops::Range<usize>) -> ParseError {
78        ParseError { kind: self, pos }
79    }
80
81    const fn as_str(&self) -> &'static str {
82        match self {
83            Self::UnfinishedStyle => "unfinished style definition",
84            Self::UnsupportedStyle => "unsupported style specifier",
85            Self::HexColor(err) => err.as_str(),
86            Self::UnfinishedColor => "unfinished color spec",
87            Self::InvalidIndexColor => "invalid indexed color",
88            Self::UnfinishedBackground => "no background specified after `on` keyword",
89            Self::BogusDelimiter => "bogus delimiter",
90            Self::NonInitialCopy => "* (copy) specifier must come first",
91            Self::NonIsolatedClear => "/ (clear) specifier must be the only token",
92            Self::UnsupportedEffect => "unsupported effect",
93            Self::NegationWithoutCopy => "negation without * (copy) specifier",
94            Self::DuplicateSpecifier => "duplicate specifier",
95            Self::RedundantNegation => "redundant negation",
96            Self::EscapeInText => "ANSI escape char 0x1b encountered in text",
97            Self::SpanOverflow => "too many spans",
98            Self::TextOverflow => "too much text",
99        }
100    }
101
102    const fn as_ascii_str(&self) -> Ascii<'static> {
103        Ascii::new(self.as_str())
104    }
105}
106
107impl fmt::Display for ParseErrorKind {
108    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109        formatter.write_str(self.as_str())
110    }
111}
112
113/// Errors that can occur parsing [`StyledString`](crate::StyledString)s from the [rich syntax](crate#rich-syntax).
114#[derive(Debug)]
115pub struct ParseError {
116    kind: ParseErrorKind,
117    pos: ops::Range<usize>,
118}
119
120impl ParseError {
121    /// Returns the kind of this error.
122    pub const fn kind(&self) -> &ParseErrorKind {
123        &self.kind
124    }
125
126    /// Returns (byte) position in the source string that corresponds to this error.
127    pub fn pos(&self) -> ops::Range<usize> {
128        self.pos.clone()
129    }
130
131    #[track_caller]
132    pub(crate) const fn compile_panic(self, raw: &str) -> ! {
133        let (_, hl) = raw.as_bytes().split_at(self.pos.start);
134        let (hl, _) = hl.split_at(self.pos.end - self.pos.start);
135        let Ok(hl) = str::from_utf8(hl) else {
136            panic!("internal error: invalid error range");
137        };
138
139        compile_panic!(
140            "invalid styled string at ",
141            self.pos.start => compile_fmt::fmt::<usize>(), "..", self.pos.end => compile_fmt::fmt::<usize>(),
142            " ('", hl => compile_fmt::clip(64, "…"),
143            "'): ", self.kind.as_ascii_str() => compile_fmt::clip_ascii(42, "")
144        );
145    }
146}
147
148impl fmt::Display for ParseError {
149    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150        write!(
151            formatter,
152            "invalid styled string at {:?}: {}",
153            self.pos, self.kind
154        )
155    }
156}
157
158impl core::error::Error for ParseError {}