use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub type Value = serde_json::Value;
pub type Metadata = BTreeMap<String, Value>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Span {
pub start: u32,
pub end: u32,
}
impl Span {
pub const fn new(start: u32, end: u32) -> Self {
Self { start, end }
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Document {
pub source: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub metadata: Metadata,
#[serde(default)]
pub children: Vec<Node>,
}
impl Document {
pub fn new(source: impl Into<String>) -> Self {
Self {
source: source.into(),
..Self::default()
}
}
pub fn descendants(&self) -> Descendants<'_> {
Descendants {
stack: self.children.iter().rev().collect(),
}
}
pub fn title(&self) -> Option<String> {
self.metadata
.get("title")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| {
self.descendants().find_map(|n| match n {
Node::Heading(h) => Some(plain_text(&h.children)),
_ => None,
})
})
}
}
pub fn plain_text(nodes: &[Node]) -> String {
let mut out = String::new();
for node in nodes {
match node {
Node::Text(t) => out.push_str(&t.value),
Node::InlineCode(c) => out.push_str(&c.value),
Node::Image(i) => out.push_str(&i.alt),
other => out.push_str(&plain_text(other.children())),
}
}
out
}
#[derive(Debug, Clone)]
pub struct Descendants<'a> {
stack: Vec<&'a Node>,
}
impl<'a> Iterator for Descendants<'a> {
type Item = &'a Node;
fn next(&mut self) -> Option<Self::Item> {
let node = self.stack.pop()?;
self.stack.extend(node.children().iter().rev());
Some(node)
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Node {
Section(Section),
Heading(Heading),
Paragraph(Paragraph),
List(List),
ListItem(ListItem),
BlockQuote(BlockQuote),
CodeBlock(CodeBlock),
Table(Table),
TableRow(TableRow),
TableCell(TableCell),
ThematicBreak(ThematicBreak),
Raw(Raw),
Text(Text),
Emphasis(Emphasis),
Strong(Strong),
InlineCode(InlineCode),
Link(Link),
Image(Image),
LineBreak(LineBreak),
Admonition(Admonition),
DefinitionList(DefinitionList),
DefinitionTerm(DefinitionTerm),
DefinitionDescription(DefinitionDescription),
FootnoteReference(FootnoteReference),
FootnoteDefinition(FootnoteDefinition),
Math(Math),
Figure(Figure),
Caption(Caption),
Anchor(Anchor),
Custom(Custom),
}
impl Node {
pub fn kind(&self) -> std::borrow::Cow<'static, str> {
use std::borrow::Cow::{Borrowed, Owned};
Borrowed(match self {
Node::Section(_) => "section",
Node::Heading(_) => "heading",
Node::Paragraph(_) => "paragraph",
Node::List(_) => "list",
Node::ListItem(_) => "list_item",
Node::BlockQuote(_) => "block_quote",
Node::CodeBlock(_) => "code_block",
Node::Table(_) => "table",
Node::TableRow(_) => "table_row",
Node::TableCell(_) => "table_cell",
Node::ThematicBreak(_) => "thematic_break",
Node::Raw(_) => "raw",
Node::Text(_) => "text",
Node::Emphasis(_) => "emphasis",
Node::Strong(_) => "strong",
Node::InlineCode(_) => "inline_code",
Node::Link(_) => "link",
Node::Image(_) => "image",
Node::LineBreak(_) => "line_break",
Node::Admonition(_) => "admonition",
Node::DefinitionList(_) => "definition_list",
Node::DefinitionTerm(_) => "definition_term",
Node::DefinitionDescription(_) => "definition_description",
Node::FootnoteReference(_) => "footnote_reference",
Node::FootnoteDefinition(_) => "footnote_definition",
Node::Math(_) => "math",
Node::Figure(_) => "figure",
Node::Caption(_) => "caption",
Node::Anchor(_) => "anchor",
Node::Custom(c) => return Owned(format!("custom:{}", c.kind)),
})
}
pub fn span(&self) -> Option<Span> {
match self {
Node::Section(n) => n.span,
Node::Heading(n) => n.span,
Node::Paragraph(n) => n.span,
Node::List(n) => n.span,
Node::ListItem(n) => n.span,
Node::BlockQuote(n) => n.span,
Node::CodeBlock(n) => n.span,
Node::Table(n) => n.span,
Node::TableRow(n) => n.span,
Node::TableCell(n) => n.span,
Node::ThematicBreak(n) => n.span,
Node::Raw(n) => n.span,
Node::Text(n) => n.span,
Node::Emphasis(n) => n.span,
Node::Strong(n) => n.span,
Node::InlineCode(n) => n.span,
Node::Link(n) => n.span,
Node::Image(n) => n.span,
Node::LineBreak(n) => n.span,
Node::Admonition(n) => n.span,
Node::DefinitionList(n) => n.span,
Node::DefinitionTerm(n) => n.span,
Node::DefinitionDescription(n) => n.span,
Node::FootnoteReference(n) => n.span,
Node::FootnoteDefinition(n) => n.span,
Node::Math(n) => n.span,
Node::Figure(n) => n.span,
Node::Caption(n) => n.span,
Node::Anchor(n) => n.span,
Node::Custom(n) => n.span,
}
}
pub fn span_mut(&mut self) -> &mut Option<Span> {
match self {
Node::Section(n) => &mut n.span,
Node::Heading(n) => &mut n.span,
Node::Paragraph(n) => &mut n.span,
Node::List(n) => &mut n.span,
Node::ListItem(n) => &mut n.span,
Node::BlockQuote(n) => &mut n.span,
Node::CodeBlock(n) => &mut n.span,
Node::Table(n) => &mut n.span,
Node::TableRow(n) => &mut n.span,
Node::TableCell(n) => &mut n.span,
Node::ThematicBreak(n) => &mut n.span,
Node::Raw(n) => &mut n.span,
Node::Text(n) => &mut n.span,
Node::Emphasis(n) => &mut n.span,
Node::Strong(n) => &mut n.span,
Node::InlineCode(n) => &mut n.span,
Node::Link(n) => &mut n.span,
Node::Image(n) => &mut n.span,
Node::LineBreak(n) => &mut n.span,
Node::Admonition(n) => &mut n.span,
Node::DefinitionList(n) => &mut n.span,
Node::DefinitionTerm(n) => &mut n.span,
Node::DefinitionDescription(n) => &mut n.span,
Node::FootnoteReference(n) => &mut n.span,
Node::FootnoteDefinition(n) => &mut n.span,
Node::Math(n) => &mut n.span,
Node::Figure(n) => &mut n.span,
Node::Caption(n) => &mut n.span,
Node::Anchor(n) => &mut n.span,
Node::Custom(n) => &mut n.span,
}
}
pub fn children(&self) -> &[Node] {
match self {
Node::Section(n) => &n.children,
Node::Heading(n) => &n.children,
Node::Paragraph(n) => &n.children,
Node::List(n) => &n.children,
Node::ListItem(n) => &n.children,
Node::BlockQuote(n) => &n.children,
Node::Table(n) => &n.children,
Node::TableRow(n) => &n.children,
Node::TableCell(n) => &n.children,
Node::Emphasis(n) => &n.children,
Node::Strong(n) => &n.children,
Node::Link(n) => &n.children,
Node::Admonition(n) => &n.children,
Node::DefinitionList(n) => &n.children,
Node::DefinitionTerm(n) => &n.children,
Node::DefinitionDescription(n) => &n.children,
Node::FootnoteDefinition(n) => &n.children,
Node::Figure(n) => &n.children,
Node::Caption(n) => &n.children,
Node::Custom(n) => &n.children,
Node::CodeBlock(_)
| Node::ThematicBreak(_)
| Node::Raw(_)
| Node::Text(_)
| Node::InlineCode(_)
| Node::Image(_)
| Node::LineBreak(_)
| Node::FootnoteReference(_)
| Node::Math(_)
| Node::Anchor(_) => &[],
}
}
pub fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
match self {
Node::Section(n) => Some(&mut n.children),
Node::Heading(n) => Some(&mut n.children),
Node::Paragraph(n) => Some(&mut n.children),
Node::List(n) => Some(&mut n.children),
Node::ListItem(n) => Some(&mut n.children),
Node::BlockQuote(n) => Some(&mut n.children),
Node::Table(n) => Some(&mut n.children),
Node::TableRow(n) => Some(&mut n.children),
Node::TableCell(n) => Some(&mut n.children),
Node::Emphasis(n) => Some(&mut n.children),
Node::Strong(n) => Some(&mut n.children),
Node::Link(n) => Some(&mut n.children),
Node::Admonition(n) => Some(&mut n.children),
Node::DefinitionList(n) => Some(&mut n.children),
Node::DefinitionTerm(n) => Some(&mut n.children),
Node::DefinitionDescription(n) => Some(&mut n.children),
Node::FootnoteDefinition(n) => Some(&mut n.children),
Node::Figure(n) => Some(&mut n.children),
Node::Caption(n) => Some(&mut n.children),
Node::Custom(n) => Some(&mut n.children),
Node::CodeBlock(_)
| Node::ThematicBreak(_)
| Node::Raw(_)
| Node::Text(_)
| Node::InlineCode(_)
| Node::Image(_)
| Node::LineBreak(_)
| Node::FootnoteReference(_)
| Node::Math(_)
| Node::Anchor(_) => None,
}
}
pub fn descendants(&self) -> Descendants<'_> {
Descendants { stack: vec![self] }
}
}
mod de {
use std::fmt;
use serde::de::value::MapAccessDeserializer;
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
use super::*;
macro_rules! variants {
($tag:expr, $d:expr, $( $name:literal => $variant:ident ),* $(,)?) => {
match $tag {
$( $name => $variant::deserialize($d).map(Node::$variant), )*
other => Err(de::Error::unknown_variant(other, &[$($name),*])),
}
};
}
fn variant<'de, D: Deserializer<'de>>(tag: &str, d: D) -> Result<Node, D::Error> {
variants!(tag, d,
"section" => Section,
"heading" => Heading,
"paragraph" => Paragraph,
"list" => List,
"list_item" => ListItem,
"block_quote" => BlockQuote,
"code_block" => CodeBlock,
"table" => Table,
"table_row" => TableRow,
"table_cell" => TableCell,
"thematic_break" => ThematicBreak,
"raw" => Raw,
"text" => Text,
"emphasis" => Emphasis,
"strong" => Strong,
"inline_code" => InlineCode,
"link" => Link,
"image" => Image,
"line_break" => LineBreak,
"admonition" => Admonition,
"definition_list" => DefinitionList,
"definition_term" => DefinitionTerm,
"definition_description" => DefinitionDescription,
"footnote_reference" => FootnoteReference,
"footnote_definition" => FootnoteDefinition,
"math" => Math,
"figure" => Figure,
"caption" => Caption,
"anchor" => Anchor,
"custom" => Custom,
)
}
enum Key {
Type,
Other(String),
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct KeyVisitor;
impl Visitor<'_> for KeyVisitor {
type Value = Key;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a field name")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Key, E> {
Ok(if v == "type" {
Key::Type
} else {
Key::Other(v.to_owned())
})
}
}
d.deserialize_str(KeyVisitor)
}
}
struct Tag<'de>(std::borrow::Cow<'de, str>);
impl<'de> Deserialize<'de> for Tag<'de> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct TagVisitor;
impl<'de> Visitor<'de> for TagVisitor {
type Value = Tag<'de>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a node type")
}
fn visit_borrowed_str<E: de::Error>(self, v: &'de str) -> Result<Tag<'de>, E> {
Ok(Tag(v.into()))
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Tag<'de>, E> {
Ok(Tag(v.to_owned().into()))
}
}
d.deserialize_str(TagVisitor)
}
}
struct NodeVisitor;
impl<'de> Visitor<'de> for NodeVisitor {
type Value = Node;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a document node: a map with a `type` field")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
let first = match map.next_key::<Key>()? {
None => return Err(de::Error::missing_field("type")),
Some(Key::Type) => {
let Tag(tag) = map.next_value()?;
return variant(&tag, MapAccessDeserializer::new(map));
}
Some(Key::Other(key)) => key,
};
let mut fields = serde_json::Map::new();
fields.insert(first, map.next_value()?);
while let Some((key, value)) = map.next_entry::<String, Value>()? {
fields.insert(key, value);
}
let tag = match fields.remove("type") {
Some(Value::String(tag)) => tag,
Some(_) => return Err(de::Error::custom("`type` must be a string")),
None => return Err(de::Error::missing_field("type")),
};
variant(&tag, Value::Object(fields)).map_err(de::Error::custom)
}
}
impl<'de> Deserialize<'de> for Node {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
d.deserialize_map(NodeVisitor)
}
}
}
macro_rules! node_struct {
(
$(#[$meta:meta])*
$name:ident {
$( $(#[$fmeta:meta])* $field:ident : $ty:ty ),* $(,)?
}
) => {
$(#[$meta])*
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct $name {
/// Where this node came from in the source, if known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
$( $(#[$fmeta])* pub $field: $ty, )*
}
impl From<$name> for Node {
fn from(n: $name) -> Self {
Node::$name(n)
}
}
};
}
node_struct! {
Section {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
Heading {
level: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
Paragraph {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
List {
#[serde(default)]
ordered: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
start: Option<u64>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
ListItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
checked: Option<bool>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
BlockQuote {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
CodeBlock {
#[serde(default, skip_serializing_if = "Option::is_none")]
language: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
info: Option<String>,
value: String,
}
}
node_struct! {
Table {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
align: Vec<Align>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
TableRow {
#[serde(default)]
header: bool,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
TableCell {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
ThematicBreak {}
}
node_struct! {
Raw {
format: String,
value: String,
}
}
node_struct! {
Text {
value: String,
}
}
node_struct! {
Emphasis {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
Strong {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
InlineCode {
value: String,
}
}
node_struct! {
Link {
url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<LinkTarget>,
#[serde(default)]
children: Vec<Node>,
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct LinkTarget {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub document: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub anchor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
}
node_struct! {
Image {
url: String,
#[serde(default)]
alt: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
}
}
node_struct! {
LineBreak {}
}
node_struct! {
Admonition {
kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
DefinitionList {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
DefinitionTerm {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
DefinitionDescription {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
FootnoteReference {
label: String,
}
}
node_struct! {
FootnoteDefinition {
label: String,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
Math {
value: String,
#[serde(default)]
display: bool,
}
}
node_struct! {
Figure {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
Caption {
#[serde(default)]
children: Vec<Node>,
}
}
node_struct! {
Anchor {
id: String,
}
}
node_struct! {
Custom {
kind: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
attrs: BTreeMap<String, Value>,
#[serde(default)]
children: Vec<Node>,
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Align {
#[default]
None,
Left,
Center,
Right,
}
pub fn text(value: impl Into<String>) -> Node {
Text {
span: None,
value: value.into(),
}
.into()
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use serde_json::json;
fn sample() -> Document {
let mut doc = Document::new("guide/intro.md");
doc.metadata.insert("title".into(), json!("Intro"));
doc.children = vec![
Heading {
span: Some(Span::new(0, 8)),
level: 1,
id: Some("intro".into()),
children: vec![text("Intro")],
}
.into(),
Paragraph {
span: None,
children: vec![
text("See "),
Link {
url: "https://example.com".into(),
children: vec![text("here")],
..Link::default()
}
.into(),
],
}
.into(),
Custom {
kind: "mermaid".into(),
attrs: BTreeMap::from([("source".into(), json!("graph TD; A-->B"))]),
..Custom::default()
}
.into(),
];
doc
}
#[test]
fn nodes_are_tagged_by_type_and_omit_empty_fields() {
let heading = &sample().children[0];
assert_eq!(
serde_json::to_value(heading).unwrap(),
json!({
"type": "heading",
"span": {"start": 0, "end": 8},
"level": 1,
"id": "intro",
"children": [{"type": "text", "value": "Intro"}],
})
);
}
#[test]
fn json_round_trip() {
let doc = sample();
let json = serde_json::to_string(&doc).unwrap();
assert_eq!(serde_json::from_str::<Document>(&json).unwrap(), doc);
}
#[test]
fn missing_optional_fields_and_unknown_fields_are_accepted() {
let node: Node = serde_json::from_value(json!({
"type": "paragraph",
"added_in_a_later_version": true,
}))
.unwrap();
assert_eq!(node, Paragraph::default().into());
}
#[test]
fn kind_matches_the_type_tag() {
for node in sample().descendants() {
let kind = node.kind();
match node {
Node::Custom(c) => assert_eq!(kind, format!("custom:{}", c.kind)),
_ => {
let tag = serde_json::to_value(node).unwrap()["type"].clone();
assert_eq!(json!(kind), tag);
}
}
}
}
#[test]
fn titles_and_plain_text() {
let mut doc = sample();
assert_eq!(doc.title().as_deref(), Some("Intro"));
doc.metadata.clear();
doc.children[0] = Heading {
level: 1,
children: vec![
text("A "),
InlineCode {
value: "b".into(),
..InlineCode::default()
}
.into(),
Image {
alt: " c".into(),
..Image::default()
}
.into(),
],
..Heading::default()
}
.into();
assert_eq!(doc.title().as_deref(), Some("A b c"));
assert_eq!(Document::new("x.md").title(), None);
}
#[test]
fn nodes_decode_whatever_the_key_order() {
let tag_first =
json!({"type": "heading", "level": 2, "children": [{"type": "text", "value": "A"}]});
let tag_last =
json!({"level": 2, "children": [{"value": "A", "type": "text"}], "type": "heading"});
let a: Node = serde_json::from_value(tag_first).unwrap();
let b: Node = serde_json::from_value(tag_last).unwrap();
assert_eq!(a, b);
assert_eq!(a.kind(), "heading");
let bad = serde_json::from_value::<Node>(json!({"type": "nope"})).unwrap_err();
assert!(bad.to_string().contains("unknown variant `nope`"), "{bad}");
let missing = serde_json::from_value::<Node>(json!({"level": 1})).unwrap_err();
assert!(missing.to_string().contains("type"), "{missing}");
}
#[test]
fn descendants_are_depth_first() {
let kinds: Vec<_> = sample().descendants().map(|n| n.kind()).collect();
assert_eq!(
kinds,
[
"heading",
"text",
"paragraph",
"text",
"link",
"text",
"custom:mermaid"
]
);
}
}