Skip to main content

mq_markdown/parser/
error.rs

1//! Errors in MDX, the only content that can be invalid.
2
3use super::tree::InlineSource;
4use crate::node::Point;
5use std::fmt;
6
7/// What a JSX tag has where something else must be.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum MdxFound {
11    /// A character.
12    Char(char),
13    /// The end of the input.
14    EndOfFile,
15}
16
17impl fmt::Display for MdxFound {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        match self {
20            MdxFound::Char(char) => write!(f, "character `{char}` (U+{:04X})", *char as u32),
21            MdxFound::EndOfFile => write!(f, "end of file"),
22        }
23    }
24}
25
26/// The part of a JSX tag where an unexpected character is.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum MdxPlace {
30    /// Before the name.
31    BeforeName,
32    /// After the name.
33    AfterName,
34    /// Before a member name after `.`.
35    BeforeMemberName,
36    /// Before a local name after `:`.
37    BeforeLocalName,
38    /// Before an attribute name.
39    BeforeAttributeName,
40    /// In an attribute name.
41    InAttributeName,
42    /// Before a local attribute name after `:`.
43    BeforeLocalAttributeName,
44    /// In a local attribute name.
45    InLocalAttributeName,
46    /// After an attribute name.
47    AfterAttributeName,
48    /// Before an attribute value.
49    BeforeAttributeValue,
50    /// After the `/` of a self-closing tag.
51    AfterSelfClosingSlash,
52}
53
54impl fmt::Display for MdxPlace {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.write_str(match self {
57            MdxPlace::BeforeName => "before name",
58            MdxPlace::AfterName => "after name",
59            MdxPlace::BeforeMemberName => "before member name",
60            MdxPlace::BeforeLocalName => "before local name",
61            MdxPlace::BeforeAttributeName => "before attribute name",
62            MdxPlace::InAttributeName => "in attribute name",
63            MdxPlace::BeforeLocalAttributeName => "before local attribute name",
64            MdxPlace::InLocalAttributeName => "in local attribute name",
65            MdxPlace::AfterAttributeName => "after attribute name",
66            MdxPlace::BeforeAttributeValue => "before attribute value",
67            MdxPlace::AfterSelfClosingSlash => "after self-closing slash",
68        })
69    }
70}
71
72/// What is wrong with invalid MDX.
73#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum MdxErrorKind {
76    /// A character, or the end of the input, where a JSX tag cannot have it.
77    Unexpected {
78        /// What the tag has there.
79        found: MdxFound,
80        /// The part of the tag it is in.
81        place: MdxPlace,
82    },
83    /// An expression without the `}` that closes its `{`.
84    UnclosedExpression,
85    /// An attribute value without its closing quote.
86    UnclosedAttributeValue {
87        /// The quote that opens the value.
88        quote: char,
89    },
90    /// A closing tag that ends with `/>`.
91    SelfClosingSlashInClosingTag,
92    /// A closing tag with attributes.
93    AttributeInClosingTag,
94    /// A line of an expression or a tag inside a container that lacks the prefix of the container.
95    LazyLine,
96    /// Elements nested deeper than the parser follows.
97    TooDeep {
98        /// The deepest nesting the parser follows.
99        limit: usize,
100    },
101    /// A closing tag without an element open.
102    UnopenedClosingTag,
103    /// A closing tag whose name is not that of the open element. Elements on lines of their own say
104    /// where the open one starts.
105    MismatchedClosingTag {
106        /// The name of the closing tag, or `None` for a fragment.
107        closing: Option<String>,
108        /// The name of the open element, or `None` for a fragment.
109        opening: Option<String>,
110        /// Where the open element starts, when it is on lines of its own.
111        opened_at: Option<Point>,
112    },
113    /// An element on lines of its own that is not closed in its container.
114    UnclosedFlowElement {
115        /// The name of the element, or `None` for a fragment.
116        name: Option<String>,
117        /// Where the element starts.
118        opened_at: Point,
119    },
120    /// An element in text that is not closed in its paragraph.
121    UnclosedTextElement {
122        /// The name of the element, or `None` for a fragment.
123        name: Option<String>,
124    },
125}
126
127impl fmt::Display for MdxErrorKind {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        let name = |name: &Option<String>| name.clone().unwrap_or_default();
130        match self {
131            MdxErrorKind::Unexpected { found, place } => write!(f, "Unexpected {found} {place}"),
132            MdxErrorKind::UnclosedExpression => {
133                write!(
134                    f,
135                    "Unexpected end of file in expression, expected a corresponding closing brace for `{{`"
136                )
137            }
138            MdxErrorKind::UnclosedAttributeValue { quote } => write!(
139                f,
140                "Unexpected end of file in attribute value, expected a corresponding closing quote `{quote}`"
141            ),
142            MdxErrorKind::SelfClosingSlashInClosingTag => write!(
143                f,
144                "Unexpected self-closing slash `/` in closing tag, expected the end of the tag"
145            ),
146            MdxErrorKind::AttributeInClosingTag => {
147                write!(f, "Unexpected attribute in closing tag, expected the end of the tag")
148            }
149            MdxErrorKind::LazyLine => write!(
150                f,
151                "Unexpected lazy line in expression in container, expected line to be prefixed with `>` when in a block quote, whitespace when in a list, etc"
152            ),
153            MdxErrorKind::TooDeep { limit } => write!(f, "Elements are nested deeper than {limit} levels"),
154            MdxErrorKind::UnopenedClosingTag => {
155                write!(f, "Unexpected closing slash `/` in tag, expected an open tag first")
156            }
157            MdxErrorKind::MismatchedClosingTag {
158                closing,
159                opening,
160                opened_at,
161            } => {
162                write!(
163                    f,
164                    "Unexpected closing tag `</{}>`, expected corresponding closing tag for `<{}>`",
165                    name(closing),
166                    name(opening)
167                )?;
168                match opened_at {
169                    Some(at) => write!(f, " ({}:{})", at.line, at.column),
170                    None => Ok(()),
171                }
172            }
173            MdxErrorKind::UnclosedFlowElement {
174                name: element,
175                opened_at,
176            } => write!(
177                f,
178                "Expected a closing tag for `<{}>` ({}:{}) before the end of its container",
179                name(element),
180                opened_at.line,
181                opened_at.column
182            ),
183            MdxErrorKind::UnclosedTextElement { name: element } => write!(
184                f,
185                "Expected a closing tag for `<{}>` before the end of the content",
186                name(element)
187            ),
188        }
189    }
190}
191
192/// An error at an offset of the text that is being parsed, before the offset is known as a position.
193#[derive(Clone, Debug)]
194pub(super) struct Located {
195    pub(super) kind: MdxErrorKind,
196    pub(super) offset: usize,
197}
198
199impl Located {
200    /// The error at its position in the document.
201    pub(super) fn in_source(self, source: &InlineSource) -> MdxError {
202        MdxError {
203            position: Some(source.point(self.offset)),
204            kind: self.kind,
205        }
206    }
207}
208
209/// Invalid MDX, with where it is in the document when that is known.
210#[derive(Clone, Debug, PartialEq, Eq)]
211pub struct MdxError {
212    kind: MdxErrorKind,
213    position: Option<Point>,
214}
215
216impl MdxError {
217    pub(super) fn new(kind: MdxErrorKind, position: Option<Point>) -> Self {
218        Self { kind, position }
219    }
220
221    /// What is wrong with the MDX.
222    pub fn kind(&self) -> &MdxErrorKind {
223        &self.kind
224    }
225
226    /// Where the error is, as a line and a column that count from 1.
227    pub fn position(&self) -> Option<&Point> {
228        self.position.as_ref()
229    }
230
231    /// A diagnostic that points at the error in `content`, the document it was found in.
232    pub(super) fn into_diagnostic(self, content: &str) -> MdxDiagnostic {
233        let span = self
234            .position
235            .as_ref()
236            .and_then(|point| offset_of(content, point))
237            .map(|offset| miette::SourceSpan::from((offset, 0)));
238        MdxDiagnostic {
239            error: self,
240            source_code: content.to_string(),
241            span,
242        }
243    }
244}
245
246impl fmt::Display for MdxError {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        self.kind.fmt(f)
249    }
250}
251
252impl std::error::Error for MdxError {}
253
254/// An [`MdxError`] with the document, to show where in it the error is.
255#[derive(Debug, miette::Diagnostic)]
256#[diagnostic(code(mq_markdown::mdx))]
257pub struct MdxDiagnostic {
258    error: MdxError,
259    #[source_code]
260    source_code: String,
261    #[label("here")]
262    span: Option<miette::SourceSpan>,
263}
264
265impl MdxDiagnostic {
266    /// The error.
267    pub fn error(&self) -> &MdxError {
268        &self.error
269    }
270}
271
272impl fmt::Display for MdxDiagnostic {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        self.error.fmt(f)
275    }
276}
277
278impl std::error::Error for MdxDiagnostic {}
279
280/// The byte offset of `point` in `content`, where columns count UTF-16 code units, as the positions of
281/// nodes do.
282fn offset_of(content: &str, point: &Point) -> Option<usize> {
283    let mut start = 0;
284    for _ in 1..point.line {
285        let rest = &content[start..];
286        let eol = rest.find(['\n', '\r'])?;
287        start += eol + if rest[eol..].starts_with("\r\n") { 2 } else { 1 };
288    }
289    let line = &content[start..];
290    let line = &line[..line.find(['\n', '\r']).unwrap_or(line.len())];
291    let mut column = 0;
292    for (index, char) in line.char_indices() {
293        if column + 1 >= point.column {
294            return Some(start + index);
295        }
296        column += char.len_utf16() as u32;
297    }
298    Some(start + line.len())
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use rstest::rstest;
305
306    #[rstest]
307    #[case::first("abc", 1, 2, Some(1))]
308    #[case::second_line("a\nbc", 2, 2, Some(3))]
309    #[case::crlf("a\r\nbc", 2, 1, Some(3))]
310    #[case::tab("\tx", 1, 2, Some(1))]
311    #[case::multibyte("éx", 1, 2, Some(2))]
312    #[case::astral("😀x", 1, 3, Some(4))]
313    #[case::end_of_line("ab\ncd", 1, 3, Some(2))]
314    #[case::missing_line("ab", 3, 1, None)]
315    fn offset_of_point(#[case] content: &str, #[case] line: u32, #[case] column: u32, #[case] expected: Option<usize>) {
316        assert_eq!(offset_of(content, &Point { line, column }), expected);
317    }
318}