Skip to main content

mdwright_latex/
error.rs

1use std::fmt;
2use std::ops::Range;
3
4/// Byte span in the original math body.
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub struct SourceSpan {
7    start: usize,
8    end: usize,
9}
10
11impl SourceSpan {
12    pub(crate) const fn new(start: usize, end: usize) -> Self {
13        Self { start, end }
14    }
15
16    /// First byte in the span.
17    #[must_use]
18    pub const fn start(self) -> usize {
19        self.start
20    }
21
22    /// Byte after the last byte in the span.
23    #[must_use]
24    pub const fn end(self) -> usize {
25        self.end
26    }
27
28    /// Return this span as a standard byte range.
29    #[must_use]
30    pub fn as_range(self) -> Range<usize> {
31        self.start..self.end
32    }
33}
34
35/// Category of TeX math-body failure.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub enum LatexErrorKind {
38    /// A byte sequence is not a token in mdwright's TeX math grammar.
39    Lexical,
40    /// Tokens are well-formed, but the grammar rejects their order.
41    Syntax,
42    /// The input is valid TeX-like math, but mdwright cannot render or translate it yet.
43    Unsupported,
44}
45
46/// Typed TeX math-body error with source coordinates.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct LatexError {
49    kind: LatexErrorKind,
50    span: SourceSpan,
51    message: String,
52}
53
54impl LatexError {
55    pub(crate) fn new(kind: LatexErrorKind, span: SourceSpan, message: impl Into<String>) -> Self {
56        Self {
57            kind,
58            span,
59            message: message.into(),
60        }
61    }
62
63    /// Error category.
64    #[must_use]
65    pub const fn kind(&self) -> &LatexErrorKind {
66        &self.kind
67    }
68
69    /// Source byte span that caused the error.
70    #[must_use]
71    pub const fn span(&self) -> SourceSpan {
72        self.span
73    }
74
75    /// Human-readable error message.
76    #[must_use]
77    pub fn message(&self) -> &str {
78        &self.message
79    }
80}
81
82impl fmt::Display for LatexError {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(&self.message)
85    }
86}
87
88impl std::error::Error for LatexError {}