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.
20//!
21//! The public, mdast-adjacent AST is produced from this tree by `ast.rs`.
22//! That projection is lossy on purpose (it drops raw inline HTML boundaries
23//! and source positions); the tree is what `html.rs` renders for CommonMark
24//! conformance.
25
26/// The node kinds. String-valued in the other two runtimes so that debug
27/// output and the AST projection read the same; [`NodeType::as_str`] is
28/// the same spelling here.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum NodeType {
31    // Containers.
32    Document,
33    BlockQuote,
34    List,
35    Item,
36    // Leaf blocks.
37    Paragraph,
38    Heading,
39    ThematicBreak,
40    CodeBlock,
41    HtmlBlock,
42    // GFM tables (extension): a leaf block as far as the spec's algorithm is
43    // concerned (no block-level element can be inserted in one) but a
44    // container as far as the tree is concerned, since its rows and cells
45    // are real nodes and its cells hold inlines.
46    Table,
47    TableRow,
48    TableCell,
49    // Inlines.
50    Text,
51    Softbreak,
52    Linebreak,
53    Code,
54    HtmlInline,
55    Emph,
56    Strong,
57    Link,
58    Image,
59    Del,
60}
61
62impl NodeType {
63    /// The canonical name, as the TypeScript union and the Go constants
64    /// spell it.
65    pub fn as_str(self) -> &'static str {
66        match self {
67            NodeType::Document => "document",
68            NodeType::BlockQuote => "block_quote",
69            NodeType::List => "list",
70            NodeType::Item => "item",
71            NodeType::Paragraph => "paragraph",
72            NodeType::Heading => "heading",
73            NodeType::ThematicBreak => "thematic_break",
74            NodeType::CodeBlock => "code_block",
75            NodeType::HtmlBlock => "html_block",
76            NodeType::Table => "table",
77            NodeType::TableRow => "table_row",
78            NodeType::TableCell => "table_cell",
79            NodeType::Text => "text",
80            NodeType::Softbreak => "softbreak",
81            NodeType::Linebreak => "linebreak",
82            NodeType::Code => "code",
83            NodeType::HtmlInline => "html_inline",
84            NodeType::Emph => "emph",
85            NodeType::Strong => "strong",
86            NodeType::Link => "link",
87            NodeType::Image => "image",
88            NodeType::Del => "del",
89        }
90    }
91
92    /// Containers may hold children; leaves carry only `literal`.
93    pub fn is_container(self) -> bool {
94        matches!(
95            self,
96            NodeType::Document
97                | NodeType::BlockQuote
98                | NodeType::List
99                | NodeType::Item
100                | NodeType::Paragraph
101                | NodeType::Heading
102                | NodeType::Table
103                | NodeType::TableRow
104                | NodeType::TableCell
105                | NodeType::Emph
106                | NodeType::Strong
107                | NodeType::Link
108                | NodeType::Image
109                | NodeType::Del
110        )
111    }
112}
113
114/// Per-column alignment of a GFM table, from the colons in its delimiter
115/// row: `:--` left, `--:` right, `:-:` center. A column with no colon is
116/// `None`, which is the canonical runtime's `null` and the Go port's
117/// `AlignNone`.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum Align {
120    Left,
121    Right,
122    Center,
123}
124
125impl Align {
126    /// The attribute value the renderer writes and the AST carries.
127    pub fn as_str(self) -> &'static str {
128        match self {
129            Align::Left => "left",
130            Align::Right => "right",
131            Align::Center => "center",
132        }
133    }
134}
135
136/// One column's alignment; `None` for a delimiter cell with no colon.
137pub type TableAlign = Option<Align>;
138
139/// Bullet or ordered.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum ListType {
142    Bullet,
143    Ordered,
144}
145
146impl ListType {
147    pub fn as_str(self) -> &'static str {
148        match self {
149            ListType::Bullet => "bullet",
150            ListType::Ordered => "ordered",
151        }
152    }
153}
154
155/// What sections 5.2 and 5.3 need to decide list identity and rendering.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct ListData {
158    pub list_type: ListType,
159    /// Tight lists omit the `<p>` wrapper around item paragraphs. Decided
160    /// at finalize.
161    pub tight: bool,
162    /// Ordered-list start number; ignored for bullet lists.
163    pub start: i64,
164    /// `.` or `)` for ordered lists; a change of delimiter starts a new list.
165    pub delimiter: String,
166    /// `-`, `+` or `*` for bullet lists; a change of char starts a new list.
167    pub bullet_char: String,
168    /// Columns of padding between the marker and the item content.
169    pub padding: usize,
170    /// Column at which the marker starts.
171    pub marker_offset: usize,
172}
173
174/// `[[startLine, startCol], [endLine, endCol]]`, all 1-based, with columns
175/// counted in characters (not bytes) as the spec counts them.
176pub type SourcePos = [[usize; 2]; 2];
177
178/// An index into a [`Tree`]'s arena.
179pub type NodeId = usize;
180
181/// One node of the tree.
182#[derive(Debug, Clone)]
183pub struct MdNode {
184    pub node_type: NodeType,
185
186    pub parent: Option<NodeId>,
187    pub first_child: Option<NodeId>,
188    pub last_child: Option<NodeId>,
189    pub prev: Option<NodeId>,
190    pub next: Option<NodeId>,
191
192    pub sourcepos: SourcePos,
193
194    /// Text payload for text / code / html_block / html_inline / code_block.
195    pub literal: String,
196
197    /// Heading level 1..6.
198    pub level: usize,
199
200    /// Link/image destination, already entity-decoded and
201    /// backslash-unescaped.
202    pub destination: String,
203    /// Link/image title, already entity-decoded and backslash-unescaped.
204    /// `None` is the canonical runtime's `null` (the Go port's `HasTitle`
205    /// false).
206    pub title: Option<String>,
207
208    /// Fenced code info string (raw, entity-decoded); `None` for indented
209    /// code, which is the canonical `null` and Go's `HasInfo` false.
210    pub info: Option<String>,
211    /// True for fenced code blocks, false for indented.
212    pub is_fenced: bool,
213    pub fence_char: u8,
214    pub fence_length: usize,
215    pub fence_offset: usize,
216
217    pub list_data: Option<ListData>,
218
219    /// GFM tables: one entry per column, in order, set on the **table** node
220    /// by the block phase from the delimiter row. Every row of the table,
221    /// header and body alike, has exactly this many cells, because short
222    /// rows are padded and long ones are truncated. `None` on every other
223    /// node type.
224    pub table_align: Option<Vec<TableAlign>>,
225
226    /// GFM tables: true on the one `table_row` that is the header row, which
227    /// is always the table's first child. mdast has no header flag and
228    /// relies on that convention, but the renderer needs to choose `<th>`
229    /// over `<td>` without walking back up to the table.
230    pub is_header_row: bool,
231
232    /// GFM task list items (`- [x] foo`): `Some(true)` / `Some(false)` for a
233    /// checked / unchecked item, `None` for an ordinary one. Set on `item`
234    /// nodes by the block phase when `gfm` is on, once the marker has been
235    /// consumed from the item's first paragraph. mdast's field and mdast's
236    /// semantics; `ast.rs` projects it straight through to
237    /// `listItem.checked`.
238    pub checked: Option<bool>,
239
240    /// The `gfm` parse option, recorded on the **document** node by the
241    /// block phase and meaningless anywhere else. The renderer defaults to
242    /// it when called without options, so a tree parsed as plain CommonMark
243    /// renders as plain CommonMark.
244    pub gfm: bool,
245
246    // --- block-phase bookkeeping, not part of the rendered tree ---
247    /// Open blocks accept further lines; closed ones are finalized.
248    pub open: bool,
249    /// Accumulated raw content, consumed by the inline phase.
250    pub string_content: String,
251    /// A block whose last line was blank cannot be lazily continued.
252    pub last_line_blank: bool,
253    pub last_line_checked: bool,
254}
255
256impl MdNode {
257    /// An open, unlinked node of the given type.
258    pub fn new(node_type: NodeType) -> Self {
259        MdNode {
260            node_type,
261            parent: None,
262            first_child: None,
263            last_child: None,
264            prev: None,
265            next: None,
266            sourcepos: [[0, 0], [0, 0]],
267            literal: String::new(),
268            level: 0,
269            destination: String::new(),
270            title: None,
271            info: None,
272            is_fenced: false,
273            fence_char: 0,
274            fence_length: 0,
275            fence_offset: 0,
276            list_data: None,
277            table_align: None,
278            is_header_row: false,
279            checked: None,
280            gfm: true,
281            open: true,
282            string_content: String::new(),
283            last_line_blank: false,
284            last_line_checked: false,
285        }
286    }
287
288    /// Containers may hold children; leaves carry only `literal`.
289    pub fn is_container(&self) -> bool {
290        self.node_type.is_container()
291    }
292}
293
294/// The arena holding one document's nodes, with the document at
295/// [`Tree::root`].
296#[derive(Debug, Clone)]
297pub struct Tree {
298    nodes: Vec<MdNode>,
299    root: NodeId,
300}
301
302impl Tree {
303    /// A tree holding only a fresh node of `root_type`, which becomes the
304    /// root.
305    pub fn new(root_type: NodeType) -> Self {
306        Tree {
307            nodes: vec![MdNode::new(root_type)],
308            root: 0,
309        }
310    }
311
312    /// The root node's id (the document, for a parse).
313    pub fn root(&self) -> NodeId {
314        self.root
315    }
316
317    /// Add an unlinked node to the arena and return its id.
318    pub fn add(&mut self, node: MdNode) -> NodeId {
319        self.nodes.push(node);
320        self.nodes.len() - 1
321    }
322
323    /// Add an open, unlinked node of `node_type`.
324    pub fn new_node(&mut self, node_type: NodeType) -> NodeId {
325        self.add(MdNode::new(node_type))
326    }
327
328    pub fn get(&self, id: NodeId) -> &MdNode {
329        &self.nodes[id]
330    }
331
332    pub fn get_mut(&mut self, id: NodeId) -> &mut MdNode {
333        &mut self.nodes[id]
334    }
335
336    /// How many nodes the arena holds, unlinked ones included.
337    pub fn len(&self) -> usize {
338        self.nodes.len()
339    }
340
341    pub fn is_empty(&self) -> bool {
342        self.nodes.is_empty()
343    }
344
345    /// The children of `parent`, first to last.
346    pub fn children(&self, parent: NodeId) -> Vec<NodeId> {
347        let mut out = Vec::new();
348        let mut child = self.nodes[parent].first_child;
349        while let Some(c) = child {
350            out.push(c);
351            child = self.nodes[c].next;
352        }
353        out
354    }
355
356    /// Add `child` as the last child of `parent`, detaching it first.
357    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
358        self.unlink(child);
359        self.nodes[child].parent = Some(parent);
360        if let Some(last) = self.nodes[parent].last_child {
361            self.nodes[last].next = Some(child);
362            self.nodes[child].prev = Some(last);
363            self.nodes[parent].last_child = Some(child);
364        } else {
365            self.nodes[parent].first_child = Some(child);
366            self.nodes[parent].last_child = Some(child);
367        }
368    }
369
370    /// Add `child` as the first child of `parent`, detaching it first.
371    pub fn prepend_child(&mut self, parent: NodeId, child: NodeId) {
372        self.unlink(child);
373        self.nodes[child].parent = Some(parent);
374        if let Some(first) = self.nodes[parent].first_child {
375            self.nodes[first].prev = Some(child);
376            self.nodes[child].next = Some(first);
377            self.nodes[parent].first_child = Some(child);
378        } else {
379            self.nodes[parent].first_child = Some(child);
380            self.nodes[parent].last_child = Some(child);
381        }
382    }
383
384    /// Place `sibling` directly after `node`.
385    pub fn insert_after(&mut self, node: NodeId, sibling: NodeId) {
386        self.unlink(sibling);
387        let next = self.nodes[node].next;
388        self.nodes[sibling].next = next;
389        if let Some(n) = next {
390            self.nodes[n].prev = Some(sibling);
391        }
392        self.nodes[sibling].prev = Some(node);
393        self.nodes[node].next = Some(sibling);
394        let parent = self.nodes[node].parent;
395        self.nodes[sibling].parent = parent;
396        if next.is_none() {
397            if let Some(p) = parent {
398                self.nodes[p].last_child = Some(sibling);
399            }
400        }
401    }
402
403    /// Place `sibling` directly before `node`.
404    pub fn insert_before(&mut self, node: NodeId, sibling: NodeId) {
405        self.unlink(sibling);
406        let prev = self.nodes[node].prev;
407        self.nodes[sibling].prev = prev;
408        if let Some(p) = prev {
409            self.nodes[p].next = Some(sibling);
410        }
411        self.nodes[sibling].next = Some(node);
412        self.nodes[node].prev = Some(sibling);
413        let parent = self.nodes[node].parent;
414        self.nodes[sibling].parent = parent;
415        if prev.is_none() {
416            if let Some(p) = parent {
417                self.nodes[p].first_child = Some(sibling);
418            }
419        }
420    }
421
422    /// Detach `node` from the tree, leaving the node itself intact.
423    pub fn unlink(&mut self, node: NodeId) {
424        let (parent, prev, next) = {
425            let n = &self.nodes[node];
426            (n.parent, n.prev, n.next)
427        };
428        match prev {
429            Some(p) => self.nodes[p].next = next,
430            None => {
431                if let Some(par) = parent {
432                    self.nodes[par].first_child = next;
433                }
434            }
435        }
436        match next {
437            Some(n) => self.nodes[n].prev = prev,
438            None => {
439                if let Some(par) = parent {
440                    self.nodes[par].last_child = prev;
441                }
442            }
443        }
444        let n = &mut self.nodes[node];
445        n.parent = None;
446        n.next = None;
447        n.prev = None;
448    }
449
450    /// A depth-first walker rooted at `root`. Containers are entered and
451    /// exited; leaves produce one event.
452    pub fn walker(&self, root: NodeId) -> Walker {
453        Walker {
454            current: Some(root),
455            root,
456            entering: true,
457        }
458    }
459}
460
461/// One step of a depth-first walk.
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub struct WalkEvent {
464    pub entering: bool,
465    pub node: NodeId,
466}
467
468/// A depth-first walker over the subtree rooted at `root`. It holds ids
469/// only, so the tree may be mutated between steps as long as the node the
470/// walker stands on stays linked, which is what both parse phases rely on.
471#[derive(Debug, Clone)]
472pub struct Walker {
473    current: Option<NodeId>,
474    root: NodeId,
475    entering: bool,
476}
477
478impl Walker {
479    /// The next event, or `None` when the walk is done.
480    pub fn next(&mut self, tree: &Tree) -> Option<WalkEvent> {
481        let cur = self.current?;
482        let entering = self.entering;
483        let node = tree.get(cur);
484
485        if entering && node.is_container() {
486            if let Some(first) = node.first_child {
487                self.current = Some(first);
488                self.entering = true;
489            } else {
490                self.entering = false;
491            }
492        } else if cur == self.root {
493            self.current = None;
494        } else if let Some(next) = node.next {
495            self.current = Some(next);
496            self.entering = true;
497        } else {
498            self.current = node.parent;
499            self.entering = false;
500        }
501
502        Some(WalkEvent {
503            entering,
504            node: cur,
505        })
506    }
507
508    /// Reposition the walker.
509    pub fn resume_at(&mut self, node: NodeId, entering: bool) {
510        self.current = Some(node);
511        self.entering = entering;
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    #[test]
520    fn splices_keep_the_links_consistent() {
521        let mut tree = Tree::new(NodeType::Document);
522        let doc = tree.root();
523        let a = tree.new_node(NodeType::Paragraph);
524        let b = tree.new_node(NodeType::Paragraph);
525        let c = tree.new_node(NodeType::Paragraph);
526        tree.append_child(doc, a);
527        tree.append_child(doc, c);
528        tree.insert_after(a, b);
529        assert_eq!(tree.children(doc), vec![a, b, c]);
530        tree.unlink(b);
531        assert_eq!(tree.children(doc), vec![a, c]);
532        assert_eq!(tree.get(b).parent, None);
533        tree.insert_before(a, b);
534        assert_eq!(tree.children(doc), vec![b, a, c]);
535        tree.prepend_child(doc, c);
536        assert_eq!(tree.children(doc), vec![c, b, a]);
537        assert_eq!(tree.get(doc).last_child, Some(a));
538    }
539
540    #[test]
541    fn the_walker_enters_and_exits_containers() {
542        let mut tree = Tree::new(NodeType::Document);
543        let doc = tree.root();
544        let p = tree.new_node(NodeType::Paragraph);
545        let t = tree.new_node(NodeType::Text);
546        tree.append_child(doc, p);
547        tree.append_child(p, t);
548        let mut walker = tree.walker(doc);
549        let mut events = Vec::new();
550        while let Some(event) = walker.next(&tree) {
551            events.push((event.entering, event.node));
552        }
553        assert_eq!(
554            events,
555            vec![(true, doc), (true, p), (true, t), (false, p), (false, doc)]
556        );
557    }
558}