1use crate::node::{Heading, Node};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
5#[repr(u8)]
6pub enum NodeKind {
7 Blockquote,
9 Break,
11 Callout,
13 Embed,
15 Definition,
17 Delete,
19 H1,
21 H2,
23 H3,
25 H4,
27 H5,
29 H6,
31 Emphasis,
33 Footnote,
35 FootnoteRef,
37 Html,
39 Yaml,
41 Toml,
43 Image,
45 ImageRef,
47 CodeInline,
49 MathInline,
51 Link,
53 LinkRef,
55 WikiLink,
57 Math,
59 List,
61 TableAlign,
63 TableRow,
65 TableCell,
67 Code,
69 Strong,
71 HorizontalRule,
73 MdxFlowExpression,
75 MdxJsxFlowElement,
77 MdxJsxTextElement,
79 MdxTextExpression,
81 MdxJsEsm,
83 Text,
85 Fragment,
87 Empty,
89}
90
91impl NodeKind {
92 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum AttrType {
187 String,
189 Integer,
191 Boolean,
193 Nodes,
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct AttrSpec {
200 pub name: &'static str,
202 pub ty: AttrType,
204 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 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 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 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 fn sample_nodes() -> Vec<crate::Node> {
355 let markdown = "---\ntitle: a\n---\n\n# Heading *em* **strong** ~~del~~ `code` $x$ [link](http://a \"t\")  [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 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}