tabnas_markdown/block.rs
1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Phase 1 of the CommonMark parse: block structure. Port of
4//! `ts/src/block.ts` (canonical) and `go/block.go`; keep the three in
5//! step, function for function. Spec 0.31.2, Appendix A "A parsing
6//! strategy".
7//!
8//! The document is a tree of blocks whose right spine (the document, then
9//! last child, then last child of that, and so on) is *open*: each open
10//! block imposes a continuation condition on the next line. For every line
11//! we
12//!
13//! 1. walk that spine, consuming each block's continuation marker (`>` for
14//! a block quote, the content indent for a list item, ...) and remember
15//! the last container that matched;
16//! 2. look for new block starts at the offset that walk reached, closing
17//! the unmatched tail of the spine as soon as a start actually matches;
18//! 3. add whatever is left of the line to the deepest open block, opening a
19//! paragraph if there is nowhere else for the text to go.
20//!
21//! Unmatched blocks are closed in step 2/3 rather than in step 1 because a
22//! paragraph line may be a *lazy continuation*: its containers' markers are
23//! missing, but the paragraph carries on regardless (section 5.1 rule 2).
24//!
25//! Positions on a line are tracked twice: `offset`, a BYTE index used to
26//! slice the text we keep (the TypeScript's is a UTF-16 index), and
27//! `column`, the tab-expanded display column used for every indent
28//! decision (section 2.2). Every block delimiter is ASCII and no UTF-8
29//! continuation byte can collide with one, so scanning by byte is exact;
30//! `column` and sourcepos columns still count CHARACTERS, which is what the
31//! spec means, so byte offsets pass through `char_count` on the way to a
32//! column. The two must move together, including the case where a marker
33//! consumes only part of a tab; see `advance_offset` and `add_line`.
34//!
35//! The two regexes in `block.ts` that use lookahead (the code fences) are
36//! hand-coded here, as they are in Go: the `regex` crate has no lookahead.
37//! Fence runs are counted with a loop, never with a regex built from an
38//! input-derived repeat count.
39//!
40//! This file owns everything the block phase sets on a node: type, level,
41//! literal (code_block / html_block), info / is_fenced, list_data
42//! (including the final `tight`), sourcepos, and `string_content`, the
43//! raw, unparsed text of paragraphs and headings that the inline phase
44//! consumes.
45
46use std::collections::HashMap;
47use std::sync::OnceLock;
48
49use regex::Regex;
50
51use crate::common::{js_trim, unescape_string};
52use crate::inline::parse_references;
53use crate::node::{
54 Align, ListData, ListType, MdNode, NodeId, NodeType, SourcePos, TableAlign, Tree,
55};
56use crate::options::{Options, RefMap};
57
58/// Section 4.4: four columns of indentation open an indented code block.
59const CODE_INDENT: usize = 4;
60
61/// One physical line of the source, with section 2.3's NUL replacement.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct LineSegment {
64 /// The line's text, terminator excluded.
65 pub text: String,
66 /// The byte offset past the terminator.
67 pub next: usize,
68}
69
70/// Cut the next physical line out of `src` at `pos`: up to (not including)
71/// the next `\n`, `\r` or `\r\n`, with `next` past the terminator. `None`
72/// at the end of the source, which is why a final line ending does not
73/// introduce a trailing blank line. Insecure NULs are replaced here, before
74/// anything else looks at the text.
75pub fn segment_next_line(src: &str, pos: usize) -> Option<LineSegment> {
76 if pos >= src.len() {
77 return None;
78 }
79 let bytes = src.as_bytes();
80 let mut i = pos;
81 while i < bytes.len() && bytes[i] != b'\n' && bytes[i] != b'\r' {
82 i += 1;
83 }
84 let mut next = i;
85 if next < bytes.len() {
86 if bytes[next] == b'\r' && next + 1 < bytes.len() && bytes[next + 1] == b'\n' {
87 next += 2;
88 } else {
89 next += 1;
90 }
91 }
92 let text = &src[pos..i];
93 let text = if text.contains('\0') {
94 text.replace('\0', "\u{FFFD}")
95 } else {
96 text.to_string()
97 };
98 Some(LineSegment { text, next })
99}
100
101/// Section 4.1: 3+ matching `*`, `_` or `-`, each optionally followed by
102/// spaces or tabs, and nothing else.
103pub fn is_thematic_break(s: &str) -> bool {
104 let bytes = s.as_bytes();
105 let Some(&c) = bytes.first() else {
106 return false;
107 };
108 if c != b'*' && c != b'_' && c != b'-' {
109 return false;
110 }
111 let mut count = 0;
112 for &b in bytes {
113 if b == c {
114 count += 1;
115 } else if b != b' ' && b != b'\t' {
116 return false;
117 }
118 }
119 count >= 3
120}
121
122/// Step 2's fast reject: every block start begins with one of these
123/// characters.
124pub fn maybe_special(ln: &str, pos: usize) -> bool {
125 match ln.as_bytes().get(pos) {
126 Some(c) => {
127 matches!(
128 c,
129 b'#' | b'`' | b'~' | b'*' | b'+' | b'_' | b'=' | b'<' | b'>' | b'-'
130 ) || c.is_ascii_digit()
131 }
132 None => false,
133 }
134}
135
136/// The same fast reject with `|` and `:` added, used when GFM is on: a GFM
137/// table's delimiter row may begin with either (`| --- |`, `:-: | ---:`),
138/// and neither is a CommonMark block start.
139///
140/// Kept separate so that a GFM-off parse takes exactly the path it always
141/// did: same characters rejected, same lines never offered to the block
142/// starts at all.
143pub fn maybe_special_gfm(ln: &str, pos: usize) -> bool {
144 match ln.as_bytes().get(pos) {
145 Some(c) => {
146 matches!(
147 c,
148 b'#' | b'`' | b'~' | b'*' | b'+' | b'_' | b'=' | b'<' | b'>' | b'-' | b':' | b'|'
149 ) || c.is_ascii_digit()
150 }
151 None => false,
152 }
153}
154
155/// Nothing but spaces, tabs, form feeds, vertical tabs and line endings.
156/// All members of the set are ASCII, so a byte scan classifies UTF-8
157/// correctly: a continuation byte counts as non-space, as the character it
158/// belongs to would.
159pub fn is_blank(s: &str) -> bool {
160 s.bytes()
161 .all(|b| matches!(b, b' ' | b'\t' | b'\x0c' | b'\x0b' | b'\r' | b'\n'))
162}
163
164/// Section 5.2: a bullet list marker is one of `*`, `+`, `-`.
165pub fn is_bullet_list_marker(s: &str) -> bool {
166 matches!(s.as_bytes().first(), Some(b'*' | b'+' | b'-'))
167}
168
169/// Section 5.2: an ordered list marker is 1 to 9 digits and `.` or `)`.
170/// Returns the digit count and the delimiter. Ten or more digits do not
171/// match.
172pub fn match_ordered_list_marker(s: &str) -> Option<(usize, u8)> {
173 let bytes = s.as_bytes();
174 let mut i = 0;
175 while i < bytes.len() && bytes[i].is_ascii_digit() {
176 i += 1;
177 }
178 if !(1..=9).contains(&i) || i >= bytes.len() {
179 return None;
180 }
181 if bytes[i] == b'.' || bytes[i] == b')' {
182 return Some((i, bytes[i]));
183 }
184 None
185}
186
187/// Section 4.2: 1 to 6 `#` followed by spaces or tabs, or the end of the
188/// line. Returns the level and the whole marker's length. Seven or more `#`
189/// do not match.
190pub fn match_atx_heading_marker(s: &str) -> Option<(usize, usize)> {
191 let bytes = s.as_bytes();
192 let mut n = 0;
193 while n < bytes.len() && bytes[n] == b'#' {
194 n += 1;
195 }
196 if !(1..=6).contains(&n) {
197 return None;
198 }
199 if n == bytes.len() {
200 return Some((n, n));
201 }
202 if bytes[n] != b' ' && bytes[n] != b'\t' {
203 return None;
204 }
205 let mut i = n;
206 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
207 i += 1;
208 }
209 Some((n, i))
210}
211
212/// Section 4.2: drop an optional closing sequence of `#`s, preceded by
213/// spaces or tabs; a line of nothing but `#`s (and spaces) has empty
214/// content. Hand-coded from the two regexes the TypeScript uses.
215pub fn strip_atx_closing(content: &str) -> &str {
216 let bytes = content.as_bytes();
217 let space = |b: u8| b == b' ' || b == b'\t';
218
219 // /^[ \t]*#+[ \t]*$/ : the whole line is one closing sequence.
220 let mut i = 0;
221 while i < bytes.len() && space(bytes[i]) {
222 i += 1;
223 }
224 let hashes_start = i;
225 while i < bytes.len() && bytes[i] == b'#' {
226 i += 1;
227 }
228 let hashes = i - hashes_start;
229 while i < bytes.len() && space(bytes[i]) {
230 i += 1;
231 }
232 if hashes > 0 && i == bytes.len() {
233 return "";
234 }
235
236 // /[ \t]+#+[ \t]*$/ : a trailing closing sequence after content.
237 let mut end = bytes.len();
238 while end > 0 && space(bytes[end - 1]) {
239 end -= 1;
240 }
241 let hashes_end = end;
242 while end > 0 && bytes[end - 1] == b'#' {
243 end -= 1;
244 }
245 if end == hashes_end {
246 return content;
247 }
248 let spaces_end = end;
249 while end > 0 && space(bytes[end - 1]) {
250 end -= 1;
251 }
252 if end == spaces_end {
253 return content;
254 }
255 &content[..end]
256}
257
258/// Section 4.5: the opening code fence at the start of `s`, as its length,
259/// or 0. A backtick fence is only a fence if the rest of the line (the info
260/// string) holds no backtick; a tilde fence has no such restriction.
261pub fn match_code_fence(s: &str) -> usize {
262 let bytes = s.as_bytes();
263 let Some(&c) = bytes.first() else {
264 return 0;
265 };
266 if c != b'`' && c != b'~' {
267 return 0;
268 }
269 let mut n = 0;
270 while n < bytes.len() && bytes[n] == c {
271 n += 1;
272 }
273 if n < 3 {
274 return 0;
275 }
276 if c == b'`' && bytes[n..].contains(&b'`') {
277 return 0;
278 }
279 n
280}
281
282/// Section 4.5: the closing-fence candidate at the start of `s`, as its
283/// length, or 0: the maximal run must be followed by spaces or tabs only.
284/// The caller still checks the fence character and length against the open
285/// block.
286pub fn match_closing_code_fence(s: &str) -> usize {
287 let bytes = s.as_bytes();
288 let Some(&c) = bytes.first() else {
289 return 0;
290 };
291 if c != b'`' && c != b'~' {
292 return 0;
293 }
294 let mut n = 0;
295 while n < bytes.len() && bytes[n] == c {
296 n += 1;
297 }
298 if n < 3 {
299 return 0;
300 }
301 if bytes[n..].iter().any(|&b| b != b' ' && b != b'\t') {
302 return 0;
303 }
304 n
305}
306
307/// Section 4.3: a run of `=` or `-` with only spaces or tabs after it.
308/// Returns the run's character, or `None` when the line is not an
309/// underline.
310pub fn match_setext_heading_line(s: &str) -> Option<u8> {
311 let bytes = s.as_bytes();
312 let &c = bytes.first()?;
313 if c != b'=' && c != b'-' {
314 return None;
315 }
316 let mut i = 0;
317 while i < bytes.len() && bytes[i] == c {
318 i += 1;
319 }
320 if bytes[i..].iter().any(|&b| b != b' ' && b != b'\t') {
321 return None;
322 }
323 Some(c)
324}
325
326// --- HTML blocks (section 4.6) ---------------------------------------------
327//
328// Seven kinds, each with its own start and end condition. Types 1 to 5 end
329// on a line *containing* their closing string (checked in
330// `incorporate_line` after the line is added); types 6 and 7 end at a blank
331// line (checked in the html_block continuation condition). Type 7 alone may
332// not interrupt a paragraph.
333
334/// Tag-shape fragments shared by HTML block type 7 (section 6.6 raw HTML).
335/// The block forms allow only spaces and tabs where the inline forms allow
336/// any whitespace.
337const BLOCK_TAG_NAME: &str = "[A-Za-z][A-Za-z0-9-]*";
338const BLOCK_ATTRIBUTE_NAME: &str = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
339const BLOCK_UNQUOTED_VALUE: &str = "[^\"'=<>`\\x00-\\x20]+";
340const BLOCK_SINGLE_QUOTED_VALUE: &str = "'[^']*'";
341const BLOCK_DOUBLE_QUOTED_VALUE: &str = "\"[^\"]*\"";
342
343/// The type 6 tag list, verbatim from section 4.6 (0.31.2 has `search`,
344/// not `source`).
345const BLOCK_TAGS: &str = "address|article|aside|base|basefont|blockquote|body|caption|\
346center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|\
347figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|\
348li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|\
349section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
350
351/// The type 1 tag list: the four whose content is raw text.
352const BLOCK_RAW_TEXT_TAGS: &str = "script|pre|textarea|style";
353
354/// Spell a lowercase pattern in both cases, mapping each ASCII letter to a
355/// two-element class and passing everything else through (so `h[1-6]`
356/// becomes `[hH][1-6]` and `|` stays an alternation).
357///
358/// This is what the TypeScript's `i` flag means and what a Unicode-aware
359/// `(?i)` does not: the `regex` crate folds case over all of Unicode, so
360/// `(?i)script` also matches `ſcript`, and `(?i)[A-Za-z]` also matches
361/// U+017F LATIN SMALL LETTER LONG S and U+212A KELVIN SIGN, where
362/// JavaScript's non-unicode `i` deliberately never folds a non-ASCII code
363/// point onto an ASCII one.
364fn ascii_fold_pattern(s: &str) -> String {
365 let mut out = String::with_capacity(4 * s.len());
366 for c in s.chars() {
367 if c.is_ascii_lowercase() {
368 out.push('[');
369 out.push(c);
370 out.push(c.to_ascii_uppercase());
371 out.push(']');
372 } else if c.is_ascii_uppercase() {
373 out.push('[');
374 out.push(c.to_ascii_lowercase());
375 out.push(c);
376 out.push(']');
377 } else {
378 out.push(c);
379 }
380 }
381 out
382}
383
384/// Indexed by HTML block type 1 to 7; slot 0 is unused.
385fn re_html_block_open() -> &'static [Regex; 8] {
386 static RE: OnceLock<[Regex; 8]> = OnceLock::new();
387 RE.get_or_init(|| {
388 let attribute_value = format!(
389 "(?:{BLOCK_UNQUOTED_VALUE}|{BLOCK_SINGLE_QUOTED_VALUE}|{BLOCK_DOUBLE_QUOTED_VALUE})"
390 );
391 let attribute_value_spec = format!("(?:[ \\t]*=[ \\t]*{attribute_value})");
392 let attribute = format!("(?:[ \\t]+{BLOCK_ATTRIBUTE_NAME}{attribute_value_spec}?)");
393 let open_tag = format!("<{BLOCK_TAG_NAME}{attribute}*[ \\t]*/?>");
394 let close_tag = format!("</{BLOCK_TAG_NAME}[ \\t]*>");
395 let compile = |p: String| Regex::new(&p).expect("the HTML block patterns compile");
396 [
397 compile("^$".to_string()),
398 compile(format!(
399 "^<(?:{})(?:[ \\t]|>|$)",
400 ascii_fold_pattern(BLOCK_RAW_TEXT_TAGS)
401 )),
402 compile("^<!--".to_string()),
403 compile("^<[?]".to_string()),
404 compile("^<![A-Za-z]".to_string()),
405 compile("^<!\\[CDATA\\[".to_string()),
406 compile(format!(
407 "^</?(?:{})(?:[ \\t]|/?>|$)",
408 ascii_fold_pattern(BLOCK_TAGS)
409 )),
410 compile(format!("^(?:{open_tag}|{close_tag})[ \\t]*$")),
411 ]
412 })
413}
414
415fn re_html_block_close_raw_text() -> &'static Regex {
416 static RE: OnceLock<Regex> = OnceLock::new();
417 RE.get_or_init(|| {
418 Regex::new(&format!(
419 "</(?:{})>",
420 ascii_fold_pattern(BLOCK_RAW_TEXT_TAGS)
421 ))
422 .expect("the raw-text close pattern compiles")
423 })
424}
425
426/// Section 4.6: which of the seven HTML block kinds `s` opens, or 0. The
427/// type-7 paragraph-interrupt restriction is contextual and stays with the
428/// caller.
429pub fn html_block_open_kind(s: &str) -> u8 {
430 let patterns = re_html_block_open();
431 for kind in 1..=7u8 {
432 if patterns[kind as usize].is_match(s) {
433 return kind;
434 }
435 }
436 0
437}
438
439/// Section 4.6: does `s` contain the closing condition for HTML block
440/// `kind` (types 1 to 5; 6 and 7 end at a blank line instead)?
441pub fn html_block_closes(s: &str, kind: u8) -> bool {
442 match kind {
443 1 => re_html_block_close_raw_text().is_match(s),
444 2 => s.contains("-->"),
445 3 => s.contains("?>"),
446 4 => s.contains('>'),
447 5 => s.contains("]]>"),
448 _ => false,
449 }
450}
451
452// --- small lexical helpers --------------------------------------------------
453
454/// The byte at `pos`, or `None` past the end of the line. Every caller
455/// compares against an ASCII constant, which no UTF-8 continuation byte can
456/// equal, so a byte here is as good as the TypeScript's code unit.
457fn peek(ln: &str, pos: usize) -> Option<u8> {
458 ln.as_bytes().get(pos).copied()
459}
460
461fn is_space_or_tab(c: Option<u8>) -> bool {
462 matches!(c, Some(b' ') | Some(b'\t'))
463}
464
465/// The number of characters in `s`. `offset` is a byte index in this port;
466/// sourcepos columns count characters, so the conversion happens here.
467pub fn char_count(s: &str) -> usize {
468 s.chars().count()
469}
470
471/// The index at which the trailing `(\n *)+` of `b` begins, or `b.len()`
472/// when there is none: the offset the JavaScript `.replace(/(\n *)+$/, ..)`
473/// would rewrite from.
474fn trailing_blank_run_start(b: &[u8]) -> usize {
475 let mut end = b.len();
476 loop {
477 let mut j = end;
478 while j > 0 && b[j - 1] == b' ' {
479 j -= 1;
480 }
481 if j > 0 && b[j - 1] == b'\n' {
482 end = j - 1;
483 continue;
484 }
485 return end;
486 }
487}
488
489// --- GFM tables (extension) -------------------------------------------------
490//
491// Everything the extension needs from a line is here: how a row splits into
492// cells, and whether a line is a delimiter row. Both are pure functions of
493// one line of text, which is what lets the block start below stay a few
494// lines long.
495//
496// Byte scanning throughout, as everywhere else in this file: every
497// character these functions test for (space, tab, `|`, `\`, `-`, `:`) is
498// ASCII, and no UTF-8 continuation byte can equal one. The cell text itself
499// is only ever *sliced* at those positions, never decoded character by
500// character, so a multi-byte character inside a cell is carried through
501// whole.
502
503/// The set `cmark_isspace` trims from a table cell: ASCII whitespace only.
504fn is_ascii_space(c: u8) -> bool {
505 c == 32 || (9..=13).contains(&c)
506}
507
508fn trim_ascii_space(s: &str) -> &str {
509 let bytes = s.as_bytes();
510 let mut start = 0;
511 let mut end = bytes.len();
512 while start < end && is_ascii_space(bytes[start]) {
513 start += 1;
514 }
515 while end > start && is_ascii_space(bytes[end - 1]) {
516 end -= 1;
517 }
518 &s[start..end]
519}
520
521/// Split one row of a table into its cell texts.
522///
523/// Cells are separated by *unescaped* pipes; a leading and a trailing pipe
524/// are both optional and may differ from row to row, so they are stripped
525/// before the split rather than producing empty cells at the ends. A
526/// trailing pipe is only a delimiter if it is itself unescaped, which is
527/// why the backslash run before it is counted.
528///
529/// `\|` is resolved to a literal `|` *here*, as the extension requires
530/// ("include a pipe in a cell's content by escaping it, including inside
531/// other inline spans"). Doing it at split time is the whole point: the
532/// inline phase never sees the backslash, so a code span in the cell yields
533/// a real pipe, which no amount of unescaping *after* inline parsing could
534/// produce. Every other backslash escape is left exactly as written for the
535/// inline phase to handle in the usual way, so no cell text is unescaped
536/// twice.
537///
538/// Scanning skips the byte after any backslash, so `\\` cannot shield the
539/// pipe that follows it: `a\\|b` is two cells, the first holding `a\\`.
540///
541/// A row of nothing but whitespace has no cells at all, which is how a
542/// header candidate that is really empty fails the cell-count test instead
543/// of matching a one-column delimiter row.
544pub fn split_table_row(line: &str) -> Vec<String> {
545 let bytes = line.as_bytes();
546 let mut start = 0;
547 let mut end = bytes.len();
548 while start < end && is_ascii_space(bytes[start]) {
549 start += 1;
550 }
551 while end > start && is_ascii_space(bytes[end - 1]) {
552 end -= 1;
553 }
554 if start == end {
555 return Vec::new();
556 }
557
558 // Optional leading pipe.
559 if bytes[start] == b'|' {
560 start += 1;
561 }
562
563 // Optional trailing pipe, but an escaped one is content, not a delimiter.
564 if start < end && bytes[end - 1] == b'|' {
565 let mut bs = end as isize - 2;
566 while bs >= start as isize && bytes[bs as usize] == b'\\' {
567 bs -= 1;
568 }
569 // An even-length backslash run leaves the pipe unescaped.
570 if (end as isize - 2 - bs) % 2 == 0 {
571 end -= 1;
572 }
573 }
574
575 let mut cells = Vec::with_capacity(4);
576 // `cur` holds the parts of the current cell that have already been
577 // rewritten; `seg` is the start of the run since then, so the common
578 // case (no escapes) costs one slice per cell rather than one per byte.
579 let mut cur = String::new();
580 let mut seg = start;
581 let mut i = start;
582
583 while i < end {
584 let c = bytes[i];
585 if c == b'\\' && i + 1 < end {
586 if bytes[i + 1] == b'|' {
587 cur.push_str(&line[seg..i]);
588 cur.push('|');
589 i += 2;
590 seg = i;
591 } else {
592 i += 2;
593 }
594 continue;
595 }
596 if c == b'|' {
597 cur.push_str(&line[seg..i]);
598 cells.push(trim_ascii_space(&cur).to_string());
599 cur.clear();
600 i += 1;
601 seg = i;
602 continue;
603 }
604 i += 1;
605 }
606 cur.push_str(&line[seg..end]);
607 cells.push(trim_ascii_space(&cur).to_string());
608
609 cells
610}
611
612/// A delimiter cell is hyphens with an optional leading and/or trailing
613/// colon, and nothing else. One `+`, one space in the middle, one stray
614/// character and the line is not a delimiter row. Hand-coded from
615/// `/^(:?)-+(:?)$/`.
616fn delimiter_cell_align(cell: &str) -> Option<TableAlign> {
617 let bytes = cell.as_bytes();
618 let mut i = 0;
619 let left = bytes.first() == Some(&b':');
620 if left {
621 i += 1;
622 }
623 let hyphens_start = i;
624 while i < bytes.len() && bytes[i] == b'-' {
625 i += 1;
626 }
627 if i == hyphens_start {
628 return None;
629 }
630 let right = i < bytes.len() && bytes[i] == b':';
631 if right {
632 i += 1;
633 }
634 if i != bytes.len() {
635 return None;
636 }
637 Some(match (left, right) {
638 (true, true) => Some(Align::Center),
639 (true, false) => Some(Align::Left),
640 (false, true) => Some(Align::Right),
641 (false, false) => None,
642 })
643}
644
645/// Read a line as a table's delimiter row, returning one alignment per
646/// column, or `None` if it is not one.
647pub fn parse_delimiter_row(line: &str) -> Option<Vec<TableAlign>> {
648 let cells = split_table_row(line);
649 if cells.is_empty() {
650 return None;
651 }
652 let mut align = Vec::with_capacity(cells.len());
653 for cell in &cells {
654 align.push(delimiter_cell_align(cell)?);
655 }
656 Some(align)
657}
658
659/// Cap on the empty cells inserted to pad short body rows, across a whole
660/// document: cmark-gfm's `MAX_AUTOCOMPLETED_CELLS`, and for the same reason.
661///
662/// Padding is the one place where a table's node count is not bounded by
663/// the size of its source: a 10000-column header followed by 10000 one-cell
664/// rows is 60 KB of input asking for 10^8 cells. Every other part of the
665/// extension is linear in the input, so this single budget is what keeps
666/// the whole of it so. Reaching it needs input that is already
667/// pathological; ordinary tables are nowhere near.
668const MAX_AUTOCOMPLETED_CELLS: usize = 0x80000;
669
670/// The most container blocks (block quotes, lists and list items, each
671/// counted) that may be open at once. A block quote marker or list marker
672/// that would open a deeper one is not a block start, so it is paragraph
673/// text, which is what markdown-it's `maxNesting` does at its limit.
674///
675/// This bound exists for the caller's stack, not the parser's: every
676/// phase here is iterative, but the AST is a `tabnas::Value`, whose
677/// destructor and `to_json` recurse once per nesting level. Unbounded,
678/// a few thousand nested block quotes made an ordinary caller's drop
679/// abort the process. Measured in a debug build on a 2 MiB thread: drop
680/// survives about 5,300 nested levels and `to_json` about 1,250, and
681/// each container is two levels (an object and its children array), so
682/// 100 containers leaves the deepest document well inside both. The
683/// canonical TypeScript has no such limit; `DIVERGENCE.md` records it,
684/// and `tests/robust_test.rs` pins the boundary. The inline phase bounds
685/// its own wrappers the same way: `inline::MAX_INLINE_NESTING`.
686pub const MAX_CONTAINER_NESTING: usize = 100;
687
688/// The blocks `MAX_CONTAINER_NESTING` counts.
689fn is_container(t: NodeType) -> bool {
690 matches!(t, NodeType::BlockQuote | NodeType::List | NodeType::Item)
691}
692
693/// Section 5.3: two markers make the same list only if type, bullet and
694/// delimiter agree.
695fn lists_match(list_data: &ListData, item_data: &ListData) -> bool {
696 list_data.list_type == item_data.list_type
697 && list_data.delimiter == item_data.delimiter
698 && list_data.bullet_char == item_data.bullet_char
699}
700
701/// `continue` result: matched, not matched, or line fully consumed (fenced
702/// code close), stop processing this line entirely.
703#[derive(Debug, Clone, Copy, PartialEq, Eq)]
704enum ContinueResult {
705 Matched,
706 NotMatched,
707 LineDone,
708}
709
710/// A block start's result: no match, a container started, or a leaf
711/// started (stop looking).
712#[derive(Debug, Clone, Copy, PartialEq, Eq)]
713enum StartResult {
714 None,
715 Container,
716 Leaf,
717}
718
719/// The per-type block behaviour the TypeScript keeps in `BLOCK_HANDLERS`:
720/// which children a block may hold, whether it accumulates raw text, and
721/// whether its lines are literal.
722fn can_contain(t: NodeType, child: NodeType) -> bool {
723 match t {
724 NodeType::Document | NodeType::BlockQuote | NodeType::Item => child != NodeType::Item,
725 NodeType::List => child == NodeType::Item,
726 NodeType::Table => child == NodeType::TableRow,
727 NodeType::TableRow => child == NodeType::TableCell,
728 _ => false,
729 }
730}
731
732/// Leaves that accumulate raw text: code blocks, HTML blocks, paragraphs,
733/// tables.
734fn accepts_lines(t: NodeType) -> bool {
735 matches!(
736 t,
737 NodeType::CodeBlock | NodeType::HtmlBlock | NodeType::Paragraph | NodeType::Table
738 )
739}
740
741/// Lines belonging to this block are literal text, so Appendix A step 2
742/// does not look for block starts while it is the last matched container.
743///
744/// True for exactly the two blocks the spec names: code blocks and HTML
745/// blocks. Paragraphs and GFM tables also accept lines, but a block start
746/// may still interrupt either: that is how `> bar` ends a table, and how
747/// `# h` ends a paragraph.
748fn verbatim(t: NodeType) -> bool {
749 matches!(t, NodeType::CodeBlock | NodeType::HtmlBlock)
750}
751
752/// The block-phase parser: the open spine, the current line, and the
753/// tree being built.
754pub struct BlockParser {
755 pub options: Options,
756 pub refmap: RefMap,
757
758 pub tree: Tree,
759 doc: NodeId,
760 /// The deepest open block; `None` only once the document itself is
761 /// finalized.
762 tip: Option<NodeId>,
763 /// The tip as it was before the current line was walked.
764 oldtip: NodeId,
765 last_matched_container: NodeId,
766 /// False while some open block failed its continuation condition.
767 all_closed: bool,
768
769 current_line: String,
770 line_number: usize,
771 last_line_length: usize,
772
773 /// The GFM table probe gate. True by default: the batch driver probes
774 /// every candidate line, as it always has. The engine driver sets it
775 /// per line from the `#LB` token's `tblArm` bit (a provable superset of
776 /// "could be a delimiter row"; see `engine_block.rs`), which is what
777 /// lets the GFM alt be a genuine, subtractable extension seam without
778 /// moving any table decision out of this file.
779 pub table_armed: bool,
780
781 /// The length of the line before the one `last_line_length` measures.
782 ///
783 /// `finalize` dates a block's end from `last_line_length`, which is
784 /// right for every block that ends on the line before the current one.
785 /// A GFM table splits its paragraph *two* lines back (the header row is
786 /// the previous line and stays with the table, so the paragraph left
787 /// behind ends on the line before that) and needs this one instead.
788 prev_line_length: usize,
789
790 /// A byte index into `current_line`.
791 offset: usize,
792 /// The tab-expanded display column matching `offset` (section 2.2),
793 /// counted in characters.
794 column: usize,
795 /// True when `offset` sits inside a tab whose columns were partly
796 /// consumed.
797 partially_consumed_tab: bool,
798
799 /// Memoize the last byte offset in `current_line` whose character count
800 /// is known, so sourcepos columns cost amortized O(1) rather than a
801 /// fresh count from the start of the line. Both reset per line. See
802 /// `source_column`.
803 col_anchor_offset: usize,
804 col_anchor_chars: usize,
805
806 next_nonspace: usize,
807 next_nonspace_column: usize,
808 /// Columns between `column` and the next non-space character.
809 indent: usize,
810 indented: bool,
811 blank: bool,
812
813 /// Empty cells inserted so far to pad short table rows. See
814 /// `MAX_AUTOCOMPLETED_CELLS`.
815 autocompleted_cells: usize,
816
817 /// The text `add_line` last appended, the column it started in, and the
818 /// block it went to.
819 ///
820 /// `try_open_table` needs the *last line* of an open paragraph, and
821 /// reading it back out of `string_content` is not affordable in the
822 /// canonical runtime: that content is built by repeated `+=`, so every
823 /// index into it flattens a fresh rope. The field is carried across
824 /// anyway: it is what makes the three runtimes the same function, and
825 /// scanning back for the previous newline is its own O(n) per line.
826 ///
827 /// The node is recorded alongside it because "the previous line went to
828 /// this very paragraph" is the extension's own rule: a header row is by
829 /// definition the line immediately above the delimiter row. If some
830 /// other block took that line, there is no header row.
831 ///
832 /// The column is what a table's sourcepos starts at: a table opens on
833 /// its header row, which is a line already consumed by the time the
834 /// delimiter row identifies it, so its column has to have been recorded
835 /// when it went past.
836 last_added_line: String,
837 last_added_column: usize,
838 last_added_to: Option<NodeId>,
839
840 /// Step 2's fast reject, widened for a table's delimiter row when GFM is
841 /// on.
842 gfm_special: bool,
843
844 /// `MdNode` has no field for the HTML block type, and the tree contract
845 /// is not ours to change, so open HTML blocks carry it here.
846 html_block_types: HashMap<NodeId, u8>,
847}
848
849impl BlockParser {
850 pub fn new(options: Options) -> Self {
851 let mut tree = Tree::new(NodeType::Document);
852 let doc = tree.root();
853 tree.get_mut(doc).sourcepos = [[1, 1], [0, 0]];
854 BlockParser {
855 options,
856 refmap: RefMap::new(),
857 tree,
858 doc,
859 tip: Some(doc),
860 oldtip: doc,
861 last_matched_container: doc,
862 all_closed: true,
863 current_line: String::new(),
864 line_number: 0,
865 last_line_length: 0,
866 table_armed: true,
867 prev_line_length: 0,
868 offset: 0,
869 column: 0,
870 partially_consumed_tab: false,
871 col_anchor_offset: 0,
872 col_anchor_chars: 0,
873 next_nonspace: 0,
874 next_nonspace_column: 0,
875 indent: 0,
876 indented: false,
877 blank: false,
878 autocompleted_cells: 0,
879 last_added_line: String::new(),
880 last_added_column: 1,
881 last_added_to: None,
882 gfm_special: options.gfm,
883 html_block_types: HashMap::new(),
884 }
885 }
886
887 /// The deepest open block. Only meaningful while a line is being
888 /// processed. The TypeScript throws when the tip is null; a missing tip
889 /// means the document itself has been closed, which cannot happen
890 /// mid-line, and this port must not panic on any input, so the document
891 /// stands in.
892 fn open_tip(&self) -> NodeId {
893 self.tip.unwrap_or(self.doc)
894 }
895
896 fn html_block_type(&self, block: NodeId) -> u8 {
897 self.html_block_types.get(&block).copied().unwrap_or(0)
898 }
899
900 fn set_html_block_type(&mut self, block: NodeId, kind: u8) {
901 self.html_block_types.insert(block, kind);
902 }
903
904 fn node_type(&self, id: NodeId) -> NodeType {
905 self.tree.get(id).node_type
906 }
907
908 /// Advance `count` characters (`columns` false) or `count` columns
909 /// (`columns` true), expanding tabs to the next 4-column tab stop
910 /// (section 2.2). A tab whose columns are only partly consumed leaves
911 /// `offset` on the tab itself and sets `partially_consumed_tab`, so
912 /// `add_line` can re-emit the remainder as spaces.
913 fn advance_offset(&mut self, mut count: usize, columns: bool) {
914 let bytes = self.current_line.as_bytes();
915 while count > 0 && self.offset < bytes.len() {
916 if bytes[self.offset] == b'\t' {
917 let chars_to_tab = 4 - (self.column % 4);
918 if columns {
919 self.partially_consumed_tab = chars_to_tab > count;
920 let chars_to_advance = chars_to_tab.min(count);
921 self.column += chars_to_advance;
922 if !self.partially_consumed_tab {
923 self.offset += 1;
924 }
925 count -= chars_to_advance;
926 } else {
927 self.partially_consumed_tab = false;
928 self.column += chars_to_tab;
929 self.offset += 1;
930 count -= 1;
931 }
932 } else {
933 self.partially_consumed_tab = false;
934 // One character, not one byte: offset is a byte index but
935 // column counts characters. Block markers are all ASCII, so
936 // the two only part company on the advance-to-end-of-line
937 // calls.
938 let size = self.current_line[self.offset..]
939 .chars()
940 .next()
941 .map_or(1, char::len_utf8);
942 self.offset += size;
943 self.column += 1;
944 count -= 1;
945 }
946 }
947 }
948
949 fn advance_next_nonspace(&mut self) {
950 self.offset = self.next_nonspace;
951 self.column = self.next_nonspace_column;
952 self.partially_consumed_tab = false;
953 }
954
955 /// Locate the next non-space character and the indent leading up to
956 /// it.
957 fn find_next_nonspace(&mut self) {
958 let bytes = self.current_line.as_bytes();
959 let mut i = self.offset;
960 let mut cols = self.column;
961
962 while i < bytes.len() {
963 if bytes[i] == b' ' {
964 i += 1;
965 cols += 1;
966 } else if bytes[i] == b'\t' {
967 i += 1;
968 cols += 4 - (cols % 4);
969 } else {
970 break;
971 }
972 }
973
974 self.blank = i >= bytes.len() || bytes[i] == b'\n' || bytes[i] == b'\r';
975 self.next_nonspace = i;
976 self.next_nonspace_column = cols;
977 self.indent = self.next_nonspace_column - self.column;
978 self.indented = self.indent >= CODE_INDENT;
979 }
980
981 /// The number of characters of `current_line` before byte `offset`:
982 /// what a sourcepos column needs.
983 ///
984 /// Counted incrementally from the last offset already measured.
985 /// `add_child` runs once per container opened, so counting from the
986 /// start of the line every time would make a line of n nested
987 /// containers (`> - > - ...`) cost O(n^2); untrusted input picks n.
988 /// Offsets advance monotonically as a line is consumed, making this
989 /// amortized O(1); a smaller offset than the anchor is still correct,
990 /// just recounted from the start.
991 fn source_column(&mut self, offset: usize) -> usize {
992 if offset < self.col_anchor_offset {
993 self.col_anchor_offset = 0;
994 self.col_anchor_chars = 0;
995 }
996 self.col_anchor_chars += char_count(&self.current_line[self.col_anchor_offset..offset]);
997 self.col_anchor_offset = offset;
998 self.col_anchor_chars
999 }
1000
1001 /// Add the rest of the current line to the tip's raw content.
1002 fn add_line(&mut self) {
1003 let tip = self.open_tip();
1004 // Taken before the tab fixup below moves `offset`, so a line's
1005 // recorded column is the one `add_child` would report for that
1006 // same position.
1007 let column = self.source_column(self.offset) + 1; // offset 0 is column 1
1008 let text = if self.partially_consumed_tab {
1009 self.offset += 1; // step over the tab
1010 let chars_to_tab = 4 - (self.column % 4);
1011 let mut text = " ".repeat(chars_to_tab);
1012 text.push_str(&self.current_line[self.offset..]);
1013 text
1014 } else {
1015 self.current_line[self.offset..].to_string()
1016 };
1017 let node = self.tree.get_mut(tip);
1018 node.string_content.push_str(&text);
1019 node.string_content.push('\n');
1020 self.last_added_line = text;
1021 self.last_added_column = column;
1022 self.last_added_to = Some(tip);
1023 }
1024
1025 /// How many container blocks the spine holds from the document down
1026 /// to `id`, `id` included.
1027 fn container_depth(&self, id: NodeId) -> usize {
1028 let mut depth = 0;
1029 let mut cur = Some(id);
1030 while let Some(n) = cur {
1031 if is_container(self.node_type(n)) {
1032 depth += 1;
1033 }
1034 cur = self.tree.get(n).parent;
1035 }
1036 depth
1037 }
1038
1039 /// The container depth a new block of `tag` would open at under `tip`.
1040 /// `add_child` closes the blocks that cannot hold it first, so the
1041 /// holder is the nearest of `tip` and its ancestors that can (or the
1042 /// document), and the new block is one deeper than that. The walk is
1043 /// bounded by `MAX_CONTAINER_NESTING` itself, since the spine never
1044 /// holds more containers than that.
1045 fn depth_of_new(&self, tip: NodeId, tag: NodeType) -> usize {
1046 let mut holder = tip;
1047 while holder != self.doc && !can_contain(self.node_type(holder), tag) {
1048 holder = self
1049 .tree
1050 .get(holder)
1051 .parent
1052 .expect("every block below the document has a parent");
1053 }
1054 self.container_depth(holder) + 1
1055 }
1056
1057 /// Open a block of `tag` as a child of the tip, closing blocks that
1058 /// cannot contain it first.
1059 fn add_child(&mut self, tag: NodeType, offset: usize) -> NodeId {
1060 // The document accepts everything but an item, and the list-item
1061 // start always opens a list first, so this terminates at the
1062 // document at the latest. Stopping there rather than closing the
1063 // document keeps the parser total where the TypeScript would throw
1064 // on the next `openTip`.
1065 loop {
1066 let tip = self.open_tip();
1067 if tip == self.doc || can_contain(self.node_type(tip), tag) {
1068 break;
1069 }
1070 self.finalize(tip, self.line_number - 1);
1071 }
1072
1073 let column_number = self.source_column(offset) + 1; // offset 0 is column 1
1074 let mut node = MdNode::new(tag);
1075 node.sourcepos = [[self.line_number, column_number], [0, 0]];
1076 let id = self.tree.add(node);
1077 let tip = self.open_tip();
1078 self.tree.append_child(tip, id);
1079 self.tip = Some(id);
1080 id
1081 }
1082
1083 /// The GFM tables block start: read the current line as the delimiter
1084 /// row of a table whose header row is the last line of the open
1085 /// paragraph `container`.
1086 ///
1087 /// The two rows must agree on the number of cells; if they do not,
1088 /// there is no table and the line is nothing special (spec example 6
1089 /// keeps the whole thing a paragraph). The header row is the paragraph's
1090 /// **last** line only, so a paragraph that had earlier lines is split:
1091 /// those lines stay a paragraph, finalized here, which is what still
1092 /// lets them contribute link reference definitions, and the table is
1093 /// opened after it.
1094 ///
1095 /// On success the table is the tip and the caller returns "leaf
1096 /// started", so step 3 adds the delimiter row itself to the table's raw
1097 /// content. It is skipped again by `finalize_table`; keeping it costs
1098 /// nothing and makes the table's accumulated lines line up one-for-one
1099 /// with the source lines.
1100 fn try_open_table(&mut self, container: NodeId) -> bool {
1101 if !self.table_armed {
1102 return false;
1103 }
1104 if !self.options.gfm || self.indented || self.node_type(container) != NodeType::Paragraph {
1105 return false;
1106 }
1107
1108 let Some(align) = parse_delimiter_row(&self.current_line[self.next_nonspace..]) else {
1109 return false;
1110 };
1111
1112 // The header row is the line directly above, which is the line
1113 // `add_line` last wrote: to this paragraph, or there is no header
1114 // row at all.
1115 if self.last_added_to != Some(container) {
1116 return false;
1117 }
1118 let header_cells = split_table_row(&self.last_added_line);
1119 if header_cells.len() != align.len() {
1120 return false;
1121 }
1122
1123 self.close_unmatched_blocks();
1124
1125 let header_line = self.line_number - 1;
1126 let header_column = self.last_added_column;
1127 // `string_content` ends with that same line plus the newline
1128 // `add_line` put after it, so the header row starts this far in: no
1129 // scan needed, and the content is only ever touched on the split
1130 // branch, at most once per table.
1131 let content_len = self.tree.get(container).string_content.len();
1132 let header_start = content_len as isize - self.last_added_line.len() as isize - 1;
1133 if header_start > 0 {
1134 // Split: everything above the header row stays a paragraph. It
1135 // ends two lines back, not one, so `finalize`'s default end
1136 // column (the previous line's, which here is the header row's)
1137 // would be somebody else's.
1138 self.tree
1139 .get_mut(container)
1140 .string_content
1141 .truncate(header_start as usize);
1142 let end_column = self.prev_line_length;
1143 self.finalize_at(container, header_line - 1, end_column);
1144 } else {
1145 let parent = self.tree.get(container).parent;
1146 self.tree.unlink(container);
1147 self.tip = parent;
1148 }
1149
1150 let table = self.add_child(NodeType::Table, self.next_nonspace);
1151 // `add_child` both dated and placed the table from the delimiter
1152 // row, and neither belongs to it: the table begins on the header
1153 // row, one line above, in the column where *that* row's content
1154 // starts. The two rows are indented independently, so the delimiter
1155 // row's column is simply somebody else's: ` a | b` over `| - | -`
1156 // starts in column 3, and `a | b` over ` | - | -` starts in column
1157 // 1.
1158 {
1159 let node = self.tree.get_mut(table);
1160 node.sourcepos[0][0] = header_line;
1161 node.sourcepos[0][1] = header_column;
1162 node.table_align = Some(align);
1163 }
1164
1165 // The row is measured over its own text, exactly as `finalize_table`
1166 // measures the body rows: `last_line_length` counts the whole source
1167 // line, container markers included, so inside a block quote it would
1168 // end the header row two columns past where every body row of the
1169 // same table ends.
1170 let end_column = char_count(&self.last_added_line);
1171 self.add_table_row(table, &header_cells, true, header_line, end_column);
1172 true
1173 }
1174
1175 /// Append one row of `cells` to `table`, padded with empty cells or
1176 /// truncated so that it is exactly as wide as the delimiter row said.
1177 ///
1178 /// Rows and cells are built closed: they are not part of the open
1179 /// spine, and the line walk in `incorporate_line` must stop at the
1180 /// table itself.
1181 fn add_table_row(
1182 &mut self,
1183 table: NodeId,
1184 cells: &[String],
1185 is_header: bool,
1186 line_number: usize,
1187 end_column: usize,
1188 ) {
1189 let width = self
1190 .tree
1191 .get(table)
1192 .table_align
1193 .as_ref()
1194 .map_or(0, Vec::len);
1195
1196 // See MAX_AUTOCOMPLETED_CELLS: padding is the only unbounded part of
1197 // a table.
1198 let mut limit = width;
1199 if cells.len() < width {
1200 let budget = MAX_AUTOCOMPLETED_CELLS.saturating_sub(self.autocompleted_cells);
1201 let padding = width - cells.len();
1202 if padding > budget {
1203 limit = cells.len() + budget;
1204 }
1205 self.autocompleted_cells += limit - cells.len();
1206 }
1207
1208 // A row and its cells occupy one source line. Columns within that
1209 // line are not tracked: nothing reads them (the AST drops sourcepos
1210 // and the renderer ignores it), and threading offsets through the
1211 // cell split to invent them would be cost with no reader.
1212 let span: SourcePos = [[line_number, 1], [line_number, end_column]];
1213
1214 let mut row = MdNode::new(NodeType::TableRow);
1215 row.sourcepos = span;
1216 row.is_header_row = is_header;
1217 row.open = false;
1218 let row = self.tree.add(row);
1219 self.tree.append_child(table, row);
1220
1221 for i in 0..limit {
1222 let mut cell = MdNode::new(NodeType::TableCell);
1223 cell.sourcepos = span;
1224 cell.open = false;
1225 // Consumed by the inline phase, exactly as a paragraph's content
1226 // is.
1227 if i < cells.len() {
1228 cell.string_content = cells[i].clone();
1229 }
1230 let cell = self.tree.add(cell);
1231 self.tree.append_child(row, cell);
1232 }
1233 }
1234
1235 /// Close a table: turn the raw lines it accumulated into body rows.
1236 ///
1237 /// The first accumulated line is the delimiter row that opened the
1238 /// table. It carries no data (its alignments are already on the node)
1239 /// so it is skipped here, which is also what keeps the source line
1240 /// numbering of the rows below it straightforward: the table accepts
1241 /// exactly one line per source line, and a blank line closes it, so
1242 /// there are no gaps.
1243 fn finalize_table(&mut self, table: NodeId) {
1244 let content = std::mem::take(&mut self.tree.get_mut(table).string_content);
1245 let header_line = self.tree.get(table).sourcepos[0][0];
1246
1247 // Line 0 is the delimiter row; the last element is the empty string
1248 // after the final newline.
1249 for (i, line) in content.split('\n').enumerate() {
1250 if i == 0 || line.is_empty() {
1251 continue;
1252 }
1253 let cells = split_table_row(line);
1254 self.add_table_row(table, &cells, false, header_line + i + 1, char_count(line));
1255 }
1256 }
1257
1258 /// Close every block that failed its continuation condition on this
1259 /// line.
1260 fn close_unmatched_blocks(&mut self) {
1261 if self.all_closed {
1262 return;
1263 }
1264 while self.oldtip != self.last_matched_container {
1265 let parent = self.tree.get(self.oldtip).parent;
1266 self.finalize(self.oldtip, self.line_number - 1);
1267 match parent {
1268 Some(p) => self.oldtip = p,
1269 None => break,
1270 }
1271 }
1272 self.all_closed = true;
1273 }
1274
1275 /// Close a block, record its end position, and run its finalizer. The
1276 /// end column is the previous line's length, which is where every block
1277 /// that ends on `line_number` ends.
1278 fn finalize(&mut self, block: NodeId, line_number: usize) {
1279 self.finalize_at(block, line_number, self.last_line_length);
1280 }
1281
1282 /// `finalize` with the end column given rather than assumed. Only a
1283 /// table's paragraph split needs it: that one closes a block two lines
1284 /// back, where `finalize`'s default is one line too recent.
1285 fn finalize_at(&mut self, block: NodeId, line_number: usize, end_column: usize) {
1286 let above = self.tree.get(block).parent;
1287 {
1288 let node = self.tree.get_mut(block);
1289 node.open = false;
1290 node.sourcepos[1] = [line_number, end_column];
1291 }
1292 self.finalize_block(block);
1293 self.html_block_types.remove(&block);
1294 self.tip = above;
1295 }
1296
1297 /// `block.listData.tight = false` on a list, as the other runtimes see
1298 /// it. In TypeScript the list and the item that opened it hold the SAME
1299 /// `listData` object (`addChild('list').listData = data` and then
1300 /// `addChild('item').listData = data`), and Go shares the pointer the
1301 /// same way, so loosening the list also loosens that first item's
1302 /// `listData`. Here `list_data` is an owned value on each node, so the
1303 /// aliasing has to be spelled out: the native tree (and its goldens)
1304 /// carry the item's `tight`, and the projection and the renderer read
1305 /// only the list's. Later items keep their own `tight: true`, in every
1306 /// runtime.
1307 fn mark_list_loose(&mut self, list: NodeId) {
1308 if let Some(data) = self.tree.get_mut(list).list_data.as_mut() {
1309 data.tight = false;
1310 }
1311 if let Some(first) = self.tree.get(list).first_child {
1312 if let Some(data) = self.tree.get_mut(first).list_data.as_mut() {
1313 data.tight = false;
1314 }
1315 }
1316 }
1317
1318 /// The per-type finalizer the TypeScript keeps in `BLOCK_HANDLERS`.
1319 fn finalize_block(&mut self, block: NodeId) {
1320 match self.node_type(block) {
1321 NodeType::List => {
1322 // Section 5.3: the list is loose if any item is followed by
1323 // a blank line, or if any item directly contains two blocks
1324 // separated by one. A blank line at the very end of the
1325 // last item does not count, hence the `next` guards.
1326 let mut item = self.tree.get(block).first_child;
1327 'items: while let Some(it) = item {
1328 let item_next = self.tree.get(it).next;
1329 if self.ends_with_blank_line(it) && item_next.is_some() {
1330 self.mark_list_loose(block);
1331 break;
1332 }
1333 let mut subitem = self.tree.get(it).first_child;
1334 while let Some(sub) = subitem {
1335 let sub_next = self.tree.get(sub).next;
1336 if self.ends_with_blank_line(sub)
1337 && (item_next.is_some() || sub_next.is_some())
1338 {
1339 self.mark_list_loose(block);
1340 break 'items;
1341 }
1342 subitem = sub_next;
1343 }
1344 item = item_next;
1345 }
1346 if let Some(last) = self.tree.get(block).last_child {
1347 let end = self.tree.get(last).sourcepos[1];
1348 self.tree.get_mut(block).sourcepos[1] = end;
1349 }
1350 }
1351
1352 NodeType::Item => {
1353 let node = self.tree.get(block);
1354 if let Some(last) = node.last_child {
1355 let end = self.tree.get(last).sourcepos[1];
1356 self.tree.get_mut(block).sourcepos[1] = end;
1357 } else if let Some(data) = &node.list_data {
1358 let end = [node.sourcepos[0][0], data.marker_offset + data.padding];
1359 self.tree.get_mut(block).sourcepos[1] = end;
1360 }
1361 }
1362
1363 NodeType::CodeBlock => {
1364 let node = self.tree.get_mut(block);
1365 if node.is_fenced {
1366 // The first accumulated line is the info string, not
1367 // content.
1368 let content = std::mem::take(&mut node.string_content);
1369 match content.find('\n') {
1370 Some(nl) => {
1371 node.info = Some(unescape_string(js_trim(&content[..nl])));
1372 node.literal = content[nl + 1..].to_string();
1373 }
1374 None => {
1375 node.info = Some(unescape_string(js_trim(&content)));
1376 node.literal = String::new();
1377 }
1378 }
1379 } else {
1380 // Section 4.4: trailing blank lines are not part of an
1381 // indented code block. This is `.replace(/(\n *)+$/, '\n')`.
1382 let content = std::mem::take(&mut node.string_content);
1383 let start = trailing_blank_run_start(content.as_bytes());
1384 if start < content.len() {
1385 node.literal = format!("{}\n", &content[..start]);
1386 } else {
1387 node.literal = content;
1388 }
1389 }
1390 }
1391
1392 NodeType::HtmlBlock => {
1393 // `.replace(/(\n *)+$/, '')`
1394 let node = self.tree.get_mut(block);
1395 let content = std::mem::take(&mut node.string_content);
1396 let start = trailing_blank_run_start(content.as_bytes());
1397 node.literal = content[..start].to_string();
1398 }
1399
1400 NodeType::Paragraph => {
1401 // Section 4.7: a paragraph may begin with link reference
1402 // definitions. Consume them from the front; if nothing is
1403 // left, the paragraph disappears.
1404 if self.consume_reference_defs(block)
1405 && is_blank(&self.tree.get(block).string_content)
1406 {
1407 self.tree.unlink(block);
1408 }
1409 }
1410
1411 // GFM tables. The header row is built when the table opens (see
1412 // `try_open_table`); every later line is accumulated raw and
1413 // split into a body row at finalize, so the table behaves like a
1414 // paragraph that happens to print as a grid: it ends at a blank
1415 // line, and any block start interrupts it, because it is not
1416 // verbatim and `can_contain` refuses everything the block starts
1417 // can open.
1418 NodeType::Table => self.finalize_table(block),
1419
1420 _ => {}
1421 }
1422 }
1423
1424 /// Section 5.3 looseness input: does this block end with a blank line?
1425 /// For lists and items the question recurses into the last child, since
1426 /// the blank line is recorded on the deepest block that saw it. The
1427 /// `last_line_checked` flag makes the recursion linear over the whole
1428 /// document rather than quadratic.
1429 fn ends_with_blank_line(&mut self, block: NodeId) -> bool {
1430 let mut cur = Some(block);
1431 while let Some(id) = cur {
1432 let node = self.tree.get_mut(id);
1433 if node.last_line_blank {
1434 return true;
1435 }
1436 let t = node.node_type;
1437 if !node.last_line_checked && (t == NodeType::List || t == NodeType::Item) {
1438 node.last_line_checked = true;
1439 cur = node.last_child;
1440 } else {
1441 node.last_line_checked = true;
1442 return false;
1443 }
1444 }
1445 false
1446 }
1447
1448 /// Strip leading link reference definitions (section 4.7) from a
1449 /// block's raw content, adding each to the refmap, and report whether
1450 /// any were consumed.
1451 fn consume_reference_defs(&mut self, block: NodeId) -> bool {
1452 let content = std::mem::take(&mut self.tree.get_mut(block).string_content);
1453 let consumed = parse_references(&content, &mut self.refmap);
1454 let node = self.tree.get_mut(block);
1455 if consumed == 0 {
1456 node.string_content = content;
1457 return false;
1458 }
1459 node.string_content = content[consumed..].to_string();
1460 true
1461 }
1462
1463 /// Can `container` absorb the current line?
1464 fn continue_block(&mut self, container: NodeId) -> ContinueResult {
1465 match self.node_type(container) {
1466 NodeType::Document | NodeType::List => ContinueResult::Matched,
1467
1468 NodeType::BlockQuote => {
1469 if !self.indented && peek(&self.current_line, self.next_nonspace) == Some(b'>') {
1470 self.advance_next_nonspace();
1471 self.advance_offset(1, false);
1472 // Section 5.1: one optional space of indentation after
1473 // `>`, tab-aware.
1474 if is_space_or_tab(peek(&self.current_line, self.offset)) {
1475 self.advance_offset(1, true);
1476 }
1477 return ContinueResult::Matched;
1478 }
1479 ContinueResult::NotMatched
1480 }
1481
1482 NodeType::Item => {
1483 let (marker_offset, padding, first_child) = {
1484 let node = self.tree.get(container);
1485 let Some(data) = &node.list_data else {
1486 return ContinueResult::NotMatched;
1487 };
1488 (data.marker_offset, data.padding, node.first_child)
1489 };
1490
1491 if self.blank {
1492 // An item whose first line is blank cannot be continued
1493 // by a second blank line (section 5.2 rule 3: at most
1494 // one leading blank line).
1495 if first_child.is_none() {
1496 return ContinueResult::NotMatched;
1497 }
1498 self.advance_next_nonspace();
1499 return ContinueResult::Matched;
1500 }
1501
1502 // Section 5.2: subsequent lines belong to the item if
1503 // indented to the content column derived from the marker.
1504 if self.indent >= marker_offset + padding {
1505 self.advance_offset(marker_offset + padding, true);
1506 return ContinueResult::Matched;
1507 }
1508 ContinueResult::NotMatched
1509 }
1510
1511 // A heading is always exactly one line (setext headings are
1512 // converted from an already-complete paragraph).
1513 NodeType::Heading | NodeType::ThematicBreak => ContinueResult::NotMatched,
1514
1515 NodeType::CodeBlock => {
1516 let indent = self.indent;
1517 let (is_fenced, fence_char, fence_length, fence_offset) = {
1518 let node = self.tree.get(container);
1519 (
1520 node.is_fenced,
1521 node.fence_char,
1522 node.fence_length,
1523 node.fence_offset,
1524 )
1525 };
1526
1527 if is_fenced {
1528 // Section 4.5: the closing fence is the same character,
1529 // at least as long, at most 3 columns indented, and
1530 // followed only by spaces or tabs.
1531 let mut match_len = 0;
1532 if indent <= 3
1533 && peek(&self.current_line, self.next_nonspace) == Some(fence_char)
1534 {
1535 match_len =
1536 match_closing_code_fence(&self.current_line[self.next_nonspace..]);
1537 }
1538 if match_len > 0 && match_len >= fence_length {
1539 self.last_line_length =
1540 char_count(&self.current_line[..self.offset]) + indent + match_len;
1541 self.finalize(container, self.line_number);
1542 return ContinueResult::LineDone;
1543 }
1544 // Content is de-indented by up to the opening fence's own
1545 // indent.
1546 let mut i = fence_offset;
1547 while i > 0 && is_space_or_tab(peek(&self.current_line, self.offset)) {
1548 self.advance_offset(1, true);
1549 i -= 1;
1550 }
1551 return ContinueResult::Matched;
1552 }
1553
1554 // Section 4.4 indented code: four columns, or a blank line
1555 // (which is kept).
1556 if indent >= CODE_INDENT {
1557 self.advance_offset(CODE_INDENT, true);
1558 return ContinueResult::Matched;
1559 }
1560 if self.blank {
1561 self.advance_next_nonspace();
1562 return ContinueResult::Matched;
1563 }
1564 ContinueResult::NotMatched
1565 }
1566
1567 NodeType::HtmlBlock => {
1568 // Types 6 and 7 end at a blank line; 1 to 5 end on their
1569 // closing string, which `incorporate_line` checks after
1570 // adding the line.
1571 let kind = self.html_block_type(container);
1572 if self.blank && (kind == 6 || kind == 7) {
1573 return ContinueResult::NotMatched;
1574 }
1575 ContinueResult::Matched
1576 }
1577
1578 NodeType::Paragraph | NodeType::Table => {
1579 if self.blank {
1580 ContinueResult::NotMatched
1581 } else {
1582 ContinueResult::Matched
1583 }
1584 }
1585
1586 // Rows and cells are created closed, and are never the parser's
1587 // tip, so nothing here is reached in a normal parse. An inert
1588 // leaf is the safe reading: no continuation, no children, no
1589 // lines.
1590 _ => ContinueResult::NotMatched,
1591 }
1592 }
1593
1594 /// Parse a list marker at `next_nonspace` and derive the item's
1595 /// content indent.
1596 ///
1597 /// The content indent is marker width + the spaces that follow it,
1598 /// with two exceptions that both fall back to marker width + 1:
1599 ///
1600 /// - rule 2, item starting with indented code: 5+ spaces after the
1601 /// marker means only the first space belongs to the marker, the rest
1602 /// is code;
1603 /// - rule 3, item starting with a blank line: nothing follows the
1604 /// marker at all, so there are no spaces to measure.
1605 ///
1606 /// Returns `None` when this is not a list item start. Advances the
1607 /// parser to the item's content column when it is.
1608 fn parse_list_marker(&mut self, container: NodeId) -> Option<ListData> {
1609 // Four columns of indentation is indented code, never a list marker.
1610 if self.indent >= CODE_INDENT {
1611 return None;
1612 }
1613
1614 let container_is_paragraph = self.node_type(container) == NodeType::Paragraph;
1615 let rest = &self.current_line[self.next_nonspace..];
1616
1617 let mut data = ListData {
1618 list_type: ListType::Bullet,
1619 tight: true, // lists are tight until finalize proves otherwise
1620 start: 1,
1621 delimiter: String::new(),
1622 bullet_char: String::new(),
1623 padding: 0,
1624 marker_offset: self.indent,
1625 };
1626
1627 let marker_len;
1628 if is_bullet_list_marker(rest) {
1629 data.list_type = ListType::Bullet;
1630 data.bullet_char = rest[..1].to_string();
1631 marker_len = 1;
1632 } else {
1633 let (digits, delimiter) = match_ordered_list_marker(rest)?;
1634 // At most nine digits, which always fit.
1635 let start: i64 = rest[..digits].parse().ok()?;
1636 // Section 5.2 exception 1(b): an ordered item interrupting a
1637 // paragraph must start at 1.
1638 if container_is_paragraph && start != 1 {
1639 return None;
1640 }
1641 data.list_type = ListType::Ordered;
1642 data.start = start;
1643 data.delimiter = (delimiter as char).to_string();
1644 marker_len = digits + 1;
1645 }
1646
1647 // At least one space or tab (or the end of the line) must follow the
1648 // marker.
1649 let nextc = peek(&self.current_line, self.next_nonspace + marker_len);
1650 if !(nextc.is_none() || nextc == Some(b'\t') || nextc == Some(b' ')) {
1651 return None;
1652 }
1653
1654 // Section 5.2 exception 1(a): an item interrupting a paragraph may
1655 // not start blank.
1656 if container_is_paragraph && is_blank(&self.current_line[self.next_nonspace + marker_len..])
1657 {
1658 return None;
1659 }
1660
1661 self.advance_next_nonspace(); // to the marker
1662 self.advance_offset(marker_len, true); // past the marker
1663
1664 let spaces_start_col = self.column;
1665 let spaces_start_offset = self.offset;
1666 loop {
1667 self.advance_offset(1, true);
1668 let nextc = peek(&self.current_line, self.offset);
1669 if !(self.column - spaces_start_col < 5 && is_space_or_tab(nextc)) {
1670 break;
1671 }
1672 }
1673
1674 let blank_item = peek(&self.current_line, self.offset).is_none();
1675 let spaces_after_marker = self.column - spaces_start_col;
1676
1677 if !(1..5).contains(&spaces_after_marker) || blank_item {
1678 data.padding = marker_len + 1;
1679 self.column = spaces_start_col;
1680 self.offset = spaces_start_offset;
1681 if is_space_or_tab(peek(&self.current_line, self.offset)) {
1682 self.advance_offset(1, true);
1683 }
1684 } else {
1685 data.padding = marker_len + spaces_after_marker;
1686 }
1687
1688 Some(data)
1689 }
1690
1691 /// The block starts, tried in order, and the order is the spec's: a
1692 /// setext underline beats a thematic break (so `Foo\n---` is a
1693 /// heading), a thematic break beats a list item (so `- - -` is a
1694 /// break), and indented code comes last because any of the others may
1695 /// be indented up to three columns. The GFM table start is last of all;
1696 /// see `try_open_table`.
1697 fn block_start(&mut self, index: usize, container: NodeId) -> StartResult {
1698 match index {
1699 // Block quote (section 5.1).
1700 0 => {
1701 if !self.indented && peek(&self.current_line, self.next_nonspace) == Some(b'>') {
1702 // The nesting limit: past it the marker is text. The
1703 // holder is judged from `container`, which is what the
1704 // tip becomes once `close_unmatched_blocks` has run.
1705 if self.depth_of_new(container, NodeType::BlockQuote) > MAX_CONTAINER_NESTING {
1706 return StartResult::None;
1707 }
1708 self.advance_next_nonspace();
1709 self.advance_offset(1, false);
1710 if is_space_or_tab(peek(&self.current_line, self.offset)) {
1711 self.advance_offset(1, true);
1712 }
1713 self.close_unmatched_blocks();
1714 self.add_child(NodeType::BlockQuote, self.next_nonspace);
1715 return StartResult::Container;
1716 }
1717 StartResult::None
1718 }
1719
1720 // ATX heading (section 4.2).
1721 1 => {
1722 if self.indented {
1723 return StartResult::None;
1724 }
1725 let Some((level, match_len)) =
1726 match_atx_heading_marker(&self.current_line[self.next_nonspace..])
1727 else {
1728 return StartResult::None;
1729 };
1730
1731 self.advance_next_nonspace();
1732 self.advance_offset(match_len, false);
1733 self.close_unmatched_blocks();
1734
1735 let heading = self.add_child(NodeType::Heading, self.next_nonspace);
1736 let content = strip_atx_closing(&self.current_line[self.offset..]).to_string();
1737 {
1738 let node = self.tree.get_mut(heading);
1739 node.level = level;
1740 node.string_content = content;
1741 }
1742 let rest = self.current_line.len() - self.offset;
1743 self.advance_offset(rest, false);
1744 StartResult::Leaf
1745 }
1746
1747 // Fenced code block (section 4.5).
1748 2 => {
1749 if self.indented {
1750 return StartResult::None;
1751 }
1752 let rest = &self.current_line[self.next_nonspace..];
1753 let fence_length = match_code_fence(rest);
1754 if fence_length == 0 {
1755 return StartResult::None;
1756 }
1757 let fence_char = rest.as_bytes()[0];
1758
1759 self.close_unmatched_blocks();
1760 let code = self.add_child(NodeType::CodeBlock, self.next_nonspace);
1761 {
1762 let node = self.tree.get_mut(code);
1763 node.is_fenced = true;
1764 node.fence_length = fence_length;
1765 node.fence_char = fence_char;
1766 node.fence_offset = self.indent;
1767 }
1768 self.advance_next_nonspace();
1769 self.advance_offset(fence_length, false);
1770 // The rest of the line is added as the block's first line:
1771 // the info string.
1772 StartResult::Leaf
1773 }
1774
1775 // HTML block (section 4.6), types 1 to 7.
1776 3 => {
1777 if self.indented || peek(&self.current_line, self.next_nonspace) != Some(b'<') {
1778 return StartResult::None;
1779 }
1780 let kind = html_block_open_kind(&self.current_line[self.next_nonspace..]);
1781 if kind == 0 {
1782 return StartResult::None;
1783 }
1784 // Type 7 may not interrupt a paragraph, including a
1785 // paragraph we are only about to continue lazily.
1786 if kind == 7
1787 && (self.node_type(container) == NodeType::Paragraph
1788 || (!self.all_closed
1789 && !self.blank
1790 && self.node_type(self.open_tip()) == NodeType::Paragraph))
1791 {
1792 return StartResult::None;
1793 }
1794 self.close_unmatched_blocks();
1795 // The offset is deliberately not advanced: leading spaces
1796 // are part of the raw HTML.
1797 let block = self.add_child(NodeType::HtmlBlock, self.offset);
1798 self.set_html_block_type(block, kind);
1799 StartResult::Leaf
1800 }
1801
1802 // Setext heading underline (section 4.3): converts the whole
1803 // open paragraph.
1804 4 => {
1805 if self.indented || self.node_type(container) != NodeType::Paragraph {
1806 return StartResult::None;
1807 }
1808 let Some(underline) =
1809 match_setext_heading_line(&self.current_line[self.next_nonspace..])
1810 else {
1811 return StartResult::None;
1812 };
1813
1814 self.close_unmatched_blocks();
1815
1816 // Section 4.7: the paragraph may still have led with
1817 // reference definitions; only what remains becomes the
1818 // heading. If nothing remains this is not a setext underline
1819 // at all (it falls through to thematic break / paragraph).
1820 self.consume_reference_defs(container);
1821 if self.tree.get(container).string_content.is_empty() {
1822 return StartResult::None;
1823 }
1824
1825 let start = self.tree.get(container).sourcepos[0];
1826 let content = std::mem::take(&mut self.tree.get_mut(container).string_content);
1827 let mut heading = MdNode::new(NodeType::Heading);
1828 heading.sourcepos = [[start[0], start[1]], [0, 0]];
1829 heading.level = if underline == b'=' { 1 } else { 2 };
1830 heading.string_content = content;
1831 let heading = self.tree.add(heading);
1832 self.tree.insert_after(container, heading);
1833 self.tree.unlink(container);
1834 self.tip = Some(heading);
1835 let rest = self.current_line.len() - self.offset;
1836 self.advance_offset(rest, false);
1837 StartResult::Leaf
1838 }
1839
1840 // Thematic break (section 4.1).
1841 5 => {
1842 if self.indented {
1843 return StartResult::None;
1844 }
1845 if !is_thematic_break(&self.current_line[self.next_nonspace..]) {
1846 return StartResult::None;
1847 }
1848 self.close_unmatched_blocks();
1849 self.add_child(NodeType::ThematicBreak, self.next_nonspace);
1850 let rest = self.current_line.len() - self.offset;
1851 self.advance_offset(rest, false);
1852 StartResult::Leaf
1853 }
1854
1855 // List item (section 5.2). `parse_list_marker` rejects a marker
1856 // indented four or more columns on its own, so there is no
1857 // `indented` test here.
1858 6 => {
1859 // `parse_list_marker` moves the cursor when it matches, so
1860 // the position is kept for the nesting limit below, which
1861 // has to leave the line exactly as it found it.
1862 let before = (self.offset, self.column, self.partially_consumed_tab);
1863 let Some(data) = self.parse_list_marker(container) else {
1864 return StartResult::None;
1865 };
1866
1867 // Section 5.3: a change of bullet character or ordered
1868 // delimiter starts a new list. Judged from `container`,
1869 // which is what the tip becomes once
1870 // `close_unmatched_blocks` has run.
1871 let same_list = self.node_type(container) == NodeType::List
1872 && self
1873 .tree
1874 .get(container)
1875 .list_data
1876 .as_ref()
1877 .is_some_and(|existing| lists_match(existing, &data));
1878
1879 // The nesting limit: an item in the open list is one
1880 // container deeper, a new list and its item are two. Past
1881 // it the marker is text.
1882 let depth = if same_list {
1883 self.depth_of_new(container, NodeType::Item)
1884 } else {
1885 self.depth_of_new(container, NodeType::List) + 1
1886 };
1887 if depth > MAX_CONTAINER_NESTING {
1888 (self.offset, self.column, self.partially_consumed_tab) = before;
1889 return StartResult::None;
1890 }
1891
1892 self.close_unmatched_blocks();
1893
1894 let tip = self.open_tip();
1895 debug_assert_eq!(tip, container, "the tip is the last matched container");
1896 if !same_list {
1897 let list = self.add_child(NodeType::List, self.next_nonspace);
1898 self.tree.get_mut(list).list_data = Some(data.clone());
1899 }
1900
1901 let item = self.add_child(NodeType::Item, self.next_nonspace);
1902 self.tree.get_mut(item).list_data = Some(data);
1903 StartResult::Container
1904 }
1905
1906 // Indented code block (section 4.4): may not interrupt a
1907 // paragraph.
1908 7 => {
1909 if !self.indented
1910 || self.node_type(self.open_tip()) == NodeType::Paragraph
1911 || self.blank
1912 {
1913 return StartResult::None;
1914 }
1915 self.advance_offset(CODE_INDENT, true);
1916 self.close_unmatched_blocks();
1917 self.add_child(NodeType::CodeBlock, self.offset);
1918 StartResult::Leaf
1919 }
1920
1921 // GFM table (extension): a delimiter row directly under an open
1922 // paragraph.
1923 //
1924 // Last, and the position is load-bearing in both directions. It
1925 // must come after the setext underline so that `foo` over `---`
1926 // stays an `<h2>` rather than becoming a one-column table, and
1927 // after the list marker so that `- | -` stays a list item;
1928 // cmark-gfm reaches its extensions from the same place, once
1929 // every built-in start has refused the line.
1930 8 => {
1931 if self.try_open_table(container) {
1932 StartResult::Leaf
1933 } else {
1934 StartResult::None
1935 }
1936 }
1937
1938 _ => StartResult::None,
1939 }
1940 }
1941
1942 /// How many block starts `block_start` knows.
1943 const BLOCK_STARTS: usize = 9;
1944
1945 /// Incorporate one line into the tree: the three steps of Appendix A.
1946 pub fn incorporate_line(&mut self, ln: &str) {
1947 let mut all_matched = true;
1948 let mut container = self.doc;
1949
1950 // `last_line_length` still measures the previous line here.
1951 // Captured before anything can overwrite it (an HTML block closing
1952 // mid-line does) and installed as `prev_line_length` at whichever
1953 // exit updates `last_line_length`, so the two always describe
1954 // consecutive lines.
1955 let length_before_this_line = self.last_line_length;
1956
1957 self.oldtip = self.open_tip();
1958 self.offset = 0;
1959 self.column = 0;
1960 self.blank = false;
1961 self.partially_consumed_tab = false;
1962 self.line_number += 1;
1963 self.current_line.clear();
1964 self.current_line.push_str(ln);
1965 // The column anchor memoizes offsets into `current_line`; a new line
1966 // invalidates it. See `source_column`.
1967 self.col_anchor_offset = 0;
1968 self.col_anchor_chars = 0;
1969
1970 // Step 1: walk the open blocks, consuming continuation markers.
1971 // Stop at the first block that does not match; `container` is then
1972 // the last matched one.
1973 let mut last_child = self.tree.get(container).last_child;
1974 while let Some(child) = last_child {
1975 if !self.tree.get(child).open {
1976 break;
1977 }
1978 container = child;
1979 self.find_next_nonspace();
1980
1981 match self.continue_block(container) {
1982 ContinueResult::NotMatched => all_matched = false,
1983 // A fenced code block was closed by this line; nothing else
1984 // to do.
1985 ContinueResult::LineDone => return,
1986 ContinueResult::Matched => {}
1987 }
1988
1989 if !all_matched {
1990 if let Some(parent) = self.tree.get(container).parent {
1991 container = parent;
1992 }
1993 break;
1994 }
1995
1996 last_child = self.tree.get(container).last_child;
1997 }
1998
1999 self.all_closed = container == self.oldtip;
2000 self.last_matched_container = container;
2001
2002 // Step 2: look for new block starts under the last matched
2003 // container, unless its lines are literal text, in which case there
2004 // is nothing to look for.
2005 let mut matched_leaf = verbatim(self.node_type(container));
2006
2007 while !matched_leaf {
2008 self.find_next_nonspace();
2009
2010 let special = if self.gfm_special {
2011 maybe_special_gfm(&self.current_line, self.next_nonspace)
2012 } else {
2013 maybe_special(&self.current_line, self.next_nonspace)
2014 };
2015 if !self.indented && !special {
2016 self.advance_next_nonspace();
2017 break;
2018 }
2019
2020 let mut i = 0;
2021 while i < Self::BLOCK_STARTS {
2022 match self.block_start(i, container) {
2023 StartResult::Container => {
2024 container = self.open_tip();
2025 break;
2026 }
2027 StartResult::Leaf => {
2028 container = self.open_tip();
2029 matched_leaf = true;
2030 break;
2031 }
2032 StartResult::None => i += 1,
2033 }
2034 }
2035
2036 if i == Self::BLOCK_STARTS {
2037 // Nothing matched: the rest of the line is plain text.
2038 self.advance_next_nonspace();
2039 break;
2040 }
2041 }
2042
2043 // Step 3: whatever is left of the line is text for the deepest open
2044 // block.
2045 if !self.all_closed && !self.blank && self.node_type(self.open_tip()) == NodeType::Paragraph
2046 {
2047 // Lazy continuation (section 5.1 rule 2): the markers are
2048 // missing but an open paragraph absorbs the line anyway, and
2049 // its containers stay open.
2050 self.add_line();
2051 self.prev_line_length = length_before_this_line;
2052 self.last_line_length = char_count(ln);
2053 return;
2054 }
2055
2056 self.close_unmatched_blocks();
2057
2058 if self.blank {
2059 if let Some(last) = self.tree.get(container).last_child {
2060 self.tree.get_mut(last).last_line_blank = true;
2061 }
2062 }
2063
2064 let t = self.node_type(container);
2065
2066 // A block quote line is never blank (it has a `>`), blank lines
2067 // inside fenced code do not affect list looseness, and an item's own
2068 // first blank line is part of the item, not a separator.
2069 let last_line_blank = self.blank && {
2070 let node = self.tree.get(container);
2071 !(t == NodeType::BlockQuote
2072 || (t == NodeType::CodeBlock && node.is_fenced)
2073 || (t == NodeType::Item
2074 && node.first_child.is_none()
2075 && node.sourcepos[0][0] == self.line_number))
2076 };
2077
2078 // Propagate up: a container whose last line was blank ends with a
2079 // blank line.
2080 let mut cont = Some(container);
2081 while let Some(id) = cont {
2082 let node = self.tree.get_mut(id);
2083 node.last_line_blank = last_line_blank;
2084 cont = node.parent;
2085 }
2086
2087 if accepts_lines(t) {
2088 self.add_line();
2089 // Section 4.6: HTML block types 1 to 5 end on the line that
2090 // contains their closing string, which may be the line that
2091 // opened them.
2092 if t == NodeType::HtmlBlock {
2093 let kind = self.html_block_type(container);
2094 if (1..=5).contains(&kind)
2095 && html_block_closes(&self.current_line[self.offset..], kind)
2096 {
2097 self.last_line_length = char_count(ln);
2098 self.finalize(container, self.line_number);
2099 }
2100 }
2101 } else if self.offset < self.current_line.len() && !self.blank {
2102 // Nowhere else for the text to go: open a paragraph for it.
2103 self.add_child(NodeType::Paragraph, self.offset);
2104 self.advance_next_nonspace();
2105 self.add_line();
2106 }
2107
2108 self.prev_line_length = length_before_this_line;
2109 self.last_line_length = char_count(ln);
2110 }
2111
2112 /// Feed every line of `input` and finish. An empty document still
2113 /// incorporates one empty line, exactly as the historical split-based
2114 /// loop did: line count and sourcepos depend on it. Line cutting and
2115 /// section 2.3 NUL replacement both live in `segment_next_line`.
2116 pub fn parse(mut self, input: &str) -> (Tree, RefMap) {
2117 if input.is_empty() {
2118 self.incorporate_line("");
2119 } else {
2120 let mut pos = 0;
2121 while let Some(seg) = segment_next_line(input, pos) {
2122 self.incorporate_line(&seg.text);
2123 pos = seg.next;
2124 }
2125 }
2126 self.finish()
2127 }
2128
2129 /// Close every still-open block, stamp the parse-time `gfm` flag, and
2130 /// run the task-list post-pass. `line_number` is the count of
2131 /// incorporated lines, so an incremental driver (one that feeds
2132 /// `incorporate_line` itself instead of calling `parse`) finishes with
2133 /// exactly the same finalization the batch loop gets.
2134 pub fn finish(mut self) -> (Tree, RefMap) {
2135 while let Some(tip) = self.tip {
2136 self.finalize(tip, self.line_number);
2137 }
2138
2139 self.tree.get_mut(self.doc).gfm = self.options.gfm;
2140 if self.options.gfm {
2141 mark_task_list_items(&mut self.tree, self.doc);
2142 }
2143
2144 (self.tree, self.refmap)
2145 }
2146}
2147
2148// --- GFM task list items ----------------------------------------------------
2149
2150/// The task list item marker: optional spaces, `[`, either a whitespace
2151/// character or `x`/`X`, `]`, and then at least one whitespace character
2152/// before any other content. Returns the character between the brackets
2153/// and the byte length of the whole marker.
2154///
2155/// The trailing whitespace is required by the extension ("...and at least
2156/// one whitespace character before any other content"), so `- [x]` with
2157/// nothing after it is an ordinary item whose text is `[x]`. It is matched
2158/// as a space or a tab rather than as any whitespace: a line ending there
2159/// would mean the content starts on the *next* line, and consuming it would
2160/// swallow the paragraph's first soft break.
2161pub fn task_list_marker(s: &str) -> Option<(u8, usize)> {
2162 let bytes = s.as_bytes();
2163 let mut i = 0;
2164 while i < bytes.len() && bytes[i] == b' ' {
2165 i += 1;
2166 }
2167 if i >= bytes.len() || bytes[i] != b'[' {
2168 return None;
2169 }
2170 i += 1;
2171 if i >= bytes.len() {
2172 return None;
2173 }
2174 let state = bytes[i];
2175 if state != b' ' && state != b'\t' && state != b'x' && state != b'X' {
2176 return None;
2177 }
2178 i += 1;
2179 if i >= bytes.len() || bytes[i] != b']' {
2180 return None;
2181 }
2182 i += 1;
2183
2184 let spaces = i;
2185 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
2186 i += 1;
2187 }
2188 if i == spaces {
2189 return None;
2190 }
2191 Some((state, i))
2192}
2193
2194/// GFM task list items: mark every item whose first block is a paragraph
2195/// beginning with a task list item marker, and consume the marker so it
2196/// does not survive into the text.
2197///
2198/// Run at the end of the block phase, over `string_content`, before the
2199/// inline phase has seen it. That is what makes the marker win over
2200/// anything the inline scanner would otherwise make of the brackets: with
2201/// a `[x]: /url` definition in the document, `- [x] foo` is still a task
2202/// item rather than a link. It also means the item's checked state is
2203/// settled before `ast.rs` or `html.rs` looks at the tree.
2204///
2205/// Iterative rather than recursive: container nesting depth is chosen by
2206/// the input, and `"> ".repeat(20000)` is a document this parser otherwise
2207/// handles.
2208fn mark_task_list_items(tree: &mut Tree, doc: NodeId) {
2209 let mut stack = vec![doc];
2210
2211 while let Some(node) = stack.pop() {
2212 let t = tree.get(node).node_type;
2213
2214 if t == NodeType::Item {
2215 if let Some(first) = tree.get(node).first_child {
2216 if tree.get(first).node_type == NodeType::Paragraph {
2217 if let Some((state, length)) = task_list_marker(&tree.get(first).string_content)
2218 {
2219 // Whitespace between the brackets is unchecked;
2220 // `x`/`X` is checked.
2221 tree.get_mut(node).checked = Some(state != b' ' && state != b'\t');
2222 let content = &mut tree.get_mut(first).string_content;
2223 content.drain(..length);
2224 }
2225 }
2226 }
2227 }
2228
2229 if matches!(
2230 t,
2231 NodeType::Document | NodeType::BlockQuote | NodeType::List | NodeType::Item
2232 ) {
2233 let mut c = tree.get(node).last_child;
2234 while let Some(id) = c {
2235 stack.push(id);
2236 c = tree.get(id).prev;
2237 }
2238 }
2239 }
2240}
2241
2242/// Phase 1: build the block tree and collect link reference definitions.
2243/// Paragraph and heading text is left raw in `string_content` for phase 2.
2244pub fn parse_blocks(input: &str, options: Options) -> (Tree, RefMap) {
2245 BlockParser::new(options).parse(input)
2246}
2247
2248#[cfg(test)]
2249mod tests {
2250 use super::*;
2251
2252 #[test]
2253 fn atx_closing_sequences() {
2254 assert_eq!(strip_atx_closing("Hello ###"), "Hello");
2255 assert_eq!(strip_atx_closing("###"), "");
2256 assert_eq!(strip_atx_closing("Hello #x"), "Hello #x");
2257 assert_eq!(strip_atx_closing("Hello ### "), "Hello");
2258 assert_eq!(strip_atx_closing("a ## b ##"), "a ## b");
2259 assert_eq!(strip_atx_closing("foo#"), "foo#");
2260 assert_eq!(strip_atx_closing(" ### "), "");
2261 assert_eq!(strip_atx_closing(""), "");
2262 }
2263
2264 #[test]
2265 fn trailing_blank_runs() {
2266 assert_eq!(trailing_blank_run_start(b"a\n \n"), 1);
2267 assert_eq!(trailing_blank_run_start(b"a\nb"), 3);
2268 assert_eq!(trailing_blank_run_start(b""), 0);
2269 }
2270}