Skip to main content

mq_markdown/
node_kind.rs

1use crate::node::{Heading, Node};
2
3/// The kind of a [`Node`]. Headings are split by depth, so every `Node` has exactly one kind.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
5#[repr(u8)]
6pub enum NodeKind {
7    /// A block quote.
8    Blockquote,
9    /// A hard line break.
10    Break,
11    /// An Obsidian-style callout.
12    Callout,
13    /// An Obsidian-style file embed.
14    Embed,
15    /// A link reference definition.
16    Definition,
17    /// Strikethrough text.
18    Delete,
19    /// A heading of depth 1.
20    H1,
21    /// A heading of depth 2.
22    H2,
23    /// A heading of depth 3.
24    H3,
25    /// A heading of depth 4.
26    H4,
27    /// A heading of depth 5.
28    H5,
29    /// A heading of depth 6.
30    H6,
31    /// Emphasized text.
32    Emphasis,
33    /// A footnote definition.
34    Footnote,
35    /// A footnote reference.
36    FootnoteRef,
37    /// Raw HTML.
38    Html,
39    /// YAML front matter.
40    Yaml,
41    /// TOML front matter.
42    Toml,
43    /// An inline image.
44    Image,
45    /// A reference-style image.
46    ImageRef,
47    /// Inline code.
48    CodeInline,
49    /// Inline math.
50    MathInline,
51    /// An inline link.
52    Link,
53    /// A reference-style link.
54    LinkRef,
55    /// An Obsidian-style wikilink.
56    WikiLink,
57    /// A math block.
58    Math,
59    /// A list item.
60    List,
61    /// The delimiter row of a table, giving the column alignments.
62    TableAlign,
63    /// A table row.
64    TableRow,
65    /// A table cell.
66    TableCell,
67    /// A code block.
68    Code,
69    /// Strongly emphasized text.
70    Strong,
71    /// A thematic break.
72    HorizontalRule,
73    /// A block-level MDX expression.
74    MdxFlowExpression,
75    /// A block-level JSX element.
76    MdxJsxFlowElement,
77    /// An inline JSX element.
78    MdxJsxTextElement,
79    /// An inline MDX expression.
80    MdxTextExpression,
81    /// MDX ESM `import` or `export`.
82    MdxJsEsm,
83    /// Plain text.
84    Text,
85    /// A sequence of nodes with no wrapper.
86    Fragment,
87    /// An empty node.
88    Empty,
89}
90
91impl NodeKind {
92    /// Every kind, in declaration order.
93    pub const ALL: [NodeKind; 41] = [
94        Self::Blockquote,
95        Self::Break,
96        Self::Callout,
97        Self::Embed,
98        Self::Definition,
99        Self::Delete,
100        Self::H1,
101        Self::H2,
102        Self::H3,
103        Self::H4,
104        Self::H5,
105        Self::H6,
106        Self::Emphasis,
107        Self::Footnote,
108        Self::FootnoteRef,
109        Self::Html,
110        Self::Yaml,
111        Self::Toml,
112        Self::Image,
113        Self::ImageRef,
114        Self::CodeInline,
115        Self::MathInline,
116        Self::Link,
117        Self::LinkRef,
118        Self::WikiLink,
119        Self::Math,
120        Self::List,
121        Self::TableAlign,
122        Self::TableRow,
123        Self::TableCell,
124        Self::Code,
125        Self::Strong,
126        Self::HorizontalRule,
127        Self::MdxFlowExpression,
128        Self::MdxJsxFlowElement,
129        Self::MdxJsxTextElement,
130        Self::MdxTextExpression,
131        Self::MdxJsEsm,
132        Self::Text,
133        Self::Fragment,
134        Self::Empty,
135    ];
136
137    /// The name `to_md_name` returns for a node of this kind.
138    pub const fn name(self) -> &'static str {
139        match self {
140            Self::Blockquote => "blockquote",
141            Self::Break => "break",
142            Self::Callout => "callout",
143            Self::Embed => "embed",
144            Self::Definition => "definition",
145            Self::Delete => "delete",
146            Self::H1 => "h1",
147            Self::H2 => "h2",
148            Self::H3 => "h3",
149            Self::H4 => "h4",
150            Self::H5 => "h5",
151            Self::H6 => "h6",
152            Self::Emphasis => "emphasis",
153            Self::Footnote => "footnote",
154            Self::FootnoteRef => "footnoteref",
155            Self::Html => "html",
156            Self::Yaml => "yaml",
157            Self::Toml => "toml",
158            Self::Image => "image",
159            Self::ImageRef => "image_ref",
160            Self::CodeInline => "code_inline",
161            Self::MathInline => "math_inline",
162            Self::Link => "link",
163            Self::LinkRef => "link_ref",
164            Self::WikiLink => "wikilink",
165            Self::Math => "math",
166            Self::List => "list",
167            Self::TableAlign => "table_align",
168            Self::TableRow => "table_row",
169            Self::TableCell => "table_cell",
170            Self::Code => "code",
171            Self::Strong => "strong",
172            Self::HorizontalRule => "Horizontal_rule",
173            Self::MdxFlowExpression => "mdx_flow_expression",
174            Self::MdxJsxFlowElement => "mdx_jsx_flow_element",
175            Self::MdxJsxTextElement => "mdx_jsx_text_element",
176            Self::MdxTextExpression => "mdx_text_expression",
177            Self::MdxJsEsm => "mdx_js_esm",
178            Self::Text => "text",
179            Self::Fragment | Self::Empty => "",
180        }
181    }
182}
183
184/// The type of a node attribute as returned by [`Node::attr`](crate::Node::attr).
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum AttrType {
187    /// A string.
188    String,
189    /// An integer.
190    Integer,
191    /// A boolean.
192    Boolean,
193    /// An array of nodes.
194    Nodes,
195}
196
197/// An attribute a node kind has, with its type. `optional` attributes are `none` when absent.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct AttrSpec {
200    /// The element name, or `None` for a fragment.
201    pub name: &'static str,
202    /// The type of the attribute.
203    pub ty: AttrType,
204    /// Whether the attribute is `none` when absent.
205    pub optional: bool,
206}
207
208const fn attr(name: &'static str, ty: AttrType) -> AttrSpec {
209    AttrSpec {
210        name,
211        ty,
212        optional: false,
213    }
214}
215
216const fn optional(name: &'static str, ty: AttrType) -> AttrSpec {
217    AttrSpec {
218        name,
219        ty,
220        optional: true,
221    }
222}
223
224const VALUE: AttrSpec = attr("value", AttrType::String);
225const VALUES: AttrSpec = attr("values", AttrType::Nodes);
226const CHILDREN: AttrSpec = attr("children", AttrType::Nodes);
227const IDENT: AttrSpec = attr("ident", AttrType::String);
228const URL: AttrSpec = attr("url", AttrType::String);
229const LABEL: AttrSpec = optional("label", AttrType::String);
230const TITLE: AttrSpec = optional("title", AttrType::String);
231const ALT: AttrSpec = attr("alt", AttrType::String);
232const NAME: AttrSpec = optional("name", AttrType::String);
233const ALIGN: AttrSpec = attr("align", AttrType::String);
234const CHECKED: AttrSpec = optional("checked", AttrType::Boolean);
235const COLUMN: AttrSpec = attr("column", AttrType::Integer);
236const DEPTH: AttrSpec = attr("depth", AttrType::Integer);
237const FENCE: AttrSpec = attr("fence", AttrType::Boolean);
238const INDEX: AttrSpec = attr("index", AttrType::Integer);
239const KIND: AttrSpec = attr("kind", AttrType::String);
240const LANG: AttrSpec = optional("lang", AttrType::String);
241const LEVEL: AttrSpec = attr("level", AttrType::Integer);
242const META: AttrSpec = optional("meta", AttrType::String);
243const ORDERED: AttrSpec = attr("ordered", AttrType::Boolean);
244const ROW: AttrSpec = attr("row", AttrType::Integer);
245const LINE: AttrSpec = optional("line", AttrType::Integer);
246const END_LINE: AttrSpec = optional("end_line", AttrType::Integer);
247
248impl NodeKind {
249    /// The attributes of this kind, including `line` and `end_line` (absent for nodes
250    /// without a position). Mirrors [`Node::attr`](crate::Node::attr).
251    pub const fn attrs(self) -> &'static [AttrSpec] {
252        match self {
253            Self::Footnote => &[LINE, END_LINE, IDENT, VALUE, VALUES, CHILDREN],
254            Self::Html
255            | Self::Text
256            | Self::CodeInline
257            | Self::MathInline
258            | Self::Math
259            | Self::Yaml
260            | Self::Toml
261            | Self::MdxFlowExpression
262            | Self::MdxTextExpression
263            | Self::MdxJsEsm => &[LINE, END_LINE, VALUE],
264            Self::Code => &[LINE, END_LINE, VALUE, LANG, META, FENCE],
265            Self::Image => &[LINE, END_LINE, ALT, URL, TITLE],
266            Self::ImageRef => &[LINE, END_LINE, ALT, IDENT, LABEL],
267            Self::Link => &[LINE, END_LINE, URL, TITLE, VALUE, VALUES, CHILDREN],
268            Self::WikiLink | Self::Embed => &[LINE, END_LINE, URL, VALUE],
269            Self::Callout => &[LINE, END_LINE, KIND, TITLE, VALUE, VALUES, CHILDREN],
270            Self::LinkRef | Self::FootnoteRef => &[LINE, END_LINE, IDENT, LABEL],
271            Self::Definition => &[LINE, END_LINE, IDENT, URL, TITLE, LABEL],
272            Self::H1 | Self::H2 | Self::H3 | Self::H4 | Self::H5 | Self::H6 => {
273                &[LINE, END_LINE, DEPTH, LEVEL, VALUE, VALUES, CHILDREN]
274            }
275            Self::List => &[LINE, END_LINE, INDEX, LEVEL, ORDERED, CHECKED, VALUE, VALUES, CHILDREN],
276            Self::TableCell => &[LINE, END_LINE, COLUMN, ROW, VALUE, VALUES, CHILDREN],
277            Self::TableAlign => &[LINE, END_LINE, ALIGN],
278            Self::MdxJsxFlowElement | Self::MdxJsxTextElement => &[LINE, END_LINE, NAME, VALUES, CHILDREN],
279            Self::Strong | Self::Blockquote | Self::Delete | Self::Emphasis | Self::TableRow | Self::Fragment => {
280                &[LINE, END_LINE, VALUE, VALUES, CHILDREN]
281            }
282            Self::Break | Self::HorizontalRule | Self::Empty => &[LINE, END_LINE],
283        }
284    }
285
286    /// The attribute `name` of this kind, if it has one.
287    pub fn attr_spec(self, name: &str) -> Option<AttrSpec> {
288        self.attrs().iter().copied().find(|spec| spec.name == name)
289    }
290}
291
292impl Node {
293    /// The kind of this node. A heading depth outside `1..=6`, which parsing never produces,
294    /// is clamped.
295    pub fn kind(&self) -> NodeKind {
296        match self {
297            Node::Blockquote(_) => NodeKind::Blockquote,
298            Node::Break(_) => NodeKind::Break,
299            #[cfg(feature = "callout")]
300            Node::Callout(_) => NodeKind::Callout,
301            #[cfg(feature = "embed")]
302            Node::Embed(_) => NodeKind::Embed,
303            Node::Definition(_) => NodeKind::Definition,
304            Node::Delete(_) => NodeKind::Delete,
305            Node::Heading(Heading { depth, .. }) => match depth.get() {
306                1 => NodeKind::H1,
307                2 => NodeKind::H2,
308                3 => NodeKind::H3,
309                4 => NodeKind::H4,
310                5 => NodeKind::H5,
311                _ => NodeKind::H6,
312            },
313            Node::Emphasis(_) => NodeKind::Emphasis,
314            Node::Footnote(_) => NodeKind::Footnote,
315            Node::FootnoteRef(_) => NodeKind::FootnoteRef,
316            Node::Html(_) => NodeKind::Html,
317            Node::Yaml(_) => NodeKind::Yaml,
318            Node::Toml(_) => NodeKind::Toml,
319            Node::Image(_) => NodeKind::Image,
320            Node::ImageRef(_) => NodeKind::ImageRef,
321            Node::CodeInline(_) => NodeKind::CodeInline,
322            Node::MathInline(_) => NodeKind::MathInline,
323            Node::Link(_) => NodeKind::Link,
324            Node::LinkRef(_) => NodeKind::LinkRef,
325            #[cfg(feature = "wikilink")]
326            Node::WikiLink(_) => NodeKind::WikiLink,
327            Node::Math(_) => NodeKind::Math,
328            Node::List(_) => NodeKind::List,
329            Node::TableAlign(_) => NodeKind::TableAlign,
330            Node::TableRow(_) => NodeKind::TableRow,
331            Node::TableCell(_) => NodeKind::TableCell,
332            Node::Code(_) => NodeKind::Code,
333            Node::Strong(_) => NodeKind::Strong,
334            Node::HorizontalRule(_) => NodeKind::HorizontalRule,
335            Node::MdxFlowExpression(_) => NodeKind::MdxFlowExpression,
336            Node::MdxJsxFlowElement(_) => NodeKind::MdxJsxFlowElement,
337            Node::MdxJsxTextElement(_) => NodeKind::MdxJsxTextElement,
338            Node::MdxTextExpression(_) => NodeKind::MdxTextExpression,
339            Node::MdxJsEsm(_) => NodeKind::MdxJsEsm,
340            Node::Text(_) => NodeKind::Text,
341            Node::Fragment(_) => NodeKind::Fragment,
342            Node::Empty => NodeKind::Empty,
343        }
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use rstest::rstest;
350
351    use super::*;
352
353    /// A document with a node of most kinds, and every node reachable through `children`.
354    fn sample_nodes() -> Vec<crate::Node> {
355        let markdown = "---\ntitle: a\n---\n\n# Heading *em* **strong** ~~del~~ `code` $x$ [link](http://a \"t\") ![img](http://b) [ref][r] ![iref][r] [^1]\n\n[^1]: note\n\n[r]: http://c\n\n> quote\n\n- a\n- [x] done\n- [ ] todo\n\n1. one\n\n```rust\nfn f() {}\n```\n\n```\nplain\n```\n\n| a | b |\n|:--|--:|\n| 1 | 2 |\n\n---\n\n<div>x</div>\n\nline  \nbreak\n\n$$\nm\n$$\n";
356        let mut nodes: Vec<crate::Node> = markdown.parse::<crate::Markdown>().unwrap().nodes;
357        let mut all = Vec::new();
358        while let Some(node) = nodes.pop() {
359            if let Some(crate::node::attr_value::AttrValue::Array(children)) = node.attr("children") {
360                nodes.extend(children);
361            }
362            all.push(node);
363        }
364        all
365    }
366
367    /// Every attribute name any kind has.
368    fn attr_names() -> std::collections::BTreeSet<&'static str> {
369        NodeKind::ALL
370            .iter()
371            .flat_map(|kind| kind.attrs())
372            .map(|spec| spec.name)
373            .collect()
374    }
375
376    #[test]
377    fn test_attr_table_agrees_with_node_attr() {
378        use crate::node::attr_value::AttrValue;
379
380        let nodes = sample_nodes();
381        let kinds: std::collections::BTreeSet<_> = nodes.iter().map(|node| node.kind()).collect();
382        assert!(kinds.len() > 20, "sample covers too few kinds: {kinds:?}");
383
384        for node in &nodes {
385            let kind = node.kind();
386            for name in attr_names() {
387                let value = node.attr(name);
388                match kind.attr_spec(name) {
389                    None => assert!(
390                        value.is_none(),
391                        "{kind:?} returns `{name}` but the table does not list it"
392                    ),
393                    Some(spec) => {
394                        let Some(value) = value else {
395                            assert!(spec.optional, "{kind:?} lacks `{name}`, which is not optional");
396                            continue;
397                        };
398                        let ty = match value {
399                            AttrValue::String(_) => AttrType::String,
400                            AttrValue::Integer(_) => AttrType::Integer,
401                            AttrValue::Boolean(_) => AttrType::Boolean,
402                            AttrValue::Array(_) => AttrType::Nodes,
403                            other => panic!("unexpected {other:?} for `{name}`"),
404                        };
405                        assert_eq!(ty, spec.ty, "{kind:?}.{name}");
406                    }
407                }
408            }
409        }
410    }
411
412    #[test]
413    fn test_all_lists_every_kind_once() {
414        let mut seen = std::collections::HashSet::new();
415        assert!(NodeKind::ALL.iter().all(|kind| seen.insert(*kind)));
416        assert_eq!(
417            NodeKind::ALL.iter().map(|k| *k as usize).max(),
418            Some(NodeKind::ALL.len() - 1)
419        );
420    }
421
422    #[rstest]
423    #[case("# a", NodeKind::H1)]
424    #[case("### a", NodeKind::H3)]
425    #[case("###### a", NodeKind::H6)]
426    #[case("```rust\nfn f() {}\n```", NodeKind::Code)]
427    #[case("- a", NodeKind::List)]
428    #[case("> a", NodeKind::Blockquote)]
429    #[case("---", NodeKind::HorizontalRule)]
430    fn test_kind_agrees_with_name(#[case] markdown: &str, #[case] kind: NodeKind) {
431        let node = markdown
432            .parse::<crate::Markdown>()
433            .unwrap()
434            .nodes
435            .into_iter()
436            .next()
437            .unwrap();
438        assert_eq!(node.kind(), kind);
439        assert_eq!(node.name().as_str(), kind.name());
440    }
441}