yamd 0.19.0

Yet Another Markdown Document (flavour)
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
use std::ops::Range;

use crate::lexer::{Lexer, Token, TokenKind};
use crate::op::{Content, Node, Op};

/// Distinguishes unordered (`-`) from ordered (`+`) lists during parsing.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum ListKind {
    /// Unordered list, items prefixed with `-`. Maps to [`Node::UnorderedList`].
    Unordered,
    /// Ordered list, items prefixed with `+`. Maps to [`Node::OrderedList`].
    Ordered,
}

impl ListKind {
    pub(crate) fn node(&self) -> Node {
        match self {
            ListKind::Unordered => Node::UnorderedList,
            ListKind::Ordered => Node::OrderedList,
        }
    }
}

impl TryFrom<&Token> for ListKind {
    type Error = ();

    fn try_from(value: &Token) -> Result<Self, Self::Error> {
        if value.kind == TokenKind::Minus && value.range.len() == 1 {
            Ok(ListKind::Unordered)
        } else if value.kind == TokenKind::Plus && value.range.len() == 1 {
            Ok(ListKind::Ordered)
        } else {
            Err(())
        }
    }
}

/// Defines when the parser should treat the current position as a logical end-of-input.
///
/// Stop conditions are pushed onto a stack via [`Parser::with_eof`] and checked by
/// [`Parser::at_eof`]. This lets nested parsers (e.g., a paragraph inside a collapsible block)
/// stop at their enclosing delimiter without consuming it.
#[derive(Debug, Clone, Copy)]
pub(crate) enum StopCondition {
    /// Double newline — separates block-level elements.
    Terminator,
    /// `%}` at column 0 — ends a collapsible block.
    CollapsibleEnd,
    /// `!!` (two bangs) at column 0 — ends a highlight block.
    HighlightEnd,
    /// A list marker at or below the given nesting level — signals a sibling or parent item.
    ListBoundary { level: usize, kind: ListKind },
}

pub(crate) fn is_list_marker(t: &Token, kind: Option<ListKind>) -> bool {
    ListKind::try_from(t).is_ok_and(|k| kind.is_none_or(|want| k == want))
}

fn is_space_1(t: &Token) -> bool {
    t.kind == TokenKind::Space && t.range.len() == 1
}

fn at_list_boundary(p: &Parser, current_level: usize, max_level: usize, kind: ListKind) -> bool {
    for level in 0..=max_level {
        let k = if level == current_level {
            Some(kind)
        } else {
            None
        };
        let mut offset = p.pos;
        let matched = if level == 0 {
            p.tokens.get(offset).is_some_and(|t| t.position.column == 0) && {
                // check: list_marker, space_1
                p.tokens.get(offset).is_some_and(|t| is_list_marker(t, k)) && {
                    offset += 1;
                    p.tokens.get(offset).is_some_and(is_space_1)
                }
            }
        } else {
            p.tokens.get(offset).is_some_and(|t| t.position.column == 0) && {
                // check: space of len==level, list_marker, space_1
                p.tokens
                    .get(offset)
                    .is_some_and(|t| t.kind == TokenKind::Space && t.range.len() == level)
                    && {
                        offset += 1;
                        p.tokens.get(offset).is_some_and(|t| is_list_marker(t, k)) && {
                            offset += 1;
                            p.tokens.get(offset).is_some_and(is_space_1)
                        }
                    }
            }
        };
        if matched {
            return true;
        }
    }
    false
}

impl StopCondition {
    fn matches(&self, token: &Token, parser: &Parser) -> bool {
        match self {
            Self::Terminator => token.kind == TokenKind::Terminator,
            Self::CollapsibleEnd => {
                (token.kind == TokenKind::CollapsibleEnd && token.position.column == 0)
                    || (token.kind == TokenKind::Eol
                        && parser.tokens.get(parser.pos + 1).is_some_and(|t| {
                            t.kind == TokenKind::CollapsibleEnd && t.position.column == 0
                        }))
            }
            Self::HighlightEnd => {
                token.kind == TokenKind::Bang
                    && token.position.column == 0
                    && token.range.len() == 2
            }
            Self::ListBoundary { level, kind } => {
                token.position.column == 0 && at_list_boundary(parser, *level, *level + 1, *kind)
            }
        }
    }
}

/// Token-stream parser that produces a flat [`Op`] sequence.
///
/// Wraps the lexer output with a position cursor, a [`StopCondition`] stack for context-sensitive
/// end-of-input detection, and an output buffer of [`Op`]s.
///
/// Node-specific parsing functions (e.g., `heading`, `paragraph`) receive `&mut Parser`, use
/// [`eat`](Parser::eat)/[`at`](Parser::at) to match tokens, and push results to [`ops`](Parser::ops).
/// On mismatch they restore [`pos`](Parser::pos) and truncate `ops` to backtrack.
pub(crate) struct Parser<'a> {
    pub(crate) source: &'a str,
    tokens: Vec<Token>,
    pub(crate) pos: usize,
    eof_stack: Vec<StopCondition>,
    pub(crate) ops: Vec<Op>,
}

impl<'a> From<&'a str> for Parser<'a> {
    fn from(input: &'a str) -> Self {
        Self {
            source: input,
            tokens: Lexer::new(input).collect(),
            pos: 0,
            eof_stack: Vec::new(),
            ops: Vec::new(),
        }
    }
}

impl Parser<'_> {
    /// Returns the token at `index`, or `None` if out of bounds.
    #[inline]
    pub(crate) fn get(&self, index: usize) -> Option<&Token> {
        self.tokens.get(index)
    }

    /// Returns the current position and token, or `None` at end-of-stream.
    #[inline]
    pub(crate) fn peek(&self) -> Option<(usize, &Token)> {
        Some((self.pos, self.tokens.get(self.pos)?))
    }

    /// Advances the cursor by one. Does nothing at end-of-stream.
    #[inline]
    pub(crate) fn next(&mut self) {
        if self.pos < self.tokens.len() {
            self.pos += 1;
        }
    }

    /// Consumes the current token if `pred` returns `true`. Returns the token index range on match, or `None` (without advancing) on mismatch.
    #[inline]
    pub(crate) fn eat(&mut self, pred: impl Fn(&Token) -> bool) -> Option<Range<usize>> {
        let token = self.tokens.get(self.pos)?;
        if pred(token) {
            let start = self.pos;
            self.pos += 1;
            Some(start..self.pos)
        } else {
            None
        }
    }

    /// Returns `true` if the current token satisfies `pred`, without consuming it.
    #[inline]
    pub(crate) fn at(&self, pred: impl Fn(&Token) -> bool) -> bool {
        self.peek().is_some_and(|(_, t)| pred(t))
    }

    /// Pushes `cond` onto the stop-condition stack, runs `f`, then pops it.
    /// This scopes a stop condition to a parsing function — nested parsers see the condition
    /// via [`at_eof`](Parser::at_eof) and stop before consuming the delimiter.
    pub(crate) fn with_eof<R>(&mut self, cond: StopCondition, f: impl FnOnce(&mut Self) -> R) -> R {
        self.eof_stack.push(cond);
        let result = f(self);
        self.eof_stack.pop();
        result
    }

    /// Like [`with_eof`](Parser::with_eof) but pushes multiple conditions at once.
    pub(crate) fn with_eofs<R>(
        &mut self,
        conds: &[StopCondition],
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        for &c in conds {
            self.eof_stack.push(c);
        }
        let result = f(self);
        for _ in conds {
            self.eof_stack.pop();
        }
        result
    }

    /// Temporarily clears the stop-condition stack for the scope of `f`.
    /// Used when scanning verbatim content (e.g. a fenced code body) whose
    /// bytes must not be interpreted as delimiters of an enclosing block.
    pub(crate) fn with_no_stops<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
        let saved = std::mem::take(&mut self.eof_stack);
        let result = f(self);
        self.eof_stack = saved;
        result
    }

    /// Returns `true` if at end-of-stream or the current token matches any condition on the stop-condition stack.
    #[inline]
    pub(crate) fn at_eof(&self) -> bool {
        let Some((_, token)) = self.peek() else {
            return true;
        };
        self.eof_stack.iter().any(|cond| cond.matches(token, self))
    }

    /// Changes the token at `pos` to [`Literal`](crate::lexer::TokenKind::Literal).
    /// Used during backtracking to prevent a special character from being re-interpreted
    /// as a delimiter on the next parse attempt.
    pub(crate) fn flip_to_literal(&mut self, pos: usize) {
        if let Some(token) = self.tokens.get_mut(pos) {
            token.kind = TokenKind::Literal;
        }
    }

    /// Returns `true` if at a block boundary — either at logical EOF or at a [`Terminator`](StopCondition::Terminator) token.
    #[inline]
    pub(crate) fn at_block_boundary(&self) -> bool {
        self.at_eof() || self.at(|t| t.kind == TokenKind::Terminator)
    }

    /// Scans forward from the current position looking for a token that satisfies `matcher`.
    /// Returns `(before_range, match_range)` on success, where `before_range` covers tokens
    /// before the match and `match_range` covers the matched token. Backtracks to the starting
    /// position if no match is found before EOF or a stop condition.
    pub(crate) fn eat_until(
        &mut self,
        matcher: impl Fn(&Token) -> bool,
    ) -> Option<(Range<usize>, Range<usize>)> {
        let start = self.pos;
        while let Some(token) = self.tokens.get(self.pos) {
            if self.at_eof() {
                break;
            }
            if matcher(token) {
                let before = start..self.pos;
                let match_start = self.pos;
                self.pos += 1;
                return Some((before, match_start..self.pos));
            }
            self.pos += 1;
        }
        self.pos = start;
        None
    }

    /// Converts a token index range into [`Content`] using the tokens' byte ranges.
    /// Returns [`Content::Materialized`] when any token in the range is escaped (has gaps from
    /// removed backslashes), otherwise returns [`Content::Span`].
    #[inline]
    pub(crate) fn span(&self, range: Range<usize>) -> Content {
        if range.is_empty() {
            return Content::Span(0..0);
        }
        let tokens = &self.tokens[range];
        if tokens.iter().any(|t| t.escaped) {
            Content::from_tokens(tokens, self.source)
        } else {
            let byte_start = tokens.first().unwrap().range.start;
            let byte_end = tokens.last().unwrap().range.end;
            Content::Span(byte_start..byte_end)
        }
    }

    /// Consumes the parser and returns the accumulated operations.
    pub(crate) fn into_ops(self) -> Vec<Op> {
        self.ops
    }
}

/// Token predicate that matches an end-of-line token. Intended for use with [`Parser::eat`]
/// and [`Parser::at`].
pub(crate) fn eol(t: &Token) -> bool {
    t.kind == TokenKind::Eol
}

/// Attempts to eat a sequence of tokens matching the given predicates in order.
/// Returns `Some(start..end)` covering all matched tokens on success, or `None`
/// with the parser position restored on partial or full mismatch.
macro_rules! eat_seq {
    ($p:expr, $($pred:expr),+ $(,)?) => {{
        let start = $p.pos;
        if $( $p.eat($pred).is_some() )&&+ {
            Some(start..$p.pos)
        } else {
            $p.pos = start;
            None
        }
    }};
}

pub(crate) use eat_seq;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexer::TokenKind;

    #[test]
    fn eat_matches_and_consumes() {
        let mut p = Parser::from("hello world");
        let result = p.eat(|t| t.kind == TokenKind::Literal);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), 0..1);
        assert_eq!(p.pos, 1);
    }

    #[test]
    fn eat_no_match_does_not_advance() {
        let mut p = Parser::from("hello world");
        let result = p.eat(|t| t.kind == TokenKind::Star);
        assert!(result.is_none());
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn eat_at_eof_returns_none() {
        let mut p = Parser::from("");
        let result = p.eat(|t| t.kind == TokenKind::Literal);
        assert!(result.is_none());
    }

    #[test]
    fn at_matches_without_consuming() {
        let p = Parser::from("hello");
        assert!(p.at(|t| t.kind == TokenKind::Literal));
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn at_no_match() {
        let p = Parser::from("hello");
        assert!(!p.at(|t| t.kind == TokenKind::Star));
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn at_eof_returns_false() {
        let p = Parser::from("");
        assert!(!p.at(|t| t.kind == TokenKind::Literal));
    }

    #[test]
    fn next_at_eof_is_noop() {
        let mut p = Parser::from("");
        p.next();
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn flip_to_literal_out_of_range_is_noop() {
        let mut p = Parser::from("hi");
        p.flip_to_literal(usize::MAX);
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn eat_seq_matches_sequence() {
        let mut p = Parser::from("# hello");
        let result = eat_seq!(p, |t: &Token| t.kind == TokenKind::Hash, |t: &Token| t.kind
            == TokenKind::Space);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), 0..2);
        assert_eq!(p.pos, 2);
    }

    #[test]
    fn eat_seq_backtracks_on_partial_match() {
        let mut p = Parser::from("# hello");
        let result = eat_seq!(p, |t: &Token| t.kind == TokenKind::Hash, |t: &Token| t.kind
            == TokenKind::Star);
        assert!(result.is_none());
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn eat_seq_single_predicate() {
        let mut p = Parser::from("hello");
        let result = eat_seq!(p, |t: &Token| t.kind == TokenKind::Literal);
        assert!(result.is_some());
        assert_eq!(p.pos, 1);
    }

    #[test]
    fn eat_until_finds_match() {
        let mut p = Parser::from("hello\nworld");
        let result = p.eat_until(|t: &Token| t.kind == TokenKind::Eol);
        assert!(result.is_some());
        let (before, matched) = result.unwrap();
        assert_eq!(before, 0..1);
        assert_eq!(matched, 1..2);
    }

    #[test]
    fn eat_until_eof_hit() {
        let mut p = Parser::from("hello\n\nworld");
        p.with_eof(StopCondition::Terminator, |p| {
            let result = p.eat_until(|t: &Token| t.kind == TokenKind::Star);
            assert!(result.is_none());
            assert_eq!(p.pos, 0);
        });
    }

    #[test]
    fn eat_until_no_match_at_eof() {
        let mut p = Parser::from("hello");
        let result = p.eat_until(|t: &Token| t.kind == TokenKind::Star);
        assert!(result.is_none());
        assert_eq!(p.pos, 0);
    }

    #[test]
    fn at_eof_empty_stack_not_at_end() {
        let p = Parser::from("hello");
        assert!(!p.at_eof());
    }

    #[test]
    fn at_eof_empty_stack_at_end() {
        let p = Parser::from("");
        assert!(p.at_eof());
    }

    #[test]
    fn at_eof_terminator_on_stack() {
        let mut p = Parser::from("hello\n\nworld");
        p.with_eof(StopCondition::Terminator, |p| {
            assert!(!p.at_eof());
            p.next();
            assert!(p.at_eof());
        });
    }

    #[test]
    fn eof_guard_pops_on_drop() {
        let mut p = Parser::from("hello\n\nworld");
        p.with_eof(StopCondition::Terminator, |p| {
            p.next();
            assert!(p.at_eof());
        });
        assert!(!p.at_eof());
    }

    #[test]
    fn list_kind_node() {
        assert_eq!(ListKind::Unordered.node(), Node::UnorderedList);
        assert_eq!(ListKind::Ordered.node(), Node::OrderedList);
    }

    #[test]
    fn nested_guards_pop_in_order() {
        let mut p = Parser::from("hello\n\nworld");
        p.with_eof(StopCondition::Terminator, |p| {
            p.next();
            assert!(p.at_eof());
            p.with_eof(StopCondition::HighlightEnd, |p| {
                assert!(p.at_eof());
            });
            assert!(p.at_eof());
        });
    }
}