mq-markdown 0.10.2

Markdown parsing and manipulation utilities for mq
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! MDX: JSX tags and expressions, as the MDX syntax extensions to CommonMark define them, without a JavaScript parser,
//! so expressions are only checked for balanced braces, outside of strings, template literals and comments.

use super::error::{Located, MdxErrorKind, MdxFound, MdxPlace};
use super::scan::Span;
use crate::node::{MdxAttributeContent, MdxAttributeValue, MdxJsxAttribute};
use rustc_hash::FxHashMap;
use smol_str::SmolStr;
use std::cell::OnceCell;

/// What the end of the input means for a construct it ends inside of.
pub(super) enum Fallback {
    Nok,
    Error(Located),
}

/// The outcome of parsing at a position.
pub(super) enum Parsed<T> {
    Ok(T),
    /// Not this construct, so the text is something else.
    Nok,
    /// The input ended inside the construct. More input may complete it, and if there is none this
    /// is what the end of the input means for it.
    More(Fallback),
    /// The construct is invalid.
    Error(Located),
}

#[derive(Clone, Copy, PartialEq)]
pub(super) enum TagKind {
    Open,
    Close,
    SelfClosing,
}

/// A JSX tag: `<a b="c">`, `</a>` or `<a />`. A fragment has no name.
pub(super) struct Tag {
    pub(super) name: Option<String>,
    pub(super) attributes: Vec<MdxAttributeContent>,
    pub(super) kind: TagKind,
    /// Offset after the closing `>`.
    pub(super) end: usize,
}

/// Whether `char` can start a JavaScript identifier.
fn id_start(char: char) -> bool {
    unicode_id::UnicodeID::is_id_start(char) || matches!(char, '$' | '_')
}

/// Whether `char` can continue a JSX identifier, which may contain dashes.
fn id_continue(char: char) -> bool {
    unicode_id::UnicodeID::is_id_continue(char) || matches!(char, '\u{200c}' | '\u{200d}' | '-')
}

/// What a tag parser stops with: a failure of the construct, or of the input.
enum Stop {
    Nok,
    More(Fallback),
    Error(Located),
}

type Step<T> = Result<T, Stop>;

/// Where each `{` of a source closes, found in one pass the first time one is asked for, so that
/// many unclosed braces do not each scan to the end of the input.
#[derive(Default)]
pub(super) struct Braces(OnceCell<FxHashMap<usize, usize>>);

impl Braces {
    /// The offset of the `}` that closes the `{` at `open`, if there is one.
    fn close(&self, src: &str, open: usize) -> Option<usize> {
        self.0.get_or_init(|| match_braces(src, 0, false)).get(&open).copied()
    }
}

enum Frame {
    /// A `{`, or a `${` of a template literal when it has no offset.
    Brace(Option<usize>),
    Template,
}

/// Matches the braces of the expressions in `src` from `from`, which are not checked as JavaScript but
/// skip over strings, template literals and comments. Text outside braces is not looked at. With
/// `single`, `from` is a `{` and the search ends once it is closed.
fn match_braces(src: &str, from: usize, single: bool) -> FxHashMap<usize, usize> {
    let bytes = src.as_bytes();
    let mut closes = FxHashMap::default();
    let mut stack = Vec::new();
    let mut index = from;

    while index < bytes.len() {
        let byte = bytes[index];
        index += 1;
        match stack.last() {
            None => {
                if byte == b'{' {
                    stack.push(Frame::Brace(Some(index - 1)));
                }
            }
            Some(Frame::Template) => match byte {
                b'\\' => index += 1,
                b'`' => {
                    stack.pop();
                }
                b'$' if bytes.get(index) == Some(&b'{') => {
                    stack.push(Frame::Brace(None));
                    index += 1;
                }
                _ => {}
            },
            Some(Frame::Brace(_)) => match byte {
                b'{' => stack.push(Frame::Brace(Some(index - 1))),
                b'}' => {
                    if let Some(Frame::Brace(Some(open))) = stack.pop() {
                        closes.insert(open, index - 1);
                        if single && open == from {
                            break;
                        }
                    }
                }
                b'`' => stack.push(Frame::Template),
                b'\'' | b'"' => index = skip_string(bytes, index, byte).unwrap_or(index),
                b'/' => match bytes.get(index) {
                    Some(b'/') => {
                        index += bytes[index..].iter().take_while(|&&b| b != b'\n').count();
                    }
                    Some(b'*') => {
                        if let Some(end) = src[index + 1..].find("*/") {
                            index += 1 + end + 2;
                        }
                    }
                    _ => {}
                },
                _ => {}
            },
        }
    }
    closes
}

/// The offset after the string that starts before `from` with the `quote`. A string that does not end on
/// its line is not one.
fn skip_string(bytes: &[u8], from: usize, quote: u8) -> Option<usize> {
    let mut index = from;
    while let Some(&byte) = bytes.get(index) {
        match byte {
            b'\\' => index += 1,
            b'\n' | b'\r' => return None,
            _ if byte == quote => return Some(index + 1),
            _ => {}
        }
        index += 1;
    }
    None
}

struct Cursor<'a> {
    src: &'a str,
    index: usize,
    /// Set when the same source is searched for many expressions. Without it each one is scanned.
    braces: Option<&'a Braces>,
}

impl Cursor<'_> {
    fn peek(&self) -> Option<char> {
        self.src[self.index..].chars().next()
    }

    fn bump(&mut self) {
        if let Some(char) = self.peek() {
            self.index += char.len_utf8();
        }
    }

    /// The input ends inside a construct: more input may follow, otherwise it is not one.
    fn end_of_input<T>(&self) -> Step<T> {
        Err(Stop::More(Fallback::Nok))
    }

    /// The construct is invalid at the current position.
    fn crash<T>(&self, kind: MdxErrorKind) -> Step<T> {
        Err(Stop::Error(Located {
            kind,
            offset: self.index,
        }))
    }

    /// The current character, or the end of the input, cannot be at `place`.
    fn unexpected<T>(&self, place: MdxPlace) -> Step<T> {
        let found = self.peek().map_or(MdxFound::EndOfFile, MdxFound::Char);
        self.crash(MdxErrorKind::Unexpected { found, place })
    }

    /// Skips whitespace, including line endings. Ends the tag at the end of the input.
    fn skip_whitespace(&mut self) -> Step<()> {
        while self.peek().is_some_and(char::is_whitespace) {
            self.bump();
        }
        if self.peek().is_none() {
            return self.end_of_input();
        }
        Ok(())
    }

    fn name_part(&mut self) -> Step<&str> {
        let start = self.index;
        self.bump();
        while self.peek().is_some_and(id_continue) {
            self.bump();
        }
        Ok(&self.src[start..self.index])
    }

    /// The name of a tag, with its member (`.`) or namespace (`:`) parts, cleaned of whitespace.
    fn tag_name(&mut self) -> Step<String> {
        let mut name = self.name_part()?.to_string();
        self.skip_whitespace()?;
        match self.peek() {
            Some('.') => {
                while self.peek() == Some('.') {
                    self.bump();
                    self.skip_whitespace()?;
                    if !self.peek().is_some_and(id_start) {
                        return self.unexpected(MdxPlace::BeforeMemberName);
                    }
                    name.push('.');
                    name.push_str(self.name_part()?);
                    self.skip_whitespace()?;
                }
            }
            Some(':') => {
                self.bump();
                self.skip_whitespace()?;
                if !self.peek().is_some_and(id_start) {
                    return self.unexpected(MdxPlace::BeforeLocalName);
                }
                name.push(':');
                name.push_str(self.name_part()?);
                self.skip_whitespace()?;
            }
            _ => {}
        }
        Ok(name)
    }

    /// A `{...}` expression with balanced braces, returning the range of its content.
    fn expression(&mut self) -> Step<Span> {
        let open = self.index;
        self.bump();
        let start = self.index;
        let end = match self.braces {
            Some(braces) => braces.close(self.src, open),
            None => match_braces(self.src, open, true).get(&open).copied(),
        };
        let Some(end) = end else {
            self.index = self.src.len();
            return Err(Stop::More(Fallback::Error(Located {
                kind: MdxErrorKind::UnclosedExpression,
                offset: open,
            })));
        };
        self.index = end + 1;
        Ok(Span::new(start, end))
    }
}

impl Cursor<'_> {
    /// The value of an expression: its content, without up to two columns of whitespace at the start
    /// of each line after the first.
    fn expression_value(&self, content: Span) -> SmolStr {
        let content = content.of(self.src);
        if !content.contains(['\n', '\r']) {
            return SmolStr::new(content);
        }
        let mut value = String::with_capacity(content.len());
        // How many more columns of whitespace may be dropped at the start of the current line, and the
        // column that the line is at.
        let mut droppable = 0usize;
        let mut column = 0usize;
        for char in content.chars() {
            match char {
                '\n' | '\r' => {
                    droppable = 2;
                    column = 0;
                    value.push(char);
                }
                ' ' if droppable > 0 => {
                    droppable -= 1;
                    column += 1;
                }
                // What is left of a tab that is dropped in part stays as spaces.
                '\t' if droppable > 0 => {
                    let width = 4 - column % 4;
                    value.extend(std::iter::repeat_n(' ', width.saturating_sub(droppable)));
                    droppable = droppable.saturating_sub(width);
                    column += width;
                }
                _ => {
                    droppable = 0;
                    value.push(char);
                }
            }
        }
        SmolStr::new(value)
    }

    /// Checks the character after a name: whitespace or one of `allowed`.
    fn end_of_name(&self, allowed: &[char], place: MdxPlace) -> Step<()> {
        match self.peek() {
            None => self.end_of_input(),
            Some(char) if char.is_whitespace() || allowed.contains(&char) => Ok(()),
            Some(_) => self.unexpected(place),
        }
    }

    fn attribute(&mut self) -> Step<MdxAttributeContent> {
        let mut name = self.name_part()?.to_string();
        self.end_of_name(&['/', ':', '=', '>', '{'], MdxPlace::InAttributeName)?;
        self.skip_whitespace()?;

        if self.peek() == Some(':') {
            self.bump();
            self.skip_whitespace()?;
            if !self.peek().is_some_and(id_start) {
                return self.unexpected(MdxPlace::BeforeLocalAttributeName);
            }
            name.push(':');
            name.push_str(self.name_part()?);
            self.end_of_name(&['/', '=', '>', '{'], MdxPlace::InLocalAttributeName)?;
            self.skip_whitespace()?;
        }

        let name = SmolStr::new(name);
        if self.peek() != Some('=') {
            if !matches!(self.peek(), Some('/' | '>' | '{')) && !self.peek().is_some_and(id_start) {
                return self.unexpected(MdxPlace::AfterAttributeName);
            }
            return Ok(MdxAttributeContent::Property(MdxJsxAttribute { name, value: None }));
        }

        self.bump();
        self.skip_whitespace()?;
        let value = match self.peek() {
            Some(quote @ ('"' | '\'')) => {
                self.bump();
                let start = self.index;
                let Some(length) = self.src[start..].find(quote) else {
                    return Err(Stop::More(Fallback::Error(Located {
                        kind: MdxErrorKind::UnclosedAttributeValue { quote },
                        offset: start - 1,
                    })));
                };
                self.index = start + length + 1;
                MdxAttributeValue::Literal(SmolStr::new(super::inline::decode_references(
                    &self.src[start..start + length],
                )))
            }
            Some('{') => {
                let content = self.expression()?;
                MdxAttributeValue::Expression(self.expression_value(content))
            }
            _ => {
                return self.unexpected(MdxPlace::BeforeAttributeValue);
            }
        };
        Ok(MdxAttributeContent::Property(MdxJsxAttribute {
            name,
            value: Some(value),
        }))
    }

    fn tag(&mut self) -> Step<Tag> {
        // `<` is followed by a name, not by whitespace.
        match self.peek() {
            Some(' ' | '\t' | '\n' | '\r') => return Err(Stop::Nok),
            None => return self.end_of_input(),
            Some(_) => {}
        }
        self.skip_whitespace()?;

        let mut kind = TagKind::Open;
        if self.peek() == Some('/') {
            self.bump();
            self.skip_whitespace()?;
            kind = TagKind::Close;
        }

        let name = match self.peek() {
            Some('>') => None,
            Some(char) if id_start(char) => Some(self.tag_name()?),
            _ => return self.unexpected(MdxPlace::BeforeName),
        };
        if name.is_some() {
            self.end_of_tag_name()?;
        }

        let mut attributes = Vec::new();
        // Errors about a closing tag are reported once the tag is known to end.
        let mut misplaced = None;
        loop {
            match self.peek() {
                Some('/') => {
                    self.bump();
                    self.skip_whitespace()?;
                    if self.peek() != Some('>') {
                        return self.unexpected(MdxPlace::AfterSelfClosingSlash);
                    }
                    if kind == TagKind::Close {
                        return self.crash(MdxErrorKind::SelfClosingSlashInClosingTag);
                    }
                    kind = TagKind::SelfClosing;
                }
                Some('>') => {
                    self.bump();
                    break;
                }
                Some(char) if char == '{' || id_start(char) => {
                    if kind == TagKind::Close && misplaced.is_none() {
                        misplaced = Some(Located {
                            kind: MdxErrorKind::AttributeInClosingTag,
                            offset: self.index,
                        });
                    }
                    let attribute = if char == '{' {
                        let content = self.expression()?;
                        MdxAttributeContent::Expression(self.expression_value(content))
                    } else {
                        self.attribute()?
                    };
                    attributes.push(attribute);
                    self.skip_whitespace()?;
                }
                None => return self.end_of_input(),
                Some(_) => return self.unexpected(MdxPlace::BeforeAttributeName),
            }
        }

        if let Some(error) = misplaced {
            return Err(Stop::Error(error));
        }

        Ok(Tag {
            name,
            attributes,
            kind,
            end: self.index,
        })
    }

    /// After the name of a tag comes a slash, the end, or an attribute.
    fn end_of_tag_name(&self) -> Step<()> {
        match self.peek() {
            None => self.end_of_input(),
            Some('/' | '>' | '{') => Ok(()),
            // An attribute needs whitespace before it.
            Some(char) if id_start(char) && self.src[..self.index].ends_with(char::is_whitespace) => Ok(()),
            Some(_) => self.unexpected(MdxPlace::AfterName),
        }
    }
}

fn parsed<T>(step: Step<T>) -> Parsed<T> {
    match step {
        Ok(value) => Parsed::Ok(value),
        Err(Stop::Nok) => Parsed::Nok,
        Err(Stop::More(fallback)) => Parsed::More(fallback),
        Err(Stop::Error(error)) => Parsed::Error(error),
    }
}

/// Parses the JSX tag that starts at `pos`, a `<`.
pub(super) fn tag(src: &str, pos: usize, braces: Option<&Braces>) -> Parsed<Tag> {
    let mut cursor = Cursor {
        src,
        index: pos + 1,
        braces,
    };
    parsed(cursor.tag())
}

/// Parses the expression that starts at `pos`, a `{`, returning the offset after it and its value.
pub(super) fn expression(src: &str, pos: usize, braces: Option<&Braces>) -> Parsed<(usize, SmolStr)> {
    let mut cursor = Cursor {
        src,
        index: pos,
        braces,
    };
    parsed(
        cursor
            .expression()
            .map(|content| (content.end + 1, cursor.expression_value(content))),
    )
}