core-markdown 0.2.0

CommonMark compliant markdown parser in Rust with ASTs and extensions
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
// Released under the MIT License.
// Copyright, 2026, by Samuel Williams.

//! Fixed Markdown escaping rules. Scopes and neighbor predicates are static;
//! matching allocates nothing and retains regex-style non-overlapping matches.
use super::{construct_name::ConstructName, util::safe::EscapeInfos};
use alloc::{string::String, vec::Vec};
use core::ops::Range;

const fn bit(name: ConstructName) -> u32 {
    1 << name as u32
}
use ConstructName::*;
const PHRASING: u32 = bit(Phrasing);
const FULL_SPANS: u32 = bit(Autolink)
    | bit(DestinationLiteral)
    | bit(DestinationRaw)
    | bit(Reference)
    | bit(TitleApostrophe)
    | bit(TitleQuote);
const LANGUAGE: u32 = bit(CodeFencedLangGraveAccent) | bit(CodeFencedLangTilde);
const NEWLINES: u32 = LANGUAGE
    | bit(CodeFencedMetaGraveAccent)
    | bit(CodeFencedMetaTilde)
    | bit(DestinationLiteral)
    | bit(HeadingAtx)
    | bit(MathFlowMeta);

#[derive(Clone, Copy)]
enum Before {
    Any,
    Previous(u8),
    Line,
    Digits,
}
#[derive(Clone, Copy)]
enum After {
    Any,
    Set(&'static [u8]),
    LineEnd,
    SpaceOrEnd,
    Entity,
    Html,
    Math,
}
struct Rule {
    byte: u8,
    before: Before,
    after: After,
    include: u32,
    exclude: u32,
}
// These are static records, not runtime constructors.
macro_rules! rule {
    ($byte:expr, $before:expr, $after:expr, $include:expr, $exclude:expr $(,)?) => {
        Rule {
            byte: $byte,
            before: $before,
            after: $after,
            include: $include,
            exclude: $exclude,
        }
    };
}
use After::{Any as A, Set};
use Before::{Any as B, Digits, Line, Previous};
static RULES: &[Rule] = &[
    rule!(b'\t', B, Set(b"\r\n"), PHRASING, 0),
    rule!(b'\t', Previous(b'\n'), A, PHRASING, 0),
    rule!(b'\t', Previous(b'\r'), A, PHRASING, 0),
    rule!(b'\t', B, A, LANGUAGE, 0),
    rule!(b'\r', B, A, NEWLINES, 0),
    rule!(b'\n', B, A, NEWLINES, 0),
    rule!(b' ', B, Set(b"\r\n"), PHRASING, 0),
    rule!(b' ', Previous(b'\n'), A, PHRASING, 0),
    rule!(b' ', Previous(b'\r'), A, PHRASING, 0),
    rule!(b' ', B, A, LANGUAGE, 0),
    rule!(b'!', B, Set(b"["), PHRASING, FULL_SPANS),
    rule!(b'"', B, A, bit(TitleQuote), 0),
    rule!(b'#', Line, A, 0, 0),
    rule!(b'#', B, After::LineEnd, bit(HeadingAtx), 0),
    rule!(b'&', B, After::Entity, PHRASING, 0),
    rule!(b'\'', B, A, bit(TitleApostrophe), 0),
    rule!(b'(', B, A, bit(DestinationRaw), 0),
    rule!(b'(', Previous(b']'), A, PHRASING, FULL_SPANS),
    rule!(b')', Digits, A, 0, 0),
    rule!(b')', B, A, bit(DestinationRaw), 0),
    rule!(b'*', Line, Set(b" \t\r\n*"), 0, 0),
    rule!(b'*', B, A, PHRASING, FULL_SPANS),
    rule!(b'+', Line, Set(b" \t\r\n"), 0, 0),
    rule!(b'-', Line, Set(b" \t\r\n-"), 0, 0),
    rule!(b'.', Digits, After::SpaceOrEnd, 0, 0),
    rule!(b'<', Line, After::Html, 0, 0),
    rule!(b'<', B, After::Html, PHRASING, FULL_SPANS),
    rule!(b'<', B, A, bit(DestinationLiteral), 0),
    rule!(b'=', Line, A, 0, 0),
    rule!(b'>', Line, A, 0, 0),
    rule!(b'>', B, A, bit(DestinationLiteral), 0),
    rule!(b'[', Line, A, 0, 0),
    rule!(b'[', B, A, PHRASING, FULL_SPANS),
    rule!(b'[', B, A, bit(Label) | bit(Reference), 0),
    rule!(b'\\', B, Set(b"\r\n"), PHRASING, 0),
    rule!(b']', B, A, bit(Label) | bit(Reference), 0),
    rule!(b'_', Line, A, 0, 0),
    rule!(b'_', B, A, PHRASING, FULL_SPANS),
    rule!(b'`', Line, A, 0, 0),
    rule!(
        b'`',
        B,
        A,
        bit(CodeFencedLangGraveAccent) | bit(CodeFencedMetaGraveAccent),
        0,
    ),
    rule!(b'`', B, A, PHRASING, FULL_SPANS),
    rule!(b'~', Line, A, 0, 0),
    rule!(b'$', B, After::Math, PHRASING, 0),
    rule!(b'$', B, A, bit(MathFlowMeta), 0),
    rule!(b'$', Line, Set(b"$"), 0, 0),
];

// A first character outside every escape rule stays literal in any formatting scope.
// CR/LF and ASCII spaces/tabs also stay on the full-render path for unwrap/task trimming.
pub(super) fn literal_prefix(value: &str) -> Option<char> {
    let first = value.chars().next()?;
    (!RULES.iter().any(|rule| char::from(rule.byte) == first)).then_some(first)
}

// Borrow neighboring text instead of assembling a copy of the growing output prefix.
#[derive(Clone, Copy)]
struct Context<'a>([&'a [u8]; 3]);

impl Context<'_> {
    fn get(self, mut position: usize) -> Option<u8> {
        for part in self.0 {
            if position < part.len() {
                return Some(part[position]);
            }
            position -= part.len();
        }
        None
    }

    fn find(self, byte: u8, start: usize) -> Option<usize> {
        let mut offset = 0;
        for part in self.0 {
            let from = start.saturating_sub(offset);
            if from < part.len() {
                if let Some(index) = memchr::memchr(byte, &part[from..]) {
                    return Some(offset + from + index);
                }
            }
            offset += part.len();
        }
        None
    }
}

fn scopes(stack: &[ConstructName]) -> u32 {
    stack.iter().fold(0, |mask, name| mask | bit(*name))
}

impl Rule {
    fn active(&self, scopes: u32) -> bool {
        (self.include == 0 || self.include & scopes != 0) && self.exclude & scopes == 0
    }
    fn at(&self, value: Context<'_>, position: usize, single_math: bool) -> Option<Range<usize>> {
        let start = match self.before {
            Before::Any => position,
            Before::Previous(byte) => {
                if position == 0 || value.get(position - 1) != Some(byte) {
                    return None;
                }
                position - 1
            }
            Before::Line | Before::Digits => {
                let mut at = position;
                if matches!(self.before, Before::Digits) {
                    // Markdown ordered-list markers use ASCII digits.
                    while at > 0 && value.get(at - 1).is_some_and(|byte| byte.is_ascii_digit()) {
                        at -= 1;
                    }
                    if at == position {
                        return None;
                    }
                }
                while at > 0 && matches!(value.get(at - 1), Some(b' ' | b'\t')) {
                    at -= 1;
                }
                if at == 0 || !matches!(value.get(at - 1), Some(b'\r' | b'\n')) {
                    return None;
                }
                at - 1
            }
        };
        let next = value.get(position + 1);
        let width = match self.after {
            After::Any => 0,
            After::Math if single_math => 0,
            After::Math => {
                if next == Some(b'$') {
                    1
                } else {
                    return None;
                }
            }
            After::Set(set) => {
                if next.is_some_and(|byte| set.contains(&byte)) {
                    1
                } else {
                    return None;
                }
            }
            After::LineEnd => match next {
                None => 0,
                Some(b'\r' | b'\n') => 1,
                _ => return None,
            },
            After::SpaceOrEnd => match next {
                None => 0,
                Some(b' ' | b'\t' | b'\r' | b'\n') => 1,
                _ => return None,
            },
            After::Entity => {
                if next.is_some_and(|byte| byte == b'#' || byte.is_ascii_alphabetic()) {
                    1
                } else {
                    return None;
                }
            }
            After::Html => {
                if next.is_some_and(|byte| {
                    matches!(byte, b'!' | b'/' | b'?') || byte.is_ascii_alphabetic()
                }) {
                    1
                } else {
                    return None;
                }
            }
        };
        Some(start..position + 1 + width)
    }
    fn matches<'a>(
        &'a self,
        value: Context<'a>,
        single_math: bool,
    ) -> impl Iterator<Item = (Range<usize>, usize)> + 'a {
        let mut search = 0;
        let mut minimum = 0;
        core::iter::from_fn(move || {
            while let Some(position) = value.find(self.byte, search) {
                if let Some(range) = self
                    .at(value, position, single_math)
                    .filter(|range| range.start >= minimum)
                {
                    search = range.end;
                    minimum = range.end;
                    return Some((range, position));
                }
                search = position + 1;
            }
            None
        })
    }
}

pub(super) fn collect(
    before: &str,
    input: &str,
    after: &str,
    stack: &[ConstructName],
    single_math: bool,
    output: &mut Vec<(usize, EscapeInfos)>,
) {
    let value = Context([before.as_bytes(), input.as_bytes(), after.as_bytes()]);
    let start = before.len().saturating_sub(1);
    let end = before.len() + input.len();
    let scopes = scopes(stack);
    for rule in RULES.iter().filter(|rule| rule.active(scopes)) {
        // Only input escapes and the immediately preceding escape can affect output.
        // Test candidates without a consumption boundary first; a possible match still
        // uses the full prefix walk to preserve non-overlapping neighbor consumption.
        let mut at = start;
        let mut possible = false;
        while let Some(position) = value.find(rule.byte, at).filter(|position| *position < end) {
            if rule.at(value, position, single_math).is_some() {
                possible = true;
                break;
            }
            at = position + 1;
        }
        if !possible {
            continue;
        }
        for (_, position) in rule.matches(value, single_math) {
            if position >= start && position < end {
                output.push((
                    position,
                    EscapeInfos {
                        before: !matches!(rule.before, Before::Any),
                        after: !matches!(rule.after, After::Any)
                            && !(matches!(rule.after, After::Math) && single_math),
                    },
                ));
            }
        }
    }
}

pub(super) fn unsafe_newline(stack: &[ConstructName]) -> bool {
    scopes(stack) & NEWLINES != 0
}

pub(super) fn normalize_inline(value: &mut String) {
    for rule in RULES
        .iter()
        .filter(|rule| matches!(rule.before, Before::Line | Before::Digits))
    {
        loop {
            let first = rule
                .matches(Context([b"", value.as_bytes(), b""]), false)
                .next();
            let Some((range, _)) = first else {
                break;
            };
            let at = range.start;
            let from = at
                - usize::from(
                    at > 0 && value.as_bytes()[at - 1] == b'\r' && value.as_bytes()[at] == b'\n',
                );
            value.replace_range(from..at + 1, " ");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{format, string::ToString};

    #[test]
    fn borrowed_context_preserves_matches_across_every_split() {
        for value in [
            "",
            "ordinary é α 世界",
            "\r\n \t12. next",
            "\n*\n*\n*\n* ",
            "\r\n-\r\n-\r\n-\r\n",
            "](![x] &amp; <$a> $$ ",
            "\\\r\n\t é\n  # heading\r\n",
            "\n123456) x\r\n",
            "`**__~~$",
        ] {
            let boundaries: Vec<_> = (0..=value.len())
                .filter(|&at| value.is_char_boundary(at))
                .collect();
            for &start in &boundaries {
                for &end in boundaries.iter().filter(|&&end| end >= start) {
                    let context = Context([
                        &value.as_bytes()[..start],
                        &value.as_bytes()[start..end],
                        &value.as_bytes()[end..],
                    ]);
                    for single in [false, true] {
                        for rule in RULES {
                            let expected: Vec<_> = rule
                                .matches(Context([b"", value.as_bytes(), b""]), single)
                                .collect();
                            let actual: Vec<_> = rule.matches(context, single).collect();
                            assert_eq!(actual, expected, "{value:?}, {start}..{end}");
                        }
                        for scope in [
                            Phrasing,
                            Label,
                            DestinationRaw,
                            HeadingAtx,
                            CodeFencedLangGraveAccent,
                        ] {
                            let mut actual = Vec::new();
                            collect(
                                &value[..start],
                                &value[start..end],
                                &value[end..],
                                &[scope],
                                single,
                                &mut actual,
                            );
                            let mut expected = Vec::new();
                            for rule in RULES.iter().filter(|rule| rule.active(bit(scope))) {
                                for (_, position) in rule.matches(context, single) {
                                    if position >= start.saturating_sub(1) && position < end {
                                        expected.push((
                                            position,
                                            !matches!(rule.before, Before::Any),
                                            !matches!(rule.after, After::Any)
                                                && !(matches!(rule.after, After::Math) && single),
                                        ));
                                    }
                                }
                            }
                            let actual: Vec<_> = actual
                                .into_iter()
                                .map(|(at, flags)| (at, flags.before, flags.after))
                                .collect();
                            assert_eq!(actual, expected, "{value:?}, {start}..{end}");
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn fixed_matchers_preserve_non_overlapping_regex_rules() {
        let contexts = [
            "", "\n", "\r\n  ", "\n\t123", "x]", "\n12", "\n123 ", "é", "\n\n",
        ];
        for rule in RULES {
            for single in [false, true] {
                let before = match rule.before {
                    Before::Any => "",
                    Before::Previous(b'\n') => "(\\n)",
                    Before::Previous(b'\r') => "(\\r)",
                    Before::Previous(_) => "(\\])",
                    Before::Line => "([\\r\\n][\\t ]*)",
                    Before::Digits => "([\\r\\n][\\t ]*[0-9]+)",
                };
                let after = match rule.after {
                    After::Any => "".to_string(),
                    After::Set(set) => {
                        format!("[{}]", regex::escape(core::str::from_utf8(set).unwrap()))
                    }
                    After::LineEnd => "(?:[\\r\\n]|$)".into(),
                    After::SpaceOrEnd => "(?:[ \\t\\r\\n]|$)".into(),
                    After::Entity => "[#A-Za-z]".into(),
                    After::Html => "[!/?A-Za-z]".into(),
                    After::Math if single => "".into(),
                    After::Math => "\\$".into(),
                };
                let expression = regex::Regex::new(&format!(
                    "{before}{}{after}",
                    regex::escape(&char::from(rule.byte).to_string())
                ))
                .unwrap();
                for left in contexts {
                    for right in contexts {
                        for byte in 0..=127u8 {
                            let value = format!(
                                "{left}{}{}{right}{}",
                                char::from(rule.byte),
                                char::from(byte),
                                char::from(rule.byte)
                            );
                            let actual: Vec<_> = rule
                                .matches(Context([b"", value.as_bytes(), b""]), single)
                                .collect();
                            let expected: Vec<_> = expression
                                .captures_iter(&value)
                                .map(|capture| {
                                    let found = capture.get(0).unwrap();
                                    let position = found.start()
                                        + capture.get(1).map_or(0, |group| group.len());
                                    (found.range(), position)
                                })
                                .collect();
                            assert_eq!(actual, expected, "{value:?}");
                        }
                    }
                }
            }
        }
    }
}