Skip to main content

lsdocs_doctree/
lib.rs

1//! Document tree (AST) types: nodes, spans and metadata.
2//!
3//! A [`Document`] is what a parser produces and what transformers and
4//! renderers consume. Every type here crosses process boundaries, so the
5//! serialized shape is part of the public API:
6//!
7//! - Nodes are tagged by a `type` field, e.g. `{"type": "heading", "level": 1,
8//!   "children": [...]}`.
9//! - Field names are `snake_case`.
10//! - Optional fields are omitted when empty, and unknown fields are ignored
11//!   when reading, so new fields can be added without breaking older plugins.
12//!
13//! Formats without a core node kind use [`Node::Custom`].
14//!
15//! ## The shape every parser produces
16//!
17//! Parsers for any source format hand transformers the same shape:
18//!
19//! - **Sections nest.** Content under a title is wrapped in a
20//!   [`Node::Section`] whose first child is the title [`Heading`], with
21//!   subsections nested inside it. A section's anchor id is
22//!   [`Section::id`]; [`Heading::id`] is only for headings outside the
23//!   section tree (e.g. inside a block quote). Content before the first
24//!   title stays at the top level.
25//! - **Ids are explicit or left out.** Parsers set ids the author wrote
26//!   (e.g. `{#id}` in Markdown, labels in reStructuredText). The host gives
27//!   every other section a unique id derived from its title after parsing.
28//! - **Cross-document links carry a [`LinkTarget`].** The host fills it in
29//!   for relative links to other documents; parsers set it for references
30//!   that are not paths, such as labels.
31
32use std::collections::BTreeMap;
33
34use serde::{Deserialize, Serialize};
35
36/// An arbitrary structured value, as found in front matter or plugin data.
37pub type Value = serde_json::Value;
38
39/// Document-level metadata, such as front matter.
40pub type Metadata = BTreeMap<String, Value>;
41
42/// A byte range within the document's source text.
43///
44/// Offsets count UTF-8 bytes from the start of the source, and `end` is
45/// exclusive. The source file is the enclosing [`Document::source`].
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
47#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
48pub struct Span {
49    /// Offset of the first byte.
50    pub start: u32,
51    /// Offset one past the last byte.
52    pub end: u32,
53}
54
55impl Span {
56    /// Creates a span from `start` (inclusive) to `end` (exclusive).
57    pub const fn new(start: u32, end: u32) -> Self {
58        Self { start, end }
59    }
60}
61
62/// A parsed source document.
63#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
64#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
65pub struct Document {
66    /// Path of the source file, relative to the site's source directory,
67    /// with `/` separators.
68    pub source: String,
69    /// Front matter and other document-level data.
70    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
71    pub metadata: Metadata,
72    /// Top-level nodes.
73    #[serde(default)]
74    pub children: Vec<Node>,
75}
76
77impl Document {
78    /// Creates an empty document for the given source path.
79    pub fn new(source: impl Into<String>) -> Self {
80        Self {
81            source: source.into(),
82            ..Self::default()
83        }
84    }
85
86    /// Iterates over every node in the document, depth first, parents before
87    /// children.
88    pub fn descendants(&self) -> Descendants<'_> {
89        Descendants {
90            stack: self.children.iter().rev().collect(),
91        }
92    }
93
94    /// The document's title: its `title` metadata if that is a string, else
95    /// the text of its first heading.
96    pub fn title(&self) -> Option<String> {
97        self.metadata
98            .get("title")
99            .and_then(Value::as_str)
100            .map(str::to_owned)
101            .or_else(|| {
102                self.descendants().find_map(|n| match n {
103                    Node::Heading(h) => Some(plain_text(&h.children)),
104                    _ => None,
105                })
106            })
107    }
108}
109
110/// The text of `nodes` without markup: text, inline code and image alt
111/// text, in order.
112pub fn plain_text(nodes: &[Node]) -> String {
113    let mut out = String::new();
114    for node in nodes {
115        match node {
116            Node::Text(t) => out.push_str(&t.value),
117            Node::InlineCode(c) => out.push_str(&c.value),
118            Node::Image(i) => out.push_str(&i.alt),
119            other => out.push_str(&plain_text(other.children())),
120        }
121    }
122    out
123}
124
125/// Depth-first iterator returned by [`Document::descendants`] and
126/// [`Node::descendants`].
127#[derive(Debug, Clone)]
128pub struct Descendants<'a> {
129    stack: Vec<&'a Node>,
130}
131
132impl<'a> Iterator for Descendants<'a> {
133    type Item = &'a Node;
134
135    fn next(&mut self) -> Option<Self::Item> {
136        let node = self.stack.pop()?;
137        self.stack.extend(node.children().iter().rev());
138        Some(node)
139    }
140}
141
142/// A node in the document tree.
143///
144/// Serialized with a `type` tag holding the [`Node::kind`] name, for core
145/// kinds, followed by the variant's fields.
146// Deserializing is hand-written (see the `de` module) because serde's
147// derived decoder for internally tagged enums buffers every node before
148// reading it, which made decoding several times slower than encoding.
149#[derive(Debug, Clone, PartialEq, Serialize)]
150#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
151#[serde(tag = "type", rename_all = "snake_case")]
152pub enum Node {
153    /// A titled section; by convention its first child is a [`Heading`].
154    Section(Section),
155    /// A heading.
156    Heading(Heading),
157    /// A paragraph.
158    Paragraph(Paragraph),
159    /// A bulleted or numbered list whose children are list items.
160    List(List),
161    /// An item of a [`List`].
162    ListItem(ListItem),
163    /// A block quote.
164    BlockQuote(BlockQuote),
165    /// A block of code or preformatted text.
166    CodeBlock(CodeBlock),
167    /// A table whose children are table rows.
168    Table(Table),
169    /// A row of a [`Table`] whose children are table cells.
170    TableRow(TableRow),
171    /// A cell of a [`TableRow`].
172    TableCell(TableCell),
173    /// A horizontal rule.
174    ThematicBreak(ThematicBreak),
175    /// Content passed through verbatim to renderers of a matching format,
176    /// such as inline HTML in Markdown.
177    Raw(Raw),
178    /// Plain text.
179    Text(Text),
180    /// Emphasized (usually italic) text.
181    Emphasis(Emphasis),
182    /// Strongly emphasized (usually bold) text.
183    Strong(Strong),
184    /// Inline code.
185    InlineCode(InlineCode),
186    /// A hyperlink.
187    Link(Link),
188    /// An image.
189    Image(Image),
190    /// A hard line break.
191    LineBreak(LineBreak),
192    /// A callout such as a note or warning.
193    Admonition(Admonition),
194    /// A list of terms and their descriptions: children alternate between
195    /// [`Node::DefinitionTerm`] and one or more
196    /// [`Node::DefinitionDescription`]s.
197    DefinitionList(DefinitionList),
198    /// A term in a [`DefinitionList`].
199    DefinitionTerm(DefinitionTerm),
200    /// The description of the term before it in a [`DefinitionList`].
201    DefinitionDescription(DefinitionDescription),
202    /// A reference to a footnote, e.g. `[^1]`.
203    FootnoteReference(FootnoteReference),
204    /// The text of a footnote.
205    FootnoteDefinition(FootnoteDefinition),
206    /// A mathematical formula, inline or on its own line.
207    Math(Math),
208    /// Content (usually an image) with an optional [`Node::Caption`] as its
209    /// last child.
210    Figure(Figure),
211    /// The caption of a [`Figure`].
212    Caption(Caption),
213    /// A link target with no content of its own, e.g. a reStructuredText
214    /// label in front of a paragraph.
215    Anchor(Anchor),
216    /// A node kind defined by a plugin rather than by lsdocs.
217    Custom(Custom),
218}
219
220impl Node {
221    /// The name plugins use to select this node, e.g. in transformer
222    /// capabilities: the `type` tag for core kinds (`"heading"`), or
223    /// `"custom:<kind>"` for custom nodes.
224    pub fn kind(&self) -> std::borrow::Cow<'static, str> {
225        use std::borrow::Cow::{Borrowed, Owned};
226        Borrowed(match self {
227            Node::Section(_) => "section",
228            Node::Heading(_) => "heading",
229            Node::Paragraph(_) => "paragraph",
230            Node::List(_) => "list",
231            Node::ListItem(_) => "list_item",
232            Node::BlockQuote(_) => "block_quote",
233            Node::CodeBlock(_) => "code_block",
234            Node::Table(_) => "table",
235            Node::TableRow(_) => "table_row",
236            Node::TableCell(_) => "table_cell",
237            Node::ThematicBreak(_) => "thematic_break",
238            Node::Raw(_) => "raw",
239            Node::Text(_) => "text",
240            Node::Emphasis(_) => "emphasis",
241            Node::Strong(_) => "strong",
242            Node::InlineCode(_) => "inline_code",
243            Node::Link(_) => "link",
244            Node::Image(_) => "image",
245            Node::LineBreak(_) => "line_break",
246            Node::Admonition(_) => "admonition",
247            Node::DefinitionList(_) => "definition_list",
248            Node::DefinitionTerm(_) => "definition_term",
249            Node::DefinitionDescription(_) => "definition_description",
250            Node::FootnoteReference(_) => "footnote_reference",
251            Node::FootnoteDefinition(_) => "footnote_definition",
252            Node::Math(_) => "math",
253            Node::Figure(_) => "figure",
254            Node::Caption(_) => "caption",
255            Node::Anchor(_) => "anchor",
256            Node::Custom(c) => return Owned(format!("custom:{}", c.kind)),
257        })
258    }
259
260    /// Where this node came from in the source, if known.
261    pub fn span(&self) -> Option<Span> {
262        match self {
263            Node::Section(n) => n.span,
264            Node::Heading(n) => n.span,
265            Node::Paragraph(n) => n.span,
266            Node::List(n) => n.span,
267            Node::ListItem(n) => n.span,
268            Node::BlockQuote(n) => n.span,
269            Node::CodeBlock(n) => n.span,
270            Node::Table(n) => n.span,
271            Node::TableRow(n) => n.span,
272            Node::TableCell(n) => n.span,
273            Node::ThematicBreak(n) => n.span,
274            Node::Raw(n) => n.span,
275            Node::Text(n) => n.span,
276            Node::Emphasis(n) => n.span,
277            Node::Strong(n) => n.span,
278            Node::InlineCode(n) => n.span,
279            Node::Link(n) => n.span,
280            Node::Image(n) => n.span,
281            Node::LineBreak(n) => n.span,
282            Node::Admonition(n) => n.span,
283            Node::DefinitionList(n) => n.span,
284            Node::DefinitionTerm(n) => n.span,
285            Node::DefinitionDescription(n) => n.span,
286            Node::FootnoteReference(n) => n.span,
287            Node::FootnoteDefinition(n) => n.span,
288            Node::Math(n) => n.span,
289            Node::Figure(n) => n.span,
290            Node::Caption(n) => n.span,
291            Node::Anchor(n) => n.span,
292            Node::Custom(n) => n.span,
293        }
294    }
295
296    /// Mutable access to where this node came from, e.g. to move spans
297    /// found in a piece of text to where that piece is in the source.
298    pub fn span_mut(&mut self) -> &mut Option<Span> {
299        match self {
300            Node::Section(n) => &mut n.span,
301            Node::Heading(n) => &mut n.span,
302            Node::Paragraph(n) => &mut n.span,
303            Node::List(n) => &mut n.span,
304            Node::ListItem(n) => &mut n.span,
305            Node::BlockQuote(n) => &mut n.span,
306            Node::CodeBlock(n) => &mut n.span,
307            Node::Table(n) => &mut n.span,
308            Node::TableRow(n) => &mut n.span,
309            Node::TableCell(n) => &mut n.span,
310            Node::ThematicBreak(n) => &mut n.span,
311            Node::Raw(n) => &mut n.span,
312            Node::Text(n) => &mut n.span,
313            Node::Emphasis(n) => &mut n.span,
314            Node::Strong(n) => &mut n.span,
315            Node::InlineCode(n) => &mut n.span,
316            Node::Link(n) => &mut n.span,
317            Node::Image(n) => &mut n.span,
318            Node::LineBreak(n) => &mut n.span,
319            Node::Admonition(n) => &mut n.span,
320            Node::DefinitionList(n) => &mut n.span,
321            Node::DefinitionTerm(n) => &mut n.span,
322            Node::DefinitionDescription(n) => &mut n.span,
323            Node::FootnoteReference(n) => &mut n.span,
324            Node::FootnoteDefinition(n) => &mut n.span,
325            Node::Math(n) => &mut n.span,
326            Node::Figure(n) => &mut n.span,
327            Node::Caption(n) => &mut n.span,
328            Node::Anchor(n) => &mut n.span,
329            Node::Custom(n) => &mut n.span,
330        }
331    }
332
333    /// This node's children; empty for leaf kinds.
334    pub fn children(&self) -> &[Node] {
335        match self {
336            Node::Section(n) => &n.children,
337            Node::Heading(n) => &n.children,
338            Node::Paragraph(n) => &n.children,
339            Node::List(n) => &n.children,
340            Node::ListItem(n) => &n.children,
341            Node::BlockQuote(n) => &n.children,
342            Node::Table(n) => &n.children,
343            Node::TableRow(n) => &n.children,
344            Node::TableCell(n) => &n.children,
345            Node::Emphasis(n) => &n.children,
346            Node::Strong(n) => &n.children,
347            Node::Link(n) => &n.children,
348            Node::Admonition(n) => &n.children,
349            Node::DefinitionList(n) => &n.children,
350            Node::DefinitionTerm(n) => &n.children,
351            Node::DefinitionDescription(n) => &n.children,
352            Node::FootnoteDefinition(n) => &n.children,
353            Node::Figure(n) => &n.children,
354            Node::Caption(n) => &n.children,
355            Node::Custom(n) => &n.children,
356            Node::CodeBlock(_)
357            | Node::ThematicBreak(_)
358            | Node::Raw(_)
359            | Node::Text(_)
360            | Node::InlineCode(_)
361            | Node::Image(_)
362            | Node::LineBreak(_)
363            | Node::FootnoteReference(_)
364            | Node::Math(_)
365            | Node::Anchor(_) => &[],
366        }
367    }
368
369    /// Mutable access to this node's children, or `None` for leaf kinds.
370    pub fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
371        match self {
372            Node::Section(n) => Some(&mut n.children),
373            Node::Heading(n) => Some(&mut n.children),
374            Node::Paragraph(n) => Some(&mut n.children),
375            Node::List(n) => Some(&mut n.children),
376            Node::ListItem(n) => Some(&mut n.children),
377            Node::BlockQuote(n) => Some(&mut n.children),
378            Node::Table(n) => Some(&mut n.children),
379            Node::TableRow(n) => Some(&mut n.children),
380            Node::TableCell(n) => Some(&mut n.children),
381            Node::Emphasis(n) => Some(&mut n.children),
382            Node::Strong(n) => Some(&mut n.children),
383            Node::Link(n) => Some(&mut n.children),
384            Node::Admonition(n) => Some(&mut n.children),
385            Node::DefinitionList(n) => Some(&mut n.children),
386            Node::DefinitionTerm(n) => Some(&mut n.children),
387            Node::DefinitionDescription(n) => Some(&mut n.children),
388            Node::FootnoteDefinition(n) => Some(&mut n.children),
389            Node::Figure(n) => Some(&mut n.children),
390            Node::Caption(n) => Some(&mut n.children),
391            Node::Custom(n) => Some(&mut n.children),
392            Node::CodeBlock(_)
393            | Node::ThematicBreak(_)
394            | Node::Raw(_)
395            | Node::Text(_)
396            | Node::InlineCode(_)
397            | Node::Image(_)
398            | Node::LineBreak(_)
399            | Node::FootnoteReference(_)
400            | Node::Math(_)
401            | Node::Anchor(_) => None,
402        }
403    }
404
405    /// Iterates over this node and everything below it, depth first.
406    pub fn descendants(&self) -> Descendants<'_> {
407        Descendants { stack: vec![self] }
408    }
409}
410
411mod de {
412    //! A [`Deserialize`] for [`Node`] that reads the `type` tag first, then
413    //! decodes the rest of the map straight into the variant's struct.
414    //!
415    //! Our encoder always writes `type` first, so this is the usual path. A
416    //! map whose first key is something else (e.g. a node built in Python or
417    //! JavaScript with its keys in another order) is buffered as JSON and
418    //! decoded from that.
419
420    use std::fmt;
421
422    use serde::de::value::MapAccessDeserializer;
423    use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
424
425    use super::*;
426
427    /// Decodes the variant named `tag` from `d`, a map without the tag.
428    macro_rules! variants {
429        ($tag:expr, $d:expr, $( $name:literal => $variant:ident ),* $(,)?) => {
430            match $tag {
431                $( $name => $variant::deserialize($d).map(Node::$variant), )*
432                other => Err(de::Error::unknown_variant(other, &[$($name),*])),
433            }
434        };
435    }
436
437    fn variant<'de, D: Deserializer<'de>>(tag: &str, d: D) -> Result<Node, D::Error> {
438        variants!(tag, d,
439            "section" => Section,
440            "heading" => Heading,
441            "paragraph" => Paragraph,
442            "list" => List,
443            "list_item" => ListItem,
444            "block_quote" => BlockQuote,
445            "code_block" => CodeBlock,
446            "table" => Table,
447            "table_row" => TableRow,
448            "table_cell" => TableCell,
449            "thematic_break" => ThematicBreak,
450            "raw" => Raw,
451            "text" => Text,
452            "emphasis" => Emphasis,
453            "strong" => Strong,
454            "inline_code" => InlineCode,
455            "link" => Link,
456            "image" => Image,
457            "line_break" => LineBreak,
458            "admonition" => Admonition,
459            "definition_list" => DefinitionList,
460            "definition_term" => DefinitionTerm,
461            "definition_description" => DefinitionDescription,
462            "footnote_reference" => FootnoteReference,
463            "footnote_definition" => FootnoteDefinition,
464            "math" => Math,
465            "figure" => Figure,
466            "caption" => Caption,
467            "anchor" => Anchor,
468            "custom" => Custom,
469        )
470    }
471
472    /// A map key, without allocating when it is `type`.
473    enum Key {
474        Type,
475        Other(String),
476    }
477
478    impl<'de> Deserialize<'de> for Key {
479        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
480            struct KeyVisitor;
481            impl Visitor<'_> for KeyVisitor {
482                type Value = Key;
483                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484                    f.write_str("a field name")
485                }
486                fn visit_str<E: de::Error>(self, v: &str) -> Result<Key, E> {
487                    Ok(if v == "type" {
488                        Key::Type
489                    } else {
490                        Key::Other(v.to_owned())
491                    })
492                }
493            }
494            d.deserialize_str(KeyVisitor)
495        }
496    }
497
498    /// A node's `type`, borrowed from the input when possible.
499    struct Tag<'de>(std::borrow::Cow<'de, str>);
500
501    impl<'de> Deserialize<'de> for Tag<'de> {
502        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
503            struct TagVisitor;
504            impl<'de> Visitor<'de> for TagVisitor {
505                type Value = Tag<'de>;
506                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507                    f.write_str("a node type")
508                }
509                fn visit_borrowed_str<E: de::Error>(self, v: &'de str) -> Result<Tag<'de>, E> {
510                    Ok(Tag(v.into()))
511                }
512                fn visit_str<E: de::Error>(self, v: &str) -> Result<Tag<'de>, E> {
513                    Ok(Tag(v.to_owned().into()))
514                }
515            }
516            d.deserialize_str(TagVisitor)
517        }
518    }
519
520    struct NodeVisitor;
521
522    impl<'de> Visitor<'de> for NodeVisitor {
523        type Value = Node;
524
525        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526            f.write_str("a document node: a map with a `type` field")
527        }
528
529        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
530            let first = match map.next_key::<Key>()? {
531                None => return Err(de::Error::missing_field("type")),
532                Some(Key::Type) => {
533                    let Tag(tag) = map.next_value()?;
534                    return variant(&tag, MapAccessDeserializer::new(map));
535                }
536                Some(Key::Other(key)) => key,
537            };
538            // Slow path: buffer the whole map, then find the tag.
539            let mut fields = serde_json::Map::new();
540            fields.insert(first, map.next_value()?);
541            while let Some((key, value)) = map.next_entry::<String, Value>()? {
542                fields.insert(key, value);
543            }
544            let tag = match fields.remove("type") {
545                Some(Value::String(tag)) => tag,
546                Some(_) => return Err(de::Error::custom("`type` must be a string")),
547                None => return Err(de::Error::missing_field("type")),
548            };
549            variant(&tag, Value::Object(fields)).map_err(de::Error::custom)
550        }
551    }
552
553    impl<'de> Deserialize<'de> for Node {
554        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
555            d.deserialize_map(NodeVisitor)
556        }
557    }
558}
559
560/// Defines a node struct with an optional `span` plus the given fields, and
561/// a `From` conversion into [`Node`].
562macro_rules! node_struct {
563    (
564        $(#[$meta:meta])*
565        $name:ident {
566            $( $(#[$fmeta:meta])* $field:ident : $ty:ty ),* $(,)?
567        }
568    ) => {
569        $(#[$meta])*
570        #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
571        #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
572        pub struct $name {
573            /// Where this node came from in the source, if known.
574            #[serde(default, skip_serializing_if = "Option::is_none")]
575            pub span: Option<Span>,
576            $( $(#[$fmeta])* pub $field: $ty, )*
577        }
578
579        impl From<$name> for Node {
580            fn from(n: $name) -> Self {
581                Node::$name(n)
582            }
583        }
584    };
585}
586
587node_struct! {
588    /// See [`Node::Section`].
589    Section {
590        /// Anchor identifier for linking to the section. Set by the parser
591        /// if the author gave one; otherwise the host derives one from the
592        /// title.
593        #[serde(default, skip_serializing_if = "Option::is_none")]
594        id: Option<String>,
595        /// Content of the section.
596        #[serde(default)]
597        children: Vec<Node>,
598    }
599}
600
601node_struct! {
602    /// See [`Node::Heading`].
603    Heading {
604        /// Heading level, from 1 (top) to 6. For a section title this is
605        /// the level as written, which may skip levels; the nesting of
606        /// sections is the structure.
607        level: u8,
608        /// Anchor identifier, only for headings that are not a section's
609        /// title (a section's anchor is [`Section::id`]).
610        #[serde(default, skip_serializing_if = "Option::is_none")]
611        id: Option<String>,
612        /// Inline content.
613        #[serde(default)]
614        children: Vec<Node>,
615    }
616}
617
618node_struct! {
619    /// See [`Node::Paragraph`].
620    Paragraph {
621        /// Inline content.
622        #[serde(default)]
623        children: Vec<Node>,
624    }
625}
626
627node_struct! {
628    /// See [`Node::List`].
629    List {
630        /// Whether items are numbered.
631        #[serde(default)]
632        ordered: bool,
633        /// Number of the first item of an ordered list, if not 1.
634        #[serde(default, skip_serializing_if = "Option::is_none")]
635        start: Option<u64>,
636        /// The list's items.
637        #[serde(default)]
638        children: Vec<Node>,
639    }
640}
641
642node_struct! {
643    /// See [`Node::ListItem`].
644    ListItem {
645        /// For task list items, whether the box is checked.
646        #[serde(default, skip_serializing_if = "Option::is_none")]
647        checked: Option<bool>,
648        /// Content of the item.
649        #[serde(default)]
650        children: Vec<Node>,
651    }
652}
653
654node_struct! {
655    /// See [`Node::BlockQuote`].
656    BlockQuote {
657        /// Quoted content.
658        #[serde(default)]
659        children: Vec<Node>,
660    }
661}
662
663node_struct! {
664    /// See [`Node::CodeBlock`].
665    CodeBlock {
666        /// Language name, e.g. `"rust"`, if given.
667        #[serde(default, skip_serializing_if = "Option::is_none")]
668        language: Option<String>,
669        /// Anything after the language on a Markdown fence's info line.
670        #[serde(default, skip_serializing_if = "Option::is_none")]
671        info: Option<String>,
672        /// The code itself.
673        value: String,
674    }
675}
676
677node_struct! {
678    /// See [`Node::Table`].
679    Table {
680        /// Alignment of each column.
681        #[serde(default, skip_serializing_if = "Vec::is_empty")]
682        align: Vec<Align>,
683        /// The table's rows.
684        #[serde(default)]
685        children: Vec<Node>,
686    }
687}
688
689node_struct! {
690    /// See [`Node::TableRow`].
691    TableRow {
692        /// Whether this is a header row.
693        #[serde(default)]
694        header: bool,
695        /// The row's cells.
696        #[serde(default)]
697        children: Vec<Node>,
698    }
699}
700
701node_struct! {
702    /// See [`Node::TableCell`].
703    TableCell {
704        /// Content of the cell.
705        #[serde(default)]
706        children: Vec<Node>,
707    }
708}
709
710node_struct! {
711    /// See [`Node::ThematicBreak`].
712    ThematicBreak {}
713}
714
715node_struct! {
716    /// See [`Node::Raw`].
717    Raw {
718        /// Output format the content is meant for, e.g. `"html"`.
719        format: String,
720        /// The verbatim content.
721        value: String,
722    }
723}
724
725node_struct! {
726    /// See [`Node::Text`].
727    Text {
728        /// The text.
729        value: String,
730    }
731}
732
733node_struct! {
734    /// See [`Node::Emphasis`].
735    Emphasis {
736        /// Emphasized content.
737        #[serde(default)]
738        children: Vec<Node>,
739    }
740}
741
742node_struct! {
743    /// See [`Node::Strong`].
744    Strong {
745        /// Strongly emphasized content.
746        #[serde(default)]
747        children: Vec<Node>,
748    }
749}
750
751node_struct! {
752    /// See [`Node::InlineCode`].
753    InlineCode {
754        /// The code.
755        value: String,
756    }
757}
758
759node_struct! {
760    /// See [`Node::Link`].
761    Link {
762        /// Link target.
763        url: String,
764        /// Link title (often shown as a tooltip).
765        #[serde(default, skip_serializing_if = "Option::is_none")]
766        title: Option<String>,
767        /// Where the link points inside the site, if it is a
768        /// cross-reference. Renderers prefer it over `url`.
769        #[serde(default, skip_serializing_if = "Option::is_none")]
770        target: Option<LinkTarget>,
771        /// Link text.
772        #[serde(default)]
773        children: Vec<Node>,
774    }
775}
776
777/// The site-internal destination of a [`Link`].
778///
779/// A resolved target names a document, an anchor, or both (an anchor alone
780/// means the linking document). An unresolved one has only a `label`, to be
781/// looked up among the anchors of every document, e.g. by a transformer.
782#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
783#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
784pub struct LinkTarget {
785    /// Source path of the target document, relative to the source
786    /// directory with `/` separators.
787    #[serde(default, skip_serializing_if = "Option::is_none")]
788    pub document: Option<String>,
789    /// Anchor id within the target document.
790    #[serde(default, skip_serializing_if = "Option::is_none")]
791    pub anchor: Option<String>,
792    /// A label naming the target, not yet resolved to a document and
793    /// anchor.
794    #[serde(default, skip_serializing_if = "Option::is_none")]
795    pub label: Option<String>,
796}
797
798node_struct! {
799    /// See [`Node::Image`].
800    Image {
801        /// Image location.
802        url: String,
803        /// Alternative text.
804        #[serde(default)]
805        alt: String,
806        /// Image title (often shown as a tooltip).
807        #[serde(default, skip_serializing_if = "Option::is_none")]
808        title: Option<String>,
809    }
810}
811
812node_struct! {
813    /// See [`Node::LineBreak`].
814    LineBreak {}
815}
816
817node_struct! {
818    /// See [`Node::Admonition`].
819    Admonition {
820        /// What kind of callout, e.g. `"note"`, `"tip"`, `"warning"`.
821        kind: String,
822        /// A title replacing the kind's default one.
823        #[serde(default, skip_serializing_if = "Option::is_none")]
824        title: Option<String>,
825        /// Content.
826        #[serde(default)]
827        children: Vec<Node>,
828    }
829}
830
831node_struct! {
832    /// See [`Node::DefinitionList`].
833    DefinitionList {
834        /// Terms and descriptions, in order.
835        #[serde(default)]
836        children: Vec<Node>,
837    }
838}
839
840node_struct! {
841    /// See [`Node::DefinitionTerm`].
842    DefinitionTerm {
843        /// Inline content.
844        #[serde(default)]
845        children: Vec<Node>,
846    }
847}
848
849node_struct! {
850    /// See [`Node::DefinitionDescription`].
851    DefinitionDescription {
852        /// Content.
853        #[serde(default)]
854        children: Vec<Node>,
855    }
856}
857
858node_struct! {
859    /// See [`Node::FootnoteReference`].
860    FootnoteReference {
861        /// The footnote's label, e.g. `"1"` or `"note"`.
862        label: String,
863    }
864}
865
866node_struct! {
867    /// See [`Node::FootnoteDefinition`].
868    FootnoteDefinition {
869        /// The label references use.
870        label: String,
871        /// Content.
872        #[serde(default)]
873        children: Vec<Node>,
874    }
875}
876
877node_struct! {
878    /// See [`Node::Math`].
879    Math {
880        /// The formula, e.g. in TeX notation.
881        value: String,
882        /// Whether it is set on its own line rather than inline.
883        #[serde(default)]
884        display: bool,
885    }
886}
887
888node_struct! {
889    /// See [`Node::Figure`].
890    Figure {
891        /// Anchor identifier, e.g. for linking to the figure.
892        #[serde(default, skip_serializing_if = "Option::is_none")]
893        id: Option<String>,
894        /// Content, then an optional caption.
895        #[serde(default)]
896        children: Vec<Node>,
897    }
898}
899
900node_struct! {
901    /// See [`Node::Caption`].
902    Caption {
903        /// Content.
904        #[serde(default)]
905        children: Vec<Node>,
906    }
907}
908
909node_struct! {
910    /// See [`Node::Anchor`].
911    Anchor {
912        /// The anchor identifier.
913        id: String,
914    }
915}
916
917node_struct! {
918    /// See [`Node::Custom`].
919    Custom {
920        /// The plugin-defined kind, e.g. `"mermaid"`. Selected as
921        /// `"custom:<kind>"`.
922        kind: String,
923        /// Arbitrary attributes.
924        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
925        attrs: BTreeMap<String, Value>,
926        /// Child nodes, if any.
927        #[serde(default)]
928        children: Vec<Node>,
929    }
930}
931
932/// Horizontal alignment of a table column.
933#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
934#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
935#[serde(rename_all = "snake_case")]
936pub enum Align {
937    /// No alignment specified.
938    #[default]
939    None,
940    /// Left-aligned.
941    Left,
942    /// Centered.
943    Center,
944    /// Right-aligned.
945    Right,
946}
947
948/// Shorthand for a [`Text`] node.
949pub fn text(value: impl Into<String>) -> Node {
950    Text {
951        span: None,
952        value: value.into(),
953    }
954    .into()
955}
956
957#[cfg(test)]
958mod tests {
959    #![allow(clippy::unwrap_used)]
960    use super::*;
961    use serde_json::json;
962
963    fn sample() -> Document {
964        let mut doc = Document::new("guide/intro.md");
965        doc.metadata.insert("title".into(), json!("Intro"));
966        doc.children = vec![
967            Heading {
968                span: Some(Span::new(0, 8)),
969                level: 1,
970                id: Some("intro".into()),
971                children: vec![text("Intro")],
972            }
973            .into(),
974            Paragraph {
975                span: None,
976                children: vec![
977                    text("See "),
978                    Link {
979                        url: "https://example.com".into(),
980                        children: vec![text("here")],
981                        ..Link::default()
982                    }
983                    .into(),
984                ],
985            }
986            .into(),
987            Custom {
988                kind: "mermaid".into(),
989                attrs: BTreeMap::from([("source".into(), json!("graph TD; A-->B"))]),
990                ..Custom::default()
991            }
992            .into(),
993        ];
994        doc
995    }
996
997    #[test]
998    fn nodes_are_tagged_by_type_and_omit_empty_fields() {
999        let heading = &sample().children[0];
1000        assert_eq!(
1001            serde_json::to_value(heading).unwrap(),
1002            json!({
1003                "type": "heading",
1004                "span": {"start": 0, "end": 8},
1005                "level": 1,
1006                "id": "intro",
1007                "children": [{"type": "text", "value": "Intro"}],
1008            })
1009        );
1010    }
1011
1012    #[test]
1013    fn json_round_trip() {
1014        let doc = sample();
1015        let json = serde_json::to_string(&doc).unwrap();
1016        assert_eq!(serde_json::from_str::<Document>(&json).unwrap(), doc);
1017    }
1018
1019    #[test]
1020    fn missing_optional_fields_and_unknown_fields_are_accepted() {
1021        let node: Node = serde_json::from_value(json!({
1022            "type": "paragraph",
1023            "added_in_a_later_version": true,
1024        }))
1025        .unwrap();
1026        assert_eq!(node, Paragraph::default().into());
1027    }
1028
1029    #[test]
1030    fn kind_matches_the_type_tag() {
1031        for node in sample().descendants() {
1032            let kind = node.kind();
1033            match node {
1034                Node::Custom(c) => assert_eq!(kind, format!("custom:{}", c.kind)),
1035                _ => {
1036                    let tag = serde_json::to_value(node).unwrap()["type"].clone();
1037                    assert_eq!(json!(kind), tag);
1038                }
1039            }
1040        }
1041    }
1042
1043    #[test]
1044    fn titles_and_plain_text() {
1045        let mut doc = sample();
1046        assert_eq!(doc.title().as_deref(), Some("Intro"));
1047        doc.metadata.clear();
1048        doc.children[0] = Heading {
1049            level: 1,
1050            children: vec![
1051                text("A "),
1052                InlineCode {
1053                    value: "b".into(),
1054                    ..InlineCode::default()
1055                }
1056                .into(),
1057                Image {
1058                    alt: " c".into(),
1059                    ..Image::default()
1060                }
1061                .into(),
1062            ],
1063            ..Heading::default()
1064        }
1065        .into();
1066        assert_eq!(doc.title().as_deref(), Some("A b c"));
1067        assert_eq!(Document::new("x.md").title(), None);
1068    }
1069
1070    #[test]
1071    fn nodes_decode_whatever_the_key_order() {
1072        let tag_first =
1073            json!({"type": "heading", "level": 2, "children": [{"type": "text", "value": "A"}]});
1074        let tag_last =
1075            json!({"level": 2, "children": [{"value": "A", "type": "text"}], "type": "heading"});
1076        let a: Node = serde_json::from_value(tag_first).unwrap();
1077        let b: Node = serde_json::from_value(tag_last).unwrap();
1078        assert_eq!(a, b);
1079        assert_eq!(a.kind(), "heading");
1080        let bad = serde_json::from_value::<Node>(json!({"type": "nope"})).unwrap_err();
1081        assert!(bad.to_string().contains("unknown variant `nope`"), "{bad}");
1082        let missing = serde_json::from_value::<Node>(json!({"level": 1})).unwrap_err();
1083        assert!(missing.to_string().contains("type"), "{missing}");
1084    }
1085
1086    #[test]
1087    fn descendants_are_depth_first() {
1088        let kinds: Vec<_> = sample().descendants().map(|n| n.kind()).collect();
1089        assert_eq!(
1090            kinds,
1091            [
1092                "heading",
1093                "text",
1094                "paragraph",
1095                "text",
1096                "link",
1097                "text",
1098                "custom:mermaid"
1099            ]
1100        );
1101    }
1102}