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
//! Source lines and their positions.

use super::block::CODE_INDENT;
use super::flavor::Flavor;
use crate::node::Point;

/// The byte order mark.
pub(super) const BOM: char = '\u{feff}';

/// Leading whitespace: how many columns it spans, where tabs go to the next multiple of four, and how
/// many bytes it takes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Indent {
    pub(super) columns: usize,
    pub(super) bytes: usize,
}

#[derive(Clone, Copy)]
pub(super) struct Line<'a> {
    pub(super) number: u32,
    /// Byte offset of `text` within the original line, non-zero inside containers.
    pub(super) column: usize,
    pub(super) text: &'a str,
    /// Line terminator that follows `text`; empty on the last line without one.
    pub(super) eol: &'a str,
    /// Whether this is the last line of the document.
    pub(super) eof: bool,
    /// Whether this is the last line of a list item.
    pub(super) item_end: bool,
    /// Whether the line continues a paragraph without its container prefix.
    pub(super) lazy: bool,
    /// The tabs of the line, to compute columns without scanning the line again.
    pub(super) stops: &'a [TabStop],
    /// The whole line without its terminator, whatever a container removed from `text`, to turn byte
    /// offsets into columns.
    pub(super) whole: &'a str,
    /// Byte offset of the line in the document, to compare with `stops`.
    pub(super) base: usize,
    /// Columns left over from a tab that a container consumed only in part. They count as leading
    /// whitespace of `text`.
    pub(super) pad: usize,
    /// How many bytes of `text` are leading spaces and tabs, so that deeply indented lines in nested
    /// containers are not scanned again by every container.
    pub(super) ws: usize,
    /// The dialect of the document.
    pub(super) flavor: Flavor,
    /// For `*`, `-` and `_`: one past the offset in the line of the last byte that is neither that
    /// character, nor a space or tab, or 0 if there is none. A thematic break is a run of one of them
    /// and whitespace to the end of the line, so this tells at once, from any offset, that it is not.
    pub(super) others: [usize; 3],
}

impl<'a> Line<'a> {
    /// The indentation from which a line is code. Without indented code, indentation never matters.
    pub(super) fn code_indent(&self) -> usize {
        if self.flavor.has_indented_code() {
            CODE_INDENT
        } else {
            usize::MAX
        }
    }

    /// The zero-based visual column where `text` starts in the document.
    fn start_column(&self) -> usize {
        self.visual_column(self.column)
    }

    /// The zero-based visual column of the byte at `offset` in the line.
    fn visual_column(&self, offset: usize) -> usize {
        tab_adjusted_column(self.stops, self.base + offset, offset)
    }

    /// The leading whitespace.
    pub(super) fn indent(&self) -> Indent {
        let start = self.start_column();
        let end = self.visual_column(self.column + self.ws);
        Indent {
            columns: self.pad + end - start,
            bytes: self.ws,
        }
    }

    pub(super) fn is_blank(&self) -> bool {
        self.ws == self.text.len()
    }

    /// The position of the byte at `byte` in `text`. Columns are in UTF-16 code units, and a tab is one.
    pub(super) fn point(&self, byte: usize) -> Point {
        let offset = self.column + byte;
        Point {
            line: self.number,
            column: to_u32(offset - extra_bytes(&self.whole.as_bytes()[..offset.min(self.whole.len())]) + 1),
        }
    }

    /// The same line with the first `bytes` bytes removed.
    pub(super) fn skip(self, bytes: usize) -> Line<'a> {
        let text = &self.text[bytes..];
        Line {
            column: self.column + bytes,
            text,
            pad: 0,
            ws: self.ws.checked_sub(bytes).unwrap_or_else(|| leading_ws(text)),
            ..self
        }
    }

    /// The same line with `columns` columns of leading whitespace removed. What is left of a tab that
    /// is only consumed in part stays as padding.
    pub(super) fn skip_columns(self, columns: usize) -> Line<'a> {
        let (bytes, pad) = consume_columns(self.text.as_bytes(), self.start_column(), columns, self.pad);
        Line {
            column: self.column + bytes,
            text: &self.text[bytes..],
            pad,
            ws: self.ws - bytes,
            ..self
        }
    }

    pub(super) fn end(&self) -> Point {
        self.point(self.text.len())
    }
}

/// A tab in the document and the zero-based column right after it.
#[derive(Clone, Copy)]
pub(super) struct TabStop {
    at: usize,
    after: usize,
}

/// The column of the byte at `at` in the document: counted from the last tab before it, or `offset` if none.
/// `stops` is sorted by `at`.
fn tab_adjusted_column(stops: &[TabStop], at: usize, offset: usize) -> usize {
    let passed = stops.partition_point(|stop| stop.at < at);
    match passed.checked_sub(1).map(|index| stops[index]) {
        Some(stop) => stop.after + (at - stop.at - 1),
        None => offset,
    }
}

/// Every tab in `src` in order. A byte order mark at the start has no width.
pub(super) fn tab_stops(src: &str) -> Vec<TabStop> {
    let mut stops = Vec::new();
    // The byte offset and the column right after the last tab or line start.
    let (mut anchor, mut anchor_column) = (if src.starts_with(BOM) { BOM.len_utf8() } else { 0 }, 0);
    let bytes = src.as_bytes();
    for index in memchr::memchr_iter(b'\t', bytes) {
        if let Some(line_end) = memchr::memrchr2(b'\n', b'\r', &bytes[anchor..index]) {
            (anchor, anchor_column) = (anchor + line_end + 1, 0);
        }
        let column = anchor_column + (index - anchor);
        let after = (column / 4 + 1) * 4;
        stops.push(TabStop { at: index, after });
        (anchor, anchor_column) = (index + 1, after);
    }
    stops
}

/// Converts a count to a [`Point`] coordinate, saturating on inputs past `u32::MAX`.
pub(super) fn to_u32(value: usize) -> u32 {
    u32::try_from(value).unwrap_or(u32::MAX)
}

/// How many of `bytes`, which are whole characters, are more than UTF-16 code units: each continuation
/// byte is one, except that a character of four bytes is two code units.
pub(super) fn extra_bytes(bytes: &[u8]) -> usize {
    let (mut continuation, mut astral) = (0, 0);
    for &byte in bytes {
        continuation += usize::from(byte & 0xC0 == 0x80);
        astral += usize::from(byte >= 0xF0);
    }
    continuation - astral
}

/// Removes `columns` columns of leading whitespace from `text`, which starts at column `start`, after
/// the `pad` columns left over from a tab. Returns the bytes consumed and the new padding.
///
/// Only leading spaces and tabs are consumed, so the bytes never exceed `Line::ws`.
fn consume_columns(text: &[u8], start: usize, columns: usize, pad: usize) -> (usize, usize) {
    let mut remaining = columns;
    let consumed = remaining.min(pad);
    let mut pad = pad - consumed;
    remaining -= consumed;

    let mut absolute = start;
    let mut bytes = 0;
    for &byte in text {
        if remaining == 0 {
            break;
        }
        match byte {
            b' ' => {
                remaining -= 1;
                absolute += 1;
            }
            b'\t' => {
                let width = (absolute / 4 + 1) * 4 - absolute;
                absolute += width;
                if width > remaining {
                    pad = width - remaining;
                    remaining = 0;
                } else {
                    remaining -= width;
                }
            }
            _ => break,
        }
        bytes += 1;
    }
    (bytes, pad)
}

/// The number of leading spaces and tabs in `text`.
pub(super) fn leading_ws(text: &str) -> usize {
    text.bytes().take_while(|byte| matches!(byte, b' ' | b'\t')).count()
}

/// The `Line::others` of `text`. Scans from the end, where the first ordinary byte settles all three.
fn last_others(text: &str) -> [usize; 3] {
    let mut last = [0; 3];
    let mut settled = [false; 3];
    for (index, byte) in text.bytes().enumerate().rev() {
        let others: [bool; 3] = match byte {
            b' ' | b'\t' => continue,
            b'*' => [false, true, true],
            b'-' => [true, false, true],
            b'_' => [true, true, false],
            _ => [true; 3],
        };
        for marker in 0..3 {
            if others[marker] && !settled[marker] {
                (last[marker], settled[marker]) = (index + 1, true);
            }
        }
        if settled == [true; 3] {
            break;
        }
    }
    last
}

/// Splits `src` into lines on `\n`, `\r\n` and `\r`. A trailing terminator does not add a line.
pub(super) fn split_lines<'a>(src: &'a str, flavor: Flavor, stops: &'a [TabStop]) -> Vec<Line<'a>> {
    let bytes = src.as_bytes();
    // A `\r\n` counts twice, which only reserves a little more.
    let mut lines = Vec::with_capacity(memchr::memchr2_iter(b'\n', b'\r', bytes).count() + 1);
    let (mut start, mut index) = (0, 0);
    let mut next_stop = 0;
    // The tabs between `start` and `end`.
    let mut take_stops = |end: usize| {
        let first = next_stop;
        while stops.get(next_stop).is_some_and(|stop| stop.at < end) {
            next_stop += 1;
        }
        &stops[first..next_stop]
    };

    while let Some(found) = memchr::memchr2(b'\n', b'\r', &bytes[index..]) {
        let end = index + found;
        index = end
            + if bytes[end] == b'\r' && bytes.get(end + 1) == Some(&b'\n') {
                2
            } else {
                1
            };
        lines.push(Line {
            number: to_u32(lines.len() + 1),
            column: 0,
            text: &src[start..end],
            eol: &src[end..index],
            eof: index == bytes.len(),
            item_end: false,
            lazy: false,
            stops: take_stops(end),
            whole: &src[start..end],
            base: start,
            pad: 0,
            ws: leading_ws(&src[start..end]),
            flavor,
            others: last_others(&src[start..end]),
        });
        start = index;
    }

    if start < src.len() {
        lines.push(Line {
            number: to_u32(lines.len() + 1),
            column: 0,
            text: &src[start..],
            eol: "",
            eof: true,
            item_end: false,
            lazy: false,
            stops: take_stops(src.len()),
            whole: &src[start..],
            base: start,
            pad: 0,
            ws: leading_ws(&src[start..]),
            flavor,
            others: last_others(&src[start..]),
        });
    }

    lines
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    /// The byte offset of the `n`-th character boundary of `text`, counting from zero and wrapping.
    fn boundary(text: &str, n: usize) -> usize {
        let boundaries: Vec<usize> = text
            .char_indices()
            .map(|(index, _)| index)
            .chain([text.len()])
            .collect();
        boundaries[n % boundaries.len()]
    }

    proptest! {
        /// `Tree::extra_before` moves a cursor by `extra_bytes` of the text between two offsets.
        #[test]
        fn extra_bytes_is_additive_over_a_split(text in any::<String>(), a in any::<usize>(), b in any::<usize>()) {
            let (a, b) = (boundary(&text, a), boundary(&text, b));
            let (at, offset) = (a.min(b), a.max(b));
            let bytes = text.as_bytes();
            prop_assert_eq!(extra_bytes(&bytes[..offset]), extra_bytes(&bytes[..at]) + extra_bytes(&bytes[at..offset]));
        }

        /// `others[m]` is one past the last byte that is neither marker `m` nor whitespace.
        #[test]
        fn last_others_finds_the_last_byte_that_is_not_the_marker(text in "[-*_ \ta\u{e9}]{0,16}") {
            let expected = (*b"*-_").map(|marker| {
                text.bytes()
                    .rposition(|byte| !matches!(byte, b' ' | b'\t') && byte != marker)
                    .map_or(0, |index| index + 1)
            });
            prop_assert_eq!(last_others(&text), expected);
        }

        /// Lines and their tabs cover the source exactly, whatever the terminators.
        #[test]
        fn split_lines_covers_the_source(src in "[a\t\r\n]{0,24}") {
            let stops = tab_stops(&src);
            let lines = split_lines(&src, Flavor::Markdown, &stops);
            let joined: String = lines.iter().flat_map(|line| [line.text, line.eol]).collect();
            prop_assert_eq!(&joined, &src);
            prop_assert!(lines.iter().all(|line| !line.text.contains(['\r', '\n'])));
            prop_assert!(lines.iter().all(|line| matches!(line.eol, "" | "\n" | "\r" | "\r\n")));
            prop_assert_eq!(lines.iter().map(|line| line.stops.len()).sum::<usize>(), src.matches('\t').count());
            let columns: Vec<usize> = stops.iter().map(|stop| stop.after).collect();
            let mut expected = Vec::new();
            let mut column = 0;
            for byte in src.bytes() {
                match byte {
                    b'\n' | b'\r' => column = 0,
                    b'\t' => {
                        column = (column / 4 + 1) * 4;
                        expected.push(column);
                    }
                    _ => column += 1,
                }
            }
            prop_assert_eq!(columns, expected);
        }

        #[test]
        fn tab_adjusted_column_counts_from_the_last_tab(src in "[a\t\u{e9}\u{1f600}]{0,24}", at in 0usize..32) {
            let stops = tab_stops(&src);
            let at = at.min(src.len());
            let column = tab_adjusted_column(&stops, at, at);
            match src.as_bytes()[..at].iter().rposition(|byte| *byte == b'\t') {
                Some(tab) => {
                    let stop = stops.iter().find(|stop| stop.at == tab).unwrap();
                    prop_assert_eq!(column, stop.after + (at - tab - 1));
                }
                None => prop_assert_eq!(column, at),
            }
        }
    }
}

#[cfg(kani)]
mod proofs {
    use super::*;

    /// A well-formed UTF-8 buffer with two character boundaries `at <= offset`, as `Tree::extra_before` sees them.
    fn text_with_boundaries(bytes: &[u8; 6]) -> (usize, usize) {
        let text = std::str::from_utf8(bytes);
        kani::assume(text.is_ok());
        let text = text.unwrap_or_default();
        let at: usize = kani::any_where(|at: &usize| *at <= bytes.len() && text.is_char_boundary(*at));
        let offset: usize = kani::any_where(|o: &usize| *o >= at && *o <= bytes.len() && text.is_char_boundary(*o));
        (at, offset)
    }

    #[kani::proof]
    #[kani::unwind(8)]
    fn extra_bytes_does_not_underflow_on_whole_characters() {
        let bytes: [u8; 6] = kani::any();
        let (at, offset) = text_with_boundaries(&bytes);
        let _ = extra_bytes(&bytes[at..offset]);
    }

    /// The cursor in `Tree::extra_before` stores `extra_bytes(text[..at])`, so moving it back by
    /// `extra_bytes(text[offset..at])` never underflows.
    #[kani::proof]
    #[kani::unwind(8)]
    fn extra_bytes_is_additive_over_a_split() {
        let bytes: [u8; 6] = kani::any();
        let (at, offset) = text_with_boundaries(&bytes);
        kani::cover!(at > 0 && offset > at && extra_bytes(&bytes[at..offset]) > 0);
        assert_eq!(
            extra_bytes(&bytes[..offset]),
            extra_bytes(&bytes[..at]) + extra_bytes(&bytes[at..offset])
        );
    }

    /// `partition_point` finds the tabs before `at` only if `stops` is sorted, which `tab_stops` gives by
    /// walking `src` in order.
    #[kani::proof]
    #[kani::unwind(5)]
    fn tab_column_does_not_underflow() {
        let stops: [TabStop; 3] = [0, 1, 2].map(|_| TabStop {
            at: kani::any(),
            after: kani::any(),
        });
        kani::assume(stops[0].at < stops[1].at && stops[1].at < stops[2].at);
        // Bounded so that `after + (at - stop.at - 1)` stays within a document's size.
        kani::assume(stops.iter().all(|stop| stop.at < 1 << 32 && stop.after < 1 << 32));
        let (at, offset): (usize, usize) = (kani::any(), kani::any());
        kani::assume(at < 1 << 32 && offset < 1 << 32);
        let column = tab_adjusted_column(&stops, at, offset);
        if let Some(stop) = stops.iter().rev().find(|stop| stop.at < at) {
            assert_eq!(column, stop.after + (at - stop.at - 1));
        } else {
            assert_eq!(column, offset);
        }
    }

    /// Bytes consumed are leading blanks, so they never exceed the line's `ws` or length, and the
    /// columns taken from the request and from the leftover tab add up to what was asked.
    #[kani::proof]
    #[kani::unwind(6)]
    fn consume_columns_conserves_columns() {
        let text: [u8; 4] = kani::any();
        // Documents are far below 4 GiB, so columns and offsets stay below 1 << 32.
        let start: usize = kani::any_where(|n: &usize| *n < 1 << 32);
        let columns: usize = kani::any_where(|n: &usize| *n < 1 << 32);
        let pad: usize = kani::any_where(|n: &usize| *n < 1 << 32);
        let ws = text.iter().take_while(|byte| matches!(byte, b' ' | b'\t')).count();
        let (bytes, new_pad) = consume_columns(&text, start, columns, pad);
        assert!(bytes <= ws);
        assert!(bytes <= text.len());
        let mut absolute = start;
        for &byte in &text[..bytes] {
            absolute += if byte == b' ' {
                1
            } else {
                (absolute / 4 + 1) * 4 - absolute
            };
        }
        let width = absolute - start;
        if columns <= pad + width {
            assert_eq!(columns + new_pad, pad + width);
        } else {
            assert_eq!(new_pad, 0);
        }
    }
}