1use super::tree::InlineSource;
4use crate::node::Point;
5use std::fmt;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum MdxFound {
11 Char(char),
13 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum MdxPlace {
30 BeforeName,
32 AfterName,
34 BeforeMemberName,
36 BeforeLocalName,
38 BeforeAttributeName,
40 InAttributeName,
42 BeforeLocalAttributeName,
44 InLocalAttributeName,
46 AfterAttributeName,
48 BeforeAttributeValue,
50 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#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum MdxErrorKind {
76 Unexpected {
78 found: MdxFound,
80 place: MdxPlace,
82 },
83 UnclosedExpression,
85 UnclosedAttributeValue {
87 quote: char,
89 },
90 SelfClosingSlashInClosingTag,
92 AttributeInClosingTag,
94 LazyLine,
96 TooDeep {
98 limit: usize,
100 },
101 UnopenedClosingTag,
103 MismatchedClosingTag {
106 closing: Option<String>,
108 opening: Option<String>,
110 opened_at: Option<Point>,
112 },
113 UnclosedFlowElement {
115 name: Option<String>,
117 opened_at: Point,
119 },
120 UnclosedTextElement {
122 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#[derive(Clone, Debug)]
194pub(super) struct Located {
195 pub(super) kind: MdxErrorKind,
196 pub(super) offset: usize,
197}
198
199impl Located {
200 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#[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 pub fn kind(&self) -> &MdxErrorKind {
223 &self.kind
224 }
225
226 pub fn position(&self) -> Option<&Point> {
228 self.position.as_ref()
229 }
230
231 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#[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 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
280fn 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}