Skip to main content

tabnas_markdown/
node.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Native CommonMark node tree, the internal parse result. Port of
4//! `ts/src/node.ts` and `go/node.go`; keep the three in step.
5//!
6//! The canonical tree is linked (parent / firstChild / lastChild / prev /
7//! next) rather than a children array, because both phases of the
8//! CommonMark algorithm (spec 0.31.2 Appendix A) splice nodes mid-walk: the
9//! block phase keeps a spine of open blocks and closes them from the tail,
10//! and the inline phase's delimiter stack rewrites sibling runs in place.
11//!
12//! This port keeps exactly those links, but the nodes live in an arena
13//! ([`Tree`]) and the links are indices ([`NodeId`]) rather than pointers.
14//! That is the one shape difference from the other two runtimes, and it is
15//! what Rust's ownership rules ask for: a node that points at its parent
16//! and its siblings cannot be a plain owned value, and reference counting
17//! would make every splice a borrow-checker negotiation. An arena gives
18//! the same O(1) splices with plain integer bookkeeping, and an unlinked
19//! node simply becomes unreachable. A driver that writes blocks as they
20//! finish and keeps no tree gives a written block's slots back
21//! ([`Tree::free_subtree`], [`crate::block::BlockParser::release_block`]),
22//! which the next nodes fill, so a long document's arena stays as large as
23//! its widest open block, not its length (tabnas/markdown#100).
24//!
25//! The public, mdast-adjacent AST is produced from this tree by `ast.rs`.
26//! That projection is lossy on purpose (it drops raw inline HTML boundaries
27//! and source positions); the tree is what `html.rs` renders for CommonMark
28//! conformance.
29
30/// The node kinds. String-valued in the other two runtimes so that debug
31/// output and the AST projection read the same; [`NodeType::as_str`] is
32/// the same spelling here.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum NodeType {
35    // Containers.
36    Document,
37    BlockQuote,
38    List,
39    Item,
40    // Leaf blocks.
41    Paragraph,
42    Heading,
43    ThematicBreak,
44    CodeBlock,
45    HtmlBlock,
46    // GFM tables (extension): a leaf block as far as the spec's algorithm is
47    // concerned (no block-level element can be inserted in one) but a
48    // container as far as the tree is concerned, since its rows and cells
49    // are real nodes and its cells hold inlines.
50    Table,
51    TableRow,
52    TableCell,
53    // Inlines.
54    Text,
55    Softbreak,
56    Linebreak,
57    Code,
58    HtmlInline,
59    Emph,
60    Strong,
61    Link,
62    Image,
63    Del,
64    // A link or an image whose destination a label names, kept unresolved:
65    // an inline parse that reads references as references (the AST's, see
66    // `ast.rs`) makes these where the resolving parse would look the label
67    // up. The HTML renderer never sees one, since the tree it renders comes
68    // from the resolving parse.
69    LinkReference,
70    ImageReference,
71}
72
73impl NodeType {
74    /// The canonical name, as the TypeScript union and the Go constants
75    /// spell it.
76    pub fn as_str(self) -> &'static str {
77        match self {
78            NodeType::Document => "document",
79            NodeType::BlockQuote => "block_quote",
80            NodeType::List => "list",
81            NodeType::Item => "item",
82            NodeType::Paragraph => "paragraph",
83            NodeType::Heading => "heading",
84            NodeType::ThematicBreak => "thematic_break",
85            NodeType::CodeBlock => "code_block",
86            NodeType::HtmlBlock => "html_block",
87            NodeType::Table => "table",
88            NodeType::TableRow => "table_row",
89            NodeType::TableCell => "table_cell",
90            NodeType::Text => "text",
91            NodeType::Softbreak => "softbreak",
92            NodeType::Linebreak => "linebreak",
93            NodeType::Code => "code",
94            NodeType::HtmlInline => "html_inline",
95            NodeType::Emph => "emph",
96            NodeType::Strong => "strong",
97            NodeType::Link => "link",
98            NodeType::Image => "image",
99            NodeType::Del => "del",
100            NodeType::LinkReference => "link_reference",
101            NodeType::ImageReference => "image_reference",
102        }
103    }
104
105    /// Containers may hold children; leaves carry only `literal`.
106    pub fn is_container(self) -> bool {
107        matches!(
108            self,
109            NodeType::Document
110                | NodeType::BlockQuote
111                | NodeType::List
112                | NodeType::Item
113                | NodeType::Paragraph
114                | NodeType::Heading
115                | NodeType::Table
116                | NodeType::TableRow
117                | NodeType::TableCell
118                | NodeType::Emph
119                | NodeType::Strong
120                | NodeType::Link
121                | NodeType::Image
122                | NodeType::Del
123                | NodeType::LinkReference
124                | NodeType::ImageReference
125        )
126    }
127}
128
129/// How a reference names its label (section 6.3): `[a][b]`, `[a][]` or
130/// `[a]`.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum ReferenceType {
133    Full,
134    Collapsed,
135    Shortcut,
136}
137
138impl ReferenceType {
139    /// The name the AST's `referenceType` carries.
140    pub fn as_str(self) -> &'static str {
141        match self {
142            ReferenceType::Full => "full",
143            ReferenceType::Collapsed => "collapsed",
144            ReferenceType::Shortcut => "shortcut",
145        }
146    }
147}
148
149/// A link reference definition (section 4.7) as the block phase read it
150/// from the front of a paragraph.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Definition {
153    /// The label's raw source text, between its brackets.
154    pub label: String,
155    /// The destination, already entity-decoded and backslash-unescaped.
156    pub destination: String,
157    /// The title, likewise.
158    pub title: Option<String>,
159    /// The source lines the definition spans, 1-based, both included.
160    pub start: usize,
161    pub end: usize,
162}
163
164/// Where a definition stands among a container's children: after the
165/// child `after` (`None`: before the first), in source order. Definitions
166/// are not blocks in the spec's algorithm, which reads them out of a
167/// paragraph and drops a paragraph that held nothing else, so they are
168/// kept beside the children rather than among them: the block phase's own
169/// reads of a container's children (list looseness, the blank-line flags)
170/// never see one.
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct DefinitionSite {
173    pub after: Option<NodeId>,
174    pub def: Definition,
175}
176
177/// Per-column alignment of a GFM table, from the colons in its delimiter
178/// row: `:--` left, `--:` right, `:-:` center. A column with no colon is
179/// `None`, which is the canonical runtime's `null` and the Go port's
180/// `AlignNone`.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum Align {
183    Left,
184    Right,
185    Center,
186}
187
188impl Align {
189    /// The attribute value the renderer writes and the AST carries.
190    pub fn as_str(self) -> &'static str {
191        match self {
192            Align::Left => "left",
193            Align::Right => "right",
194            Align::Center => "center",
195        }
196    }
197}
198
199/// One column's alignment; `None` for a delimiter cell with no colon.
200pub type TableAlign = Option<Align>;
201
202/// Bullet or ordered.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum ListType {
205    Bullet,
206    Ordered,
207}
208
209impl ListType {
210    pub fn as_str(self) -> &'static str {
211        match self {
212            ListType::Bullet => "bullet",
213            ListType::Ordered => "ordered",
214        }
215    }
216}
217
218/// What sections 5.2 and 5.3 need to decide list identity and rendering.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct ListData {
221    pub list_type: ListType,
222    /// Tight lists omit the `<p>` wrapper around item paragraphs. Decided
223    /// at finalize.
224    pub tight: bool,
225    /// Ordered-list start number; ignored for bullet lists.
226    pub start: i64,
227    /// `.` or `)` for ordered lists; a change of delimiter starts a new list.
228    pub delimiter: String,
229    /// `-`, `+` or `*` for bullet lists; a change of char starts a new list.
230    pub bullet_char: String,
231    /// Columns of padding between the marker and the item content.
232    pub padding: usize,
233    /// Column at which the marker starts.
234    pub marker_offset: usize,
235}
236
237/// `[[startLine, startCol], [endLine, endCol]]`, all 1-based, with columns
238/// counted in characters (not bytes) as the spec counts them.
239pub type SourcePos = [[usize; 2]; 2];
240
241/// An index into a [`Tree`]'s arena.
242pub type NodeId = usize;
243
244/// One node of the tree.
245#[derive(Debug, Clone)]
246pub struct MdNode {
247    pub node_type: NodeType,
248
249    pub parent: Option<NodeId>,
250    pub first_child: Option<NodeId>,
251    pub last_child: Option<NodeId>,
252    pub prev: Option<NodeId>,
253    pub next: Option<NodeId>,
254
255    pub sourcepos: SourcePos,
256
257    /// Text payload for text / code / html_block / html_inline / code_block.
258    pub literal: String,
259
260    /// Heading level 1..6.
261    pub level: usize,
262
263    /// Link/image destination, already entity-decoded and
264    /// backslash-unescaped.
265    pub destination: String,
266    /// Link/image title, already entity-decoded and backslash-unescaped.
267    /// `None` is the canonical runtime's `null` (the Go port's `HasTitle`
268    /// false).
269    pub title: Option<String>,
270
271    /// Fenced code info string (raw, entity-decoded); `None` for indented
272    /// code, which is the canonical `null` and Go's `HasInfo` false.
273    pub info: Option<String>,
274    /// True for fenced code blocks, false for indented.
275    pub is_fenced: bool,
276    pub fence_char: u8,
277    pub fence_length: usize,
278    pub fence_offset: usize,
279
280    pub list_data: Option<ListData>,
281
282    /// GFM tables: one entry per column, in order, set on the **table** node
283    /// by the block phase from the delimiter row. Every row of the table,
284    /// header and body alike, has exactly this many cells, because short
285    /// rows are padded and long ones are truncated. `None` on every other
286    /// node type.
287    pub table_align: Option<Vec<TableAlign>>,
288
289    /// GFM tables: true on the one `table_row` that is the header row, which
290    /// is always the table's first child. mdast has no header flag and
291    /// relies on that convention, but the renderer needs to choose `<th>`
292    /// over `<td>` without walking back up to the table.
293    pub is_header_row: bool,
294
295    /// GFM task list items (`- [x] foo`): `Some(true)` / `Some(false)` for a
296    /// checked / unchecked item, `None` for an ordinary one. Set on `item`
297    /// nodes by the block phase when `gfm` is on, once the marker has been
298    /// consumed from the item's first paragraph. mdast's field and mdast's
299    /// semantics; `ast.rs` projects it straight through to
300    /// `listItem.checked`.
301    pub checked: Option<bool>,
302
303    /// The `gfm` parse option, recorded on the **document** node by the
304    /// block phase and meaningless anywhere else. The renderer defaults to
305    /// it when called without options, so a tree parsed as plain CommonMark
306    /// renders as plain CommonMark.
307    pub gfm: bool,
308
309    // --- block-phase bookkeeping, not part of the rendered tree ---
310    /// Open blocks accept further lines; closed ones are finalized.
311    pub open: bool,
312    /// Accumulated raw content, consumed by the inline phase.
313    pub string_content: String,
314    /// A block whose last line was blank cannot be lazily continued.
315    pub last_line_blank: bool,
316    pub last_line_checked: bool,
317    /// A paragraph's source line where `string_content` begins: its first
318    /// line, moved on past each definition read off the front, so a
319    /// definition read later knows its lines.
320    pub content_line: usize,
321
322    /// A `link_reference`'s or `image_reference`'s label (its raw source
323    /// text, between its brackets) and the form that named it.
324    pub label: String,
325    pub reference_type: Option<ReferenceType>,
326
327    /// A container's link reference definitions, read from paragraphs
328    /// among its children, each with where it stands.
329    pub definitions: Vec<DefinitionSite>,
330}
331
332impl MdNode {
333    /// An open, unlinked node of the given type.
334    pub fn new(node_type: NodeType) -> Self {
335        MdNode {
336            node_type,
337            parent: None,
338            first_child: None,
339            last_child: None,
340            prev: None,
341            next: None,
342            sourcepos: [[0, 0], [0, 0]],
343            literal: String::new(),
344            level: 0,
345            destination: String::new(),
346            title: None,
347            info: None,
348            is_fenced: false,
349            fence_char: 0,
350            fence_length: 0,
351            fence_offset: 0,
352            list_data: None,
353            table_align: None,
354            is_header_row: false,
355            checked: None,
356            gfm: true,
357            open: true,
358            string_content: String::new(),
359            last_line_blank: false,
360            last_line_checked: false,
361            content_line: 0,
362            label: String::new(),
363            reference_type: None,
364            definitions: Vec::new(),
365        }
366    }
367
368    /// Containers may hold children; leaves carry only `literal`.
369    pub fn is_container(&self) -> bool {
370        self.node_type.is_container()
371    }
372}
373
374/// The arena holding one document's nodes, with the document at
375/// [`Tree::root`].
376#[derive(Debug, Clone)]
377pub struct Tree {
378    nodes: Vec<MdNode>,
379    root: NodeId,
380    /// Slots [`Tree::free_subtree`] gave back, which [`Tree::add`] fills
381    /// before it grows the arena. Empty unless a driver that keeps no tree
382    /// frees the blocks it has written (tabnas/markdown#100).
383    free: Vec<NodeId>,
384}
385
386impl Tree {
387    /// A tree holding only a fresh node of `root_type`, which becomes the
388    /// root.
389    pub fn new(root_type: NodeType) -> Self {
390        Tree {
391            nodes: vec![MdNode::new(root_type)],
392            root: 0,
393            free: Vec::new(),
394        }
395    }
396
397    /// The root node's id (the document, for a parse).
398    pub fn root(&self) -> NodeId {
399        self.root
400    }
401
402    /// Add an unlinked node to the arena and return its id: a slot
403    /// [`Tree::free_subtree`] gave back, when there is one.
404    pub fn add(&mut self, node: MdNode) -> NodeId {
405        if let Some(id) = self.free.pop() {
406            self.nodes[id] = node;
407            return id;
408        }
409        self.nodes.push(node);
410        self.nodes.len() - 1
411    }
412
413    /// Detach `node` and give its slot, and the slots of every node below
414    /// it, back to the arena for [`Tree::add`] to fill, dropping what each
415    /// held; answer the ids given back. Only for a node nothing will read
416    /// again: a slot given back takes the next node added, under the same
417    /// id. Iterative, since nesting is the input's to choose.
418    pub fn free_subtree(&mut self, node: NodeId) -> Vec<NodeId> {
419        self.unlink(node);
420        let mut freed = Vec::new();
421        let mut pending = vec![node];
422        while let Some(id) = pending.pop() {
423            let mut child = self.nodes[id].first_child;
424            while let Some(c) = child {
425                pending.push(c);
426                child = self.nodes[c].next;
427            }
428            self.nodes[id] = MdNode::new(NodeType::Paragraph);
429            freed.push(id);
430        }
431        self.free.extend(freed.iter().copied());
432        freed
433    }
434
435    /// Add an open, unlinked node of `node_type`.
436    pub fn new_node(&mut self, node_type: NodeType) -> NodeId {
437        self.add(MdNode::new(node_type))
438    }
439
440    pub fn get(&self, id: NodeId) -> &MdNode {
441        &self.nodes[id]
442    }
443
444    pub fn get_mut(&mut self, id: NodeId) -> &mut MdNode {
445        &mut self.nodes[id]
446    }
447
448    /// How many slots the arena holds, unlinked nodes' and given-back ones
449    /// included.
450    pub fn len(&self) -> usize {
451        self.nodes.len()
452    }
453
454    pub fn is_empty(&self) -> bool {
455        self.nodes.is_empty()
456    }
457
458    /// The children of `parent`, first to last.
459    pub fn children(&self, parent: NodeId) -> Vec<NodeId> {
460        let mut out = Vec::new();
461        let mut child = self.nodes[parent].first_child;
462        while let Some(c) = child {
463            out.push(c);
464            child = self.nodes[c].next;
465        }
466        out
467    }
468
469    /// Add `child` as the last child of `parent`, detaching it first.
470    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
471        self.unlink(child);
472        self.nodes[child].parent = Some(parent);
473        if let Some(last) = self.nodes[parent].last_child {
474            self.nodes[last].next = Some(child);
475            self.nodes[child].prev = Some(last);
476            self.nodes[parent].last_child = Some(child);
477        } else {
478            self.nodes[parent].first_child = Some(child);
479            self.nodes[parent].last_child = Some(child);
480        }
481    }
482
483    /// Add `child` as the first child of `parent`, detaching it first.
484    pub fn prepend_child(&mut self, parent: NodeId, child: NodeId) {
485        self.unlink(child);
486        self.nodes[child].parent = Some(parent);
487        if let Some(first) = self.nodes[parent].first_child {
488            self.nodes[first].prev = Some(child);
489            self.nodes[child].next = Some(first);
490            self.nodes[parent].first_child = Some(child);
491        } else {
492            self.nodes[parent].first_child = Some(child);
493            self.nodes[parent].last_child = Some(child);
494        }
495    }
496
497    /// Place `sibling` directly after `node`.
498    pub fn insert_after(&mut self, node: NodeId, sibling: NodeId) {
499        self.unlink(sibling);
500        let next = self.nodes[node].next;
501        self.nodes[sibling].next = next;
502        if let Some(n) = next {
503            self.nodes[n].prev = Some(sibling);
504        }
505        self.nodes[sibling].prev = Some(node);
506        self.nodes[node].next = Some(sibling);
507        let parent = self.nodes[node].parent;
508        self.nodes[sibling].parent = parent;
509        if next.is_none() {
510            if let Some(p) = parent {
511                self.nodes[p].last_child = Some(sibling);
512            }
513        }
514    }
515
516    /// Place `sibling` directly before `node`.
517    pub fn insert_before(&mut self, node: NodeId, sibling: NodeId) {
518        self.unlink(sibling);
519        let prev = self.nodes[node].prev;
520        self.nodes[sibling].prev = prev;
521        if let Some(p) = prev {
522            self.nodes[p].next = Some(sibling);
523        }
524        self.nodes[sibling].next = Some(node);
525        self.nodes[node].prev = Some(sibling);
526        let parent = self.nodes[node].parent;
527        self.nodes[sibling].parent = parent;
528        if prev.is_none() {
529            if let Some(p) = parent {
530                self.nodes[p].first_child = Some(sibling);
531            }
532        }
533    }
534
535    /// Detach `node` from the tree, leaving the node itself intact.
536    pub fn unlink(&mut self, node: NodeId) {
537        let (parent, prev, next) = {
538            let n = &self.nodes[node];
539            (n.parent, n.prev, n.next)
540        };
541        match prev {
542            Some(p) => self.nodes[p].next = next,
543            None => {
544                if let Some(par) = parent {
545                    self.nodes[par].first_child = next;
546                }
547            }
548        }
549        match next {
550            Some(n) => self.nodes[n].prev = prev,
551            None => {
552                if let Some(par) = parent {
553                    self.nodes[par].last_child = prev;
554                }
555            }
556        }
557        let n = &mut self.nodes[node];
558        n.parent = None;
559        n.next = None;
560        n.prev = None;
561    }
562
563    /// A depth-first walker rooted at `root`. Containers are entered and
564    /// exited; leaves produce one event.
565    pub fn walker(&self, root: NodeId) -> Walker {
566        Walker {
567            current: Some(root),
568            root,
569            entering: true,
570        }
571    }
572}
573
574/// One step of a depth-first walk.
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
576pub struct WalkEvent {
577    pub entering: bool,
578    pub node: NodeId,
579}
580
581/// A depth-first walker over the subtree rooted at `root`. It holds ids
582/// only, so the tree may be mutated between steps as long as the node the
583/// walker stands on stays linked, which is what both parse phases rely on.
584#[derive(Debug, Clone)]
585pub struct Walker {
586    current: Option<NodeId>,
587    root: NodeId,
588    entering: bool,
589}
590
591impl Walker {
592    /// The next event, or `None` when the walk is done.
593    pub fn next(&mut self, tree: &Tree) -> Option<WalkEvent> {
594        let cur = self.current?;
595        let entering = self.entering;
596        let node = tree.get(cur);
597
598        if entering && node.is_container() {
599            if let Some(first) = node.first_child {
600                self.current = Some(first);
601                self.entering = true;
602            } else {
603                self.entering = false;
604            }
605        } else if cur == self.root {
606            self.current = None;
607        } else if let Some(next) = node.next {
608            self.current = Some(next);
609            self.entering = true;
610        } else {
611            self.current = node.parent;
612            self.entering = false;
613        }
614
615        Some(WalkEvent {
616            entering,
617            node: cur,
618        })
619    }
620
621    /// Reposition the walker.
622    pub fn resume_at(&mut self, node: NodeId, entering: bool) {
623        self.current = Some(node);
624        self.entering = entering;
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631
632    #[test]
633    fn splices_keep_the_links_consistent() {
634        let mut tree = Tree::new(NodeType::Document);
635        let doc = tree.root();
636        let a = tree.new_node(NodeType::Paragraph);
637        let b = tree.new_node(NodeType::Paragraph);
638        let c = tree.new_node(NodeType::Paragraph);
639        tree.append_child(doc, a);
640        tree.append_child(doc, c);
641        tree.insert_after(a, b);
642        assert_eq!(tree.children(doc), vec![a, b, c]);
643        tree.unlink(b);
644        assert_eq!(tree.children(doc), vec![a, c]);
645        assert_eq!(tree.get(b).parent, None);
646        tree.insert_before(a, b);
647        assert_eq!(tree.children(doc), vec![b, a, c]);
648        tree.prepend_child(doc, c);
649        assert_eq!(tree.children(doc), vec![c, b, a]);
650        assert_eq!(tree.get(doc).last_child, Some(a));
651    }
652
653    #[test]
654    fn the_walker_enters_and_exits_containers() {
655        let mut tree = Tree::new(NodeType::Document);
656        let doc = tree.root();
657        let p = tree.new_node(NodeType::Paragraph);
658        let t = tree.new_node(NodeType::Text);
659        tree.append_child(doc, p);
660        tree.append_child(p, t);
661        let mut walker = tree.walker(doc);
662        let mut events = Vec::new();
663        while let Some(event) = walker.next(&tree) {
664            events.push((event.entering, event.node));
665        }
666        assert_eq!(
667            events,
668            vec![(true, doc), (true, p), (true, t), (false, p), (false, doc)]
669        );
670    }
671}