use std::collections::HashMap;
use pest::{iterators::Pair, Parser as _};
use pest_derive::Parser;
use sha2::{Digest, Sha256};
use super::ast::{Block, Inline, ListItem, SourceSpan, SpannedBlock};
#[derive(Parser)]
#[grammar = "markdown/grammar.pest"]
pub struct InlineParser;
pub fn parse(input: &str) -> Vec<Block> {
parse_with_depth(input, 0)
}
fn parse_with_depth(input: &str, list_depth: usize) -> Vec<Block> {
strip_spans(parse_body_spanned_at(input, 0, list_depth))
}
pub fn parse_doc(input: &str) -> Vec<SpannedBlock> {
let (_kind, _fm, body, body_offset) = crate::frontmatter::strip_with_offset(input);
if body.is_empty() {
return Vec::new();
}
let body_line = input[..body_offset].matches('\n').count();
parse_body_spanned_at(input, body_line, 0)
}
fn parse_body_spanned_at(input: &str, body_line: usize, list_depth: usize) -> Vec<SpannedBlock> {
let (lines, starts, ends) = line_tables(input);
if body_line >= lines.len() {
return Vec::new();
}
let mut ctx = Ctx::default();
let mut scan = Scan {
full: input,
shift: TableShift {
line_shift: body_line,
},
stack: Vec::new(),
ctx: &mut ctx,
list_depth,
};
parse_spanned_lines(
&lines[body_line..],
&starts[body_line..],
&ends[body_line..],
&mut scan,
)
}
fn line_tables(input: &str) -> (Vec<&str>, Vec<usize>, Vec<usize>) {
let mut lines = Vec::new();
let mut starts = Vec::new();
let mut ends = Vec::new();
let mut off = 0usize;
for raw in input.split('\n') {
starts.push(off);
let stripped = raw.strip_suffix('\r').unwrap_or(raw);
ends.push(off + stripped.len());
lines.push(stripped);
off += raw.len() + 1;
}
(lines, starts, ends)
}
#[derive(Clone, Copy)]
struct TableShift {
line_shift: usize,
}
impl TableShift {
fn span(
&self,
starts: &[usize],
ends: &[usize],
first: usize,
end_exclusive: usize,
) -> SourceSpan {
let last = end_exclusive - 1;
SourceSpan {
start_line: first + 1 + self.line_shift,
end_line: last + 1 + self.line_shift,
start_byte: starts[first],
end_byte: ends[last],
}
}
}
#[derive(Default)]
struct Ctx {
id_counts: HashMap<String, usize>,
}
struct Scan<'a> {
full: &'a str,
shift: TableShift,
stack: Vec<(usize, String)>,
ctx: &'a mut Ctx,
list_depth: usize,
}
fn block_id(ctx: &mut Ctx, source_text: &str) -> String {
let digest = Sha256::digest(source_text.as_bytes());
let mut base = String::with_capacity(10);
base.push_str("b-");
for b in &digest[..4] {
base.push_str(&format!("{b:02x}"));
}
let seen = ctx.id_counts.entry(source_text.to_string()).or_insert(0);
*seen += 1;
if *seen == 1 {
base
} else {
format!("{base}-{}", *seen)
}
}
fn inline_plain_text(inlines: &[Inline]) -> String {
let mut out = String::new();
for i in inlines {
match i {
Inline::Text(s) => out.push_str(s),
Inline::Code(s) => out.push_str(s),
Inline::Strong(inner) | Inline::Emphasis(inner) => {
out.push_str(&inline_plain_text(inner))
}
Inline::Link { text, .. } => out.push_str(&inline_plain_text(text)),
Inline::Image { alt, .. } => out.push_str(alt),
Inline::InlineHtml(_) => {}
}
}
out
}
fn heading_path_of(stack: &[(usize, String)]) -> Vec<String> {
stack.iter().map(|(_, t)| t.clone()).collect()
}
fn parse_spanned_lines(
lines: &[&str],
starts: &[usize],
ends: &[usize],
scan: &mut Scan<'_>,
) -> Vec<SpannedBlock> {
let mut blocks = Vec::new();
let mut i = 0usize;
while i < lines.len() {
let line = lines[i];
if line.trim().is_empty() {
i += 1;
continue;
}
let (block, next): (Block, usize) = if let Some(pair) = parse_fenced_code(lines, i) {
pair
} else if let Some(pair) = parse_atx_heading(line, i, &mut scan.stack) {
pair
} else if is_thematic_break(line) {
(Block::ThematicBreak, i + 1)
} else if let Some(pair) = parse_center_container(lines, starts, ends, i, scan) {
pair
} else if let Some(pair) = parse_html_block(lines, i) {
pair
} else if let Some(pair) = parse_blockquote(lines, starts, ends, i, scan) {
pair
} else if let Some(pair) = parse_table(lines, i) {
pair
} else if let Some(pair) = parse_list(lines, i, scan.list_depth) {
pair
} else {
parse_paragraph(lines, i)
};
let span = scan.shift.span(starts, ends, i, next);
let source_text = &scan.full[span.start_byte..span.end_byte];
let id = block_id(scan.ctx, source_text);
blocks.push(SpannedBlock {
block,
span,
id,
heading_path: heading_path_of(&scan.stack),
});
i = next.max(i + 1);
}
blocks
}
fn parse_fenced_code(lines: &[&str], i: usize) -> Option<(Block, usize)> {
let trimmed = lines[i].trim_start();
let (fence_char, n) = leading_fence(trimmed)?;
let info = trimmed[n..].trim();
let mut code = String::new();
let mut j = i + 1;
while j < lines.len() {
let t = lines[j].trim_start();
if let Some((c, m)) = leading_fence(t) {
if c == fence_char && m >= n {
if let Some(block) = route_special_fence(info, &code) {
return Some((block, j + 1));
}
let lang = if info.is_empty() {
None
} else {
Some(info.to_string())
};
return Some((Block::CodeBlock { lang, code }, j + 1));
}
}
code.push_str(lines[j]);
code.push('\n');
j += 1;
}
if let Some(block) = route_special_fence(info, &code) {
return Some((block, j));
}
let lang = if info.is_empty() {
None
} else {
Some(info.to_string())
};
Some((Block::CodeBlock { lang, code }, j))
}
fn route_special_fence(info: &str, code: &str) -> Option<Block> {
let source = || code.trim_end().to_string();
match info {
"hikari" => Some(Block::LiveComponent {
source: source(),
lang: None,
}),
s if s.starts_with("hikari:") => {
let lang = s.strip_prefix("hikari:").unwrap().to_string();
Some(Block::LiveComponent {
source: source(),
lang: Some(lang),
})
}
"mermaid" => Some(Block::Diagram {
kind: crate::markdown::ast::DiagramKind::Mermaid,
source: source(),
}),
"math" | "latex" | "katex" => Some(Block::Diagram {
kind: crate::markdown::ast::DiagramKind::Math,
source: source(),
}),
_ => None,
}
}
fn leading_fence(s: &str) -> Option<(char, usize)> {
let c = s.chars().next()?;
if c != '`' && c != '~' {
return None;
}
let n = s.chars().take_while(|&ch| ch == c).count();
if n >= 3 {
Some((c, n))
} else {
None
}
}
fn atx_level(t: &str) -> Option<usize> {
let hashes = t.chars().take_while(|&c| c == '#').count();
if hashes == 0 || hashes > 6 {
return None;
}
match t[hashes..].chars().next() {
None | Some(' ') | Some('\t') => Some(hashes),
_ => None,
}
}
fn parse_atx_heading(
line: &str,
i: usize,
stack: &mut Vec<(usize, String)>,
) -> Option<(Block, usize)> {
let trimmed = line.trim_start();
let hashes = atx_level(trimmed)?;
let rest = &trimmed[hashes..];
let text = parse_inline(rest.trim());
let plain = inline_plain_text(&text);
while stack.last().is_some_and(|(lvl, _)| *lvl >= hashes) {
stack.pop();
}
stack.push((hashes, plain));
Some((
Block::Heading {
level: hashes as u8,
text,
},
i + 1,
))
}
fn is_thematic_break(line: &str) -> bool {
let t = line.trim();
if t.is_empty() {
return false;
}
let first = t.chars().next().unwrap();
if first != '-' && first != '*' && first != '_' {
return false;
}
t.chars().all(|c| c == first || c == ' ' || c == '\t')
&& t.chars().filter(|&c| c == first).count() >= 3
}
fn parse_html_block(lines: &[&str], i: usize) -> Option<(Block, usize)> {
let trimmed = lines[i].trim_start();
if !is_html_block_start(trimmed) {
return None;
}
if html_line_is_self_contained(trimmed) {
return Some((Block::Html(lines[i].to_string()), i + 1));
}
let mut buf = String::from(lines[i]);
buf.push('\n');
let mut j = i + 1;
while j < lines.len() {
let l = lines[j];
let lt = l.trim_start();
if lt.is_empty() {
break;
}
if !lt.starts_with('<') {
break;
}
buf.push_str(l);
buf.push('\n');
j += 1;
}
Some((Block::Html(buf), j))
}
fn is_html_block_start(s: &str) -> bool {
let bytes = s.as_bytes();
if bytes.first() != Some(&b'<') {
return false;
}
if bytes.starts_with(b"<!--") || bytes.starts_with(b"<!") || bytes.starts_with(b"<?") {
return true;
}
let mut k = 1;
if bytes.get(k) == Some(&b'/') {
k += 1;
}
bytes.get(k).is_some_and(|b| b.is_ascii_alphabetic())
}
fn html_line_is_self_contained(s: &str) -> bool {
if s.ends_with("/>") {
return true;
}
let after_open = match s.strip_prefix('<') {
Some(rest) => rest,
None => return false,
};
let name: String = after_open
.chars()
.take_while(|c| c.is_ascii_alphanumeric())
.collect();
if name.is_empty() {
return false;
}
let Some(open_end) = after_open.find('>') else {
return false;
};
let close = format!("</{name}>");
s[open_end + 1..].contains(&close)
}
fn parse_center_container(
lines: &[&str],
starts: &[usize],
ends: &[usize],
i: usize,
scan: &mut Scan<'_>,
) -> Option<(Block, usize)> {
let trimmed = lines[i].trim_start();
if !trimmed.starts_with("<div") {
return None;
}
let gt = trimmed.find('>')?;
let attrs = trimmed[4..gt].trim().to_string();
let mut depth: i32 = 1;
let mut j = i + 1;
while j < lines.len() {
let lt = lines[j].trim();
if lt.starts_with("<div") {
depth += 1;
} else if lt == "</div>" {
depth -= 1;
if depth == 0 {
break;
}
}
j += 1;
}
if j >= lines.len() {
return None;
}
let mut inner = Scan {
full: scan.full,
shift: TableShift {
line_shift: scan.shift.line_shift + i + 1,
},
stack: scan.stack.clone(),
ctx: scan.ctx,
list_depth: scan.list_depth,
};
let children = parse_spanned_lines(
&lines[i + 1..j],
&starts[i + 1..j],
&ends[i + 1..j],
&mut inner,
);
if attrs.contains("align=\"center\"") || attrs.contains("align=center") {
Some((Block::Center(children), j + 1))
} else {
Some((Block::Div { attrs, children }, j + 1))
}
}
fn parse_blockquote(
lines: &[&str],
starts: &[usize],
ends: &[usize],
i: usize,
scan: &mut Scan<'_>,
) -> Option<(Block, usize)> {
if !lines[i].trim_start().starts_with('>') {
return None;
}
let mut inner_lines: Vec<&str> = Vec::new();
let mut inner_starts: Vec<usize> = Vec::new();
let mut inner_ends: Vec<usize> = Vec::new();
let mut j = i;
while j < lines.len() {
let t = lines[j].trim_start();
if let Some(rest) = t.strip_prefix('>') {
let rest = rest.strip_prefix(' ').unwrap_or(rest);
let prefix_len = lines[j].len() - rest.len();
inner_lines.push(rest);
inner_starts.push(starts[j] + prefix_len);
inner_ends.push(starts[j] + prefix_len + rest.len());
j += 1;
} else if !lines[j].trim().is_empty() {
inner_lines.push(lines[j]);
inner_starts.push(starts[j]);
inner_ends.push(ends[j]);
j += 1;
} else {
break;
}
}
let mut inner = Scan {
full: scan.full,
shift: TableShift {
line_shift: scan.shift.line_shift + i,
},
stack: scan.stack.clone(),
ctx: scan.ctx,
list_depth: scan.list_depth,
};
let children = parse_spanned_lines(&inner_lines, &inner_starts, &inner_ends, &mut inner);
Some((Block::Blockquote(children), j))
}
fn parse_table(lines: &[&str], i: usize) -> Option<(Block, usize)> {
if i + 1 >= lines.len() {
return None;
}
let header_line = lines[i].trim();
let sep_line = lines[i + 1].trim();
if !header_line.contains('|') || !is_table_separator(sep_line) {
return None;
}
let headers = split_row(header_line)
.iter()
.map(|c| parse_inline(c))
.collect();
let mut rows = Vec::new();
let mut j = i + 2;
while j < lines.len() {
let l = lines[j].trim();
if l.is_empty() || !l.contains('|') {
break;
}
let row = split_row(l).iter().map(|c| parse_inline(c)).collect();
rows.push(row);
j += 1;
}
Some((Block::Table { headers, rows }, j))
}
fn is_table_separator(s: &str) -> bool {
!s.is_empty()
&& s.chars()
.all(|c| c == '|' || c == '-' || c == ':' || c == ' ' || c == '\t')
&& s.contains('-')
}
fn split_row(line: &str) -> Vec<String> {
let line = line.trim_matches('|').trim();
line.split('|').map(|c| c.trim().to_string()).collect()
}
struct ListMarker {
ordered: bool,
number: usize,
indent: usize,
content_indent: usize,
text: String,
}
struct RawItem {
content_indent: usize,
lines: Vec<String>,
}
const MAX_LIST_DEPTH: usize = 8;
fn parse_list(lines: &[&str], i: usize, depth: usize) -> Option<(Block, usize)> {
let first = list_item_marker(lines[i])?;
let ordered = first.ordered;
let base = first.indent;
let mut raw: Vec<RawItem> = Vec::new();
let mut j = i;
while j < lines.len() {
let line = lines[j];
if line.trim().is_empty() {
let mut k = j + 1;
while k < lines.len() && lines[k].trim().is_empty() {
k += 1;
}
if k >= lines.len() || !list_continues(lines[k], base, ordered) {
break;
}
if let Some(last) = raw.last_mut() {
last.lines.push(String::new());
}
j = k;
continue;
}
if let Some(m) = list_item_marker(line) {
if m.indent == base && m.ordered == ordered {
raw.push(RawItem {
content_indent: m.content_indent,
lines: vec![m.text],
});
j += 1;
continue;
}
if m.indent > base && !raw.is_empty() {
let item = raw.last_mut().expect("raw is non-empty");
if depth + 1 < MAX_LIST_DEPTH {
item.lines.push(strip_indent(line, item.content_indent));
} else {
item.lines.push(line.trim().to_string());
}
j += 1;
continue;
}
break;
}
if !raw.is_empty() && leading_indent(line) > base {
let item = raw.last_mut().expect("raw is non-empty");
item.lines.push(strip_indent(line, item.content_indent));
j += 1;
continue;
}
if !raw.is_empty() && !starts_block(line) {
let item = raw.last_mut().expect("raw is non-empty");
item.lines.push(line.trim().to_string());
j += 1;
continue;
}
break;
}
if raw.is_empty() {
return None;
}
let items: Vec<ListItem> = raw
.into_iter()
.map(|item| finish_item(item, depth))
.collect();
Some((
Block::List {
ordered,
start: if ordered { first.number } else { 1 },
items,
},
j,
))
}
fn finish_item(item: RawItem, depth: usize) -> ListItem {
let mut lines = item.lines;
while lines.last().map(|l| l.trim().is_empty()).unwrap_or(false) {
lines.pop();
}
if lines.is_empty() {
return ListItem {
inlines: Vec::new(),
children: Vec::new(),
};
}
let joined = lines.join("\n");
if depth >= MAX_LIST_DEPTH {
return ListItem {
inlines: parse_inline(&joined),
children: Vec::new(),
};
}
let mut blocks = parse_with_depth(&joined, depth + 1);
let inlines = match blocks.first() {
Some(Block::Paragraph(_)) => match blocks.remove(0) {
Block::Paragraph(inlines) => inlines,
_ => unreachable!("checked above"),
},
_ => Vec::new(),
};
ListItem {
inlines,
children: blocks,
}
}
fn list_continues(line: &str, base: usize, ordered: bool) -> bool {
match list_item_marker(line) {
Some(m) if m.indent == base => m.ordered == ordered,
Some(m) => m.indent > base,
None => leading_indent(line) > base,
}
}
fn leading_indent(line: &str) -> usize {
line.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.map(|c| if c == '\t' { 4 } else { 1 })
.sum()
}
fn strip_indent(line: &str, width: usize) -> String {
let mut removed = 0usize;
let mut cut = 0usize;
for (idx, ch) in line.char_indices() {
if removed >= width {
break;
}
match ch {
' ' => removed += 1,
'\t' if removed + 4 <= width => removed += 4,
_ => break,
}
cut = idx + ch.len_utf8();
}
line[cut..].to_string()
}
fn list_item_marker(line: &str) -> Option<ListMarker> {
let indent = leading_indent(line);
let t = line.trim_start();
let bytes = t.as_bytes();
if bytes.is_empty() {
return None;
}
if matches!(bytes[0], b'-' | b'*' | b'+') && bytes.get(1) == Some(&b' ') {
return Some(ListMarker {
ordered: false,
number: 1,
indent,
content_indent: indent + 2,
text: t[2..].to_string(),
});
}
let digits_end = bytes.iter().take_while(|&&b| b.is_ascii_digit()).count();
if (1..=9).contains(&digits_end)
&& bytes.get(digits_end) == Some(&b'.')
&& bytes.get(digits_end + 1) == Some(&b' ')
{
let number = t[..digits_end].parse().unwrap_or(1);
return Some(ListMarker {
ordered: true,
number,
indent,
content_indent: indent + digits_end + 2,
text: t[digits_end + 2..].to_string(),
});
}
None
}
fn starts_block(line: &str) -> bool {
let t = line.trim_start();
atx_level(t).is_some() || t.starts_with('>') || t.starts_with("```") || t.starts_with("~~~")
}
fn parse_paragraph(lines: &[&str], i: usize) -> (Block, usize) {
let mut buf = String::new();
let mut j = i;
while j < lines.len() {
let line = lines[j];
if line.trim().is_empty() || starts_block(line) || list_item_marker(line).is_some() {
break;
}
if !buf.is_empty() {
buf.push('\n');
}
buf.push_str(line);
j += 1;
}
(Block::Paragraph(parse_inline(&buf)), j)
}
fn strip_spans(blocks: Vec<SpannedBlock>) -> Vec<Block> {
blocks.into_iter().map(|sb| sb.block).collect()
}
fn parse_inline(input: &str) -> Vec<Inline> {
let mut pairs = match InlineParser::parse(Rule::inline_seq, input) {
Ok(p) => p,
Err(_) => return vec![Inline::Text(input.to_string())],
};
let Some(seq) = pairs.next() else {
return vec![Inline::Text(input.to_string())];
};
seq.into_inner().map(build_inline).collect()
}
fn build_inline(pair: Pair<Rule>) -> Inline {
let span_text = pair.as_str().to_string();
let Some(inner) = pair.into_inner().next() else {
return Inline::Text(span_text);
};
match inner.as_rule() {
Rule::badge_link => {
let full = inner.as_str();
let alt = full
.strip_prefix("[)
.map(|(alt, _)| alt.to_string())
.unwrap_or_default();
let urls: Vec<String> = inner.into_inner().map(|p| p.as_str().to_string()).collect();
let img_url = urls.first().cloned().unwrap_or_default();
let link_url = urls.get(1).cloned().unwrap_or_default();
Inline::Link {
text: vec![Inline::Image { alt, url: img_url }],
url: link_url,
}
}
Rule::image => {
let kids: Vec<_> = inner.into_inner().collect();
let alt = kids
.first()
.map(|p| strip_delim(p.as_str(), '[', ']'))
.unwrap_or_default();
let url = kids
.get(1)
.map(|p| p.as_str().to_string())
.unwrap_or_default();
Inline::Image { alt, url }
}
Rule::link => {
let kids: Vec<_> = inner.into_inner().collect();
let label = kids
.first()
.map(|p| strip_delim(p.as_str(), '[', ']'))
.unwrap_or_default();
let url = kids
.get(1)
.map(|p| p.as_str().to_string())
.unwrap_or_default();
Inline::Link {
text: parse_inline(&label),
url,
}
}
Rule::code_span => Inline::Code(strip_delim(inner.as_str(), '`', '`')),
Rule::strong => Inline::Strong(inner.into_inner().map(build_inline).collect()),
Rule::emphasis => Inline::Emphasis(inner.into_inner().map(build_inline).collect()),
Rule::inline_html => Inline::InlineHtml(inner.as_str().to_string()),
Rule::entity => Inline::Text(decode_entity(inner.as_str())),
Rule::raw_double_atom | Rule::raw_single_atom => Inline::Text(inner.as_str().to_string()),
Rule::escape => {
let ch = inner
.as_str()
.chars()
.nth(1)
.map(|c| c.to_string())
.unwrap_or_default();
Inline::Text(ch)
}
Rule::raw => Inline::Text(inner.as_str().to_string()),
_ => Inline::Text(inner.as_str().to_string()),
}
}
fn strip_delim(s: &str, open: char, close: char) -> String {
let s = s.strip_prefix(open).unwrap_or(s);
let s = s.strip_suffix(close).unwrap_or(s);
s.to_string()
}
fn decode_entity(s: &str) -> String {
let body = &s[1..s.len() - 1]; if let Some(num) = body.strip_prefix('#') {
let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
u32::from_str_radix(hex, 16).ok()
} else {
num.parse::<u32>().ok()
};
return code
.and_then(char::from_u32)
.map(|c| c.to_string())
.unwrap_or_else(|| s.to_string());
}
let ch = match body {
"amp" => '&',
"lt" => '<',
"gt" => '>',
"quot" => '"',
"apos" => '\'',
"nbsp" => '\u{00A0}',
"ensp" => '\u{2002}',
"emsp" => '\u{2003}',
"thinsp" => '\u{2009}',
"middot" => '·',
"bull" => '•',
"hellip" => '…',
"mdash" => '—',
"ndash" => '–',
"lsquo" => '‘',
"rsquo" => '’',
"ldquo" => '“',
"rdquo" => '”',
"sbquo" => '‚',
"bdquo" => '„',
"dagger" => '†',
"Dagger" => '‡',
"permil" => '‰',
"prime" => '′',
"Prime" => '″',
"lsaquo" => '‹',
"rsaquo" => '›',
"laquo" => '«',
"raquo" => '»',
"copy" => '©',
"reg" => '®',
"trade" => '™',
"deg" => '°',
"plusmn" => '±',
"times" => '×',
"divide" => '÷',
"micro" => 'µ',
"para" => '¶',
"sect" => '§',
"pound" => '£',
"yen" => '¥',
"euro" => '€',
"cent" => '¢',
"curren" => '¤',
"brvbar" => '¦',
"ordf" => 'ª',
"ordm" => 'º',
"not" => '¬',
"shy" => '\u{00AD}',
"macr" => '¯',
"acute" => '´',
"cedil" => '¸',
"uml" => '¨',
"sup1" => '¹',
"sup2" => '²',
"sup3" => '³',
"frac14" => '¼',
"frac12" => '½',
"frac34" => '¾',
"iexcl" => '¡',
"iquest" => '¿',
_ => return s.to_string(),
};
ch.to_string()
}
#[cfg(test)]
mod span_tests {
use super::*;
#[test]
fn spans_cover_full_file_coordinates() {
let src = "# Title\n\nIntro paragraph.\n\n```rust\ncode\n```\n";
let blocks = parse_doc(src);
assert_eq!(blocks.len(), 3);
assert_eq!(blocks[0].span.start_line, 1);
assert_eq!(blocks[0].span.end_line, 1);
assert_eq!(
&src[blocks[0].span.start_byte..blocks[0].span.end_byte],
"# Title"
);
assert_eq!(blocks[1].span.start_line, 3);
assert_eq!(
&src[blocks[1].span.start_byte..blocks[1].span.end_byte],
"Intro paragraph."
);
assert_eq!(blocks[2].span.start_line, 5);
assert_eq!(blocks[2].span.end_line, 7);
assert!(src[blocks[2].span.start_byte..blocks[2].span.end_byte].starts_with("```rust"));
}
#[test]
fn frontmatter_offsets_are_compensated() {
let src = "---\ntitle: T\n---\n# Body Heading\n\ntext\n";
let blocks = parse_doc(src);
assert_eq!(blocks.len(), 2);
assert_eq!(blocks[0].span.start_line, 4);
assert_eq!(
&src[blocks[0].span.start_byte..blocks[0].span.end_byte],
"# Body Heading"
);
assert_eq!(blocks[1].span.start_line, 6);
}
#[test]
fn heading_paths_follow_the_stack() {
let src = "# A\n\ntext\n\n## B\n\ntext2\n\n### C\n\nback to ## level\n\n## D\n\ntail\n";
let blocks = parse_doc(src);
let paths: Vec<Vec<String>> = blocks.iter().map(|b| b.heading_path.clone()).collect();
assert_eq!(paths[0], vec!["A"]); assert_eq!(paths[1], vec!["A"]);
assert_eq!(paths[2], vec!["A", "B"]); assert_eq!(paths[3], vec!["A", "B"]);
assert_eq!(paths[4], vec!["A", "B", "C"]);
assert_eq!(paths[5], vec!["A", "B", "C"]); assert_eq!(paths[6], vec!["A", "D"]); assert_eq!(paths[7], vec!["A", "D"]);
}
#[test]
fn container_headings_do_not_extend_the_document_stack() {
let src = "# Top\n\n> ## Quoted\n>\n> quoted text\n\nafter\n";
let blocks = parse_doc(src);
let quote = &blocks[1];
assert!(matches!(quote.block, Block::Blockquote(_)));
assert_eq!(quote.heading_path, vec!["Top"]);
let Block::Blockquote(inner) = "e.block else {
panic!("expected blockquote");
};
assert_eq!(inner[0].heading_path, vec!["Top", "Quoted"]);
assert_eq!(inner[1].heading_path, vec!["Top", "Quoted"]);
assert_eq!(blocks[2].heading_path, vec!["Top"]);
}
#[test]
fn block_ids_are_content_addressed_and_stable() {
let src = "# A\n\npara one\n\n## B\n\npara two\n";
let blocks = parse_doc(src);
let id_a = &blocks[1].id;
let src2 = "# Z\n\npara one\n";
let blocks2 = parse_doc(src2);
assert_eq!(id_a, &blocks2[1].id);
let dup = parse_doc("dup block\n\ndup block\n");
assert_ne!(dup[0].id, dup[1].id);
assert!(dup[1].id.starts_with(&dup[0].id));
}
#[test]
fn nested_container_blocks_carry_their_own_spans() {
let src = "<div align=\"center\">\n\ninner para\n\n</div>\n\n> quoted\n";
let blocks = parse_doc(src);
let Block::Center(children) = &blocks[0].block else {
panic!("expected center");
};
assert_eq!(children.len(), 1);
assert_eq!(
&src[children[0].span.start_byte..children[0].span.end_byte],
"inner para"
);
let Block::Blockquote(inner) = &blocks[1].block else {
panic!("expected blockquote");
};
assert_eq!(
&src[inner[0].span.start_byte..inner[0].span.end_byte],
"quoted"
);
assert_eq!(children[0].span.start_line, 3);
assert_eq!(children[0].span.end_line, 3);
assert_eq!(inner[0].span.start_line, 7);
assert_eq!(inner[0].span.end_line, 7);
}
#[test]
fn nested_blocks_report_file_lines_not_container_relative_lines() {
let src = "# Title\n\n<div align=\"center\">\n\nchild para\n\n</div>\n\n> quoted here\n";
let blocks = parse_doc(src);
let Block::Center(children) = &blocks[1].block else {
panic!("expected center as second block");
};
assert_eq!(blocks[1].span.start_line, 3);
assert_eq!(children[0].span.start_line, 5);
assert_eq!(children[0].span.end_line, 5);
assert_eq!(
&src[children[0].span.start_byte..children[0].span.end_byte],
"child para"
);
let Block::Blockquote(inner) = &blocks[2].block else {
panic!("expected blockquote as third block");
};
assert_eq!(blocks[2].span.start_line, 9);
assert_eq!(inner[0].span.start_line, 9);
assert_eq!(inner[0].span.end_line, 9);
assert_eq!(
&src[inner[0].span.start_byte..inner[0].span.end_byte],
"quoted here"
);
}
#[test]
fn parse_strips_spans_and_keeps_shape() {
let src = "# H\n\n> quoted para\n\ntext\n";
let bare = parse(src);
assert_eq!(bare.len(), 3);
assert!(
matches!(&bare[1], Block::Blockquote(inner) if matches!(inner[0].block, Block::Paragraph(_)))
);
}
}
#[cfg(test)]
mod list_tests {
use super::*;
fn list_of(blocks: &[Block]) -> (&str, usize, &Vec<ListItem>) {
match &blocks[0] {
Block::List {
ordered,
start,
items,
} => (if *ordered { "ol" } else { "ul" }, *start, items),
other => panic!("expected a list, got {other:?}"),
}
}
fn item_text(item: &ListItem) -> String {
item.inlines
.iter()
.map(|i| match i {
Inline::Text(t) => t.clone(),
_ => String::new(),
})
.collect()
}
#[test]
fn blank_lines_between_items_keep_one_list() {
let blocks = parse("1. one\n\n2. two\n\n3. three\n");
assert_eq!(blocks.len(), 1, "list split into blocks: {blocks:?}");
let (tag, start, items) = list_of(&blocks);
assert_eq!(tag, "ol");
assert_eq!(start, 1);
assert_eq!(items.len(), 3);
assert_eq!(item_text(&items[2]).trim(), "three");
}
#[test]
fn nested_markers_become_child_lists() {
let blocks = parse("1. parent\n - child a\n - child b\n2. second\n");
assert_eq!(blocks.len(), 1, "nested list escaped the block: {blocks:?}");
let (_, _, items) = list_of(&blocks);
assert_eq!(items.len(), 2, "child items flattened into siblings");
assert_eq!(item_text(&items[0]).trim(), "parent");
match &items[0].children[0] {
Block::List {
ordered,
items: kids,
..
} => {
assert!(!ordered);
assert_eq!(kids.len(), 2);
assert_eq!(item_text(&kids[1]).trim(), "child b");
}
other => panic!("expected a child list, got {other:?}"),
}
}
#[test]
fn ordered_list_carries_its_first_number() {
let blocks = parse("3. three\n4. four\n");
let (_, start, items) = list_of(&blocks);
assert_eq!(start, 3, "the start number was dropped");
assert_eq!(items.len(), 2);
}
#[test]
fn a_different_marker_kind_starts_a_new_block() {
let blocks = parse("- bullet\n1. ordered\n");
assert_eq!(blocks.len(), 2, "kinds merged into one list: {blocks:?}");
assert_eq!(list_of(&blocks[..1]).0, "ul");
assert_eq!(list_of(&blocks[1..]).0, "ol");
}
#[test]
fn indented_continuation_stays_in_its_item() {
let blocks = parse("1. first line\n continued here\n2. second\n");
let (_, _, items) = list_of(&blocks);
assert_eq!(items.len(), 2);
assert!(
item_text(&items[0]).contains("continued here"),
"continuation lost: {:?}",
items[0]
);
}
#[test]
fn a_plain_paragraph_after_a_blank_line_ends_the_list() {
let blocks = parse("- bullet\n\nplain paragraph\n");
assert_eq!(
blocks.len(),
2,
"paragraph swallowed by the list: {blocks:?}"
);
assert!(matches!(blocks[1], Block::Paragraph(_)));
}
#[test]
fn a_table_under_an_item_stays_a_table() {
let src = "- lead-in:\n\n | Base | Where |\n |---|---|\n | A | one |\n";
let blocks = parse(src);
let (_, _, items) = list_of(&blocks);
assert_eq!(items[0].children.len(), 1, "table lost: {items:?}");
assert!(
matches!(items[0].children[0], Block::Table { .. }),
"child is not a table: {:?}",
items[0].children[0]
);
}
#[test]
fn wrapped_item_text_at_the_margin_stays_in_the_item() {
let src = "1. Branch deadline — a wall-clock bound per branch; a branch\n that misses it is folded into the report\nunder reuse of the failing-branch\nsemantics.\n2. Second item.\n";
let blocks = parse(src);
assert_eq!(blocks.len(), 1, "list split into blocks: {blocks:?}");
let (_, _, items) = list_of(&blocks);
assert_eq!(items.len(), 2, "items lost: {items:?}");
let text = item_text(&items[0]);
assert!(
text.contains("under reuse of the failing-branch"),
"lazy continuation dropped: {text:?}"
);
assert!(
text.contains("semantics."),
"continuation tail dropped: {text:?}"
);
}
#[test]
fn a_nine_digit_ordinal_is_a_marker_and_ten_digits_is_text() {
let blocks = parse("123456789. nine digits\n");
assert!(matches!(blocks[0], Block::List { .. }), "{blocks:?}");
let blocks = parse("1234567890. ten digits\n");
assert!(
matches!(blocks[0], Block::Paragraph(_)),
"over-long ordinal became a list: {blocks:?}"
);
}
#[test]
fn tab_indented_nesting_keeps_its_depth() {
let src = "- parent\n\t- child\n";
let blocks = parse(src);
let (_, _, items) = list_of(&blocks);
assert_eq!(
items.len(),
1,
"tab-indented child became a sibling: {items:?}"
);
assert!(
matches!(items[0].children.first(), Some(Block::List { .. })),
"tab-indented nesting lost: {:?}",
items[0].children
);
}
#[test]
fn absurd_nesting_depth_degrades_instead_of_overflowing() {
let src: String = std::iter::repeat_n("- ", 2000).collect::<String>() + "x\n";
let blocks = parse(&src);
assert!(!blocks.is_empty(), "deep nesting produced nothing");
}
#[test]
fn a_fence_under_an_item_stays_code() {
let src = "1. run this:\n\n ```rust\n let x = 1;\n ```\n";
let blocks = parse(src);
let (_, _, items) = list_of(&blocks);
assert!(
matches!(
items[0].children.first(),
Some(Block::CodeBlock { lang, .. }) if lang.as_deref() == Some("rust")
),
"fence lost: {items:?}"
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn badge_link_is_a_link_wrapping_an_image() {
let blocks = parse("text [](./LICENSE) tail");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a paragraph, got {:?}", blocks);
};
let link = inlines
.iter()
.find_map(|i| match i {
Inline::Link { text, url } => Some((text, url)),
_ => None,
})
.expect("a badge link");
assert_eq!(link.1, "./LICENSE");
assert!(
text_contains_image(link.0, "License", "badge.svg"),
"expected an image span inside the link, got {:?}",
link.0
);
}
#[test]
fn raw_html_block_passes_through_verbatim() {
let blocks = parse("<h1 align=\"center\">Lagrange</h1>\n\nparagraph");
assert_eq!(blocks.len(), 2);
let Block::Html(raw) = &blocks[0] else {
panic!("expected an Html block, got {:?}", blocks[0]);
};
assert!(raw.contains("<h1 align=\"center\">Lagrange</h1>"));
assert!(matches!(blocks[1], Block::Paragraph(_)));
}
#[test]
fn self_closing_html_is_a_single_line_block() {
let blocks = parse("<p align=\"center\"><img src=\"logo.webp\" /></p>");
assert!(
matches!(&blocks[..], [Block::Html(_)]),
"expected a single Html block, got {:?}",
blocks
);
}
#[test]
fn gfm_table_row_with_many_bold_cells_does_not_explode() {
let row = "| **L2** coord | **2a** peers | **2b** lease | **fork** |";
let blocks = parse(row);
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks);
};
let bold_count = inlines
.iter()
.filter(|i| matches!(i, Inline::Strong(_)))
.count();
assert_eq!(bold_count, 4, "inlines: {:?}", inlines);
}
#[test]
fn underscores_are_not_emphasis() {
let blocks = parse("see my_var and snake_case_name here");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks);
};
assert!(
inlines.iter().all(|i| matches!(i, Inline::Text(_))),
"underscores leaked into emphasis: {:?}",
inlines
);
let joined: String = inlines
.iter()
.map(|i| match i {
Inline::Text(s) => s.clone(),
_ => String::new(),
})
.collect();
assert_eq!(joined, "see my_var and snake_case_name here");
}
#[test]
fn asterisk_emphasis_still_works() {
let blocks = parse("a *italic* and **bold** z");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks);
};
assert!(inlines.iter().any(|i| matches!(i, Inline::Emphasis(_))));
assert!(inlines.iter().any(|i| matches!(i, Inline::Strong(_))));
}
fn joined_text(inlines: &[Inline]) -> String {
inlines
.iter()
.map(|i| match i {
Inline::Text(s) => s.clone(),
Inline::Strong(inner) | Inline::Emphasis(inner) => joined_text(inner),
_ => String::new(),
})
.collect()
}
#[test]
fn named_entities_decode_to_text() {
let blocks = parse("GitHub · Docs & more — done");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks[0]);
};
assert_eq!(
joined_text(inlines),
"GitHub \u{00A0}·\u{00A0} Docs & more — done"
);
}
#[test]
fn numeric_entities_decode_to_text() {
let blocks = parse("AB&#63;");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks[0]);
};
assert_eq!(joined_text(inlines), "AB?");
}
#[test]
fn unknown_or_invalid_entities_pass_through_literally() {
let blocks = parse("a &nosuchentity; b � c &dangling");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks[0]);
};
assert_eq!(
joined_text(inlines),
"a &nosuchentity; b � c &dangling"
);
}
#[test]
fn entities_work_inside_emphasis() {
let blocks = parse("**a b**");
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks[0]);
};
assert_eq!(joined_text(inlines), "a \u{00A0} b");
}
#[test]
fn hash_glued_to_text_is_paragraph_content_not_a_wedge() {
let blocks = parse("intro line\n#604). tail text\n\nnext paragraph");
assert_eq!(blocks.len(), 2);
let Block::Paragraph(inlines) = &blocks[0] else {
panic!("expected a Paragraph, got {:?}", blocks[0]);
};
let text = joined_text(inlines);
assert!(text.contains("intro line"), "inlines: {:?}", inlines);
assert!(text.contains("#604)."), "inlines: {:?}", inlines);
assert!(matches!(blocks[1], Block::Paragraph(_)));
}
#[test]
fn hash_glued_to_text_alone_still_parses() {
let blocks = parse("#604");
assert!(
matches!(&blocks[..], [Block::Paragraph(_)]),
"expected one Paragraph, got {:?}",
blocks
);
}
fn text_contains_image(inlines: &[Inline], alt: &str, url_part: &str) -> bool {
inlines.iter().any(|i| match i {
Inline::Image { alt: a, url } => a == alt && url.contains(url_part),
Inline::Strong(inner) | Inline::Emphasis(inner) => {
text_contains_image(inner, alt, url_part)
}
_ => false,
})
}
}