tui_markup/parser/
error.rs

1use std::fmt::{Display, Write};
2
3use super::LSpan;
4use crate::error::LocatedError;
5
6/// Kind of parse error.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum ErrorKind {
9    /// There is unescaped `<`, `>`, `\` character.
10    UnescapedChar,
11    /// There is a unescapable character after `\`.
12    UnescapableChar,
13    /// Element not closed but reaches line end.
14    ElementNotClose,
15}
16
17/// Error type for [parse][super::parse].
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Error<'a> {
20    nom_kind: nom::error::ErrorKind,
21    pub(crate) span: LSpan<'a>,
22    kind: Option<ErrorKind>,
23}
24
25impl<'a> Display for Error<'a> {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.write_str(match self.kind {
28            Some(kind) => match kind {
29                ErrorKind::UnescapedChar => "unescaped character",
30                ErrorKind::UnescapableChar => "unescapable character",
31                ErrorKind::ElementNotClose => "expect '>' to close element for element starter",
32            },
33            None => "unknown error",
34        })?;
35
36        f.write_char(' ')?;
37        if let Some(c) = self.span.chars().next() {
38            f.write_char('\'')?;
39            f.write_char(c)?;
40            f.write_char('\'')?;
41            f.write_char(' ')?;
42        }
43
44        f.write_fmt(format_args!("near {}:{}", self.span.extra, self.span.get_column()))
45    }
46}
47
48impl<'a> std::error::Error for Error<'a> {}
49
50impl<'a> Error<'a> {
51    pub(crate) fn attach(mut self, kind: ErrorKind) -> Self {
52        if self.kind.is_none() {
53            self.kind = Some(kind);
54        }
55        self
56    }
57
58    /// Get error kind.
59    #[must_use]
60    pub fn kind(&self) -> Option<ErrorKind> {
61        self.kind
62    }
63}
64
65impl<'a> LocatedError for Error<'a> {
66    fn location(&self) -> (usize, usize) {
67        (self.span.extra, self.span.get_column())
68    }
69}
70
71impl<'a> nom::error::ParseError<LSpan<'a>> for Error<'a> {
72    fn from_error_kind(input: LSpan<'a>, kind: nom::error::ErrorKind) -> Self {
73        Self {
74            nom_kind: kind,
75            span: input,
76            kind: None,
77        }
78    }
79
80    fn append(_input: LSpan<'a>, _kind: nom::error::ErrorKind, other: Self) -> Self {
81        other
82    }
83}