use serde::{Deserialize, Serialize};
use super::{
DocView,
checker::{parents, possible},
};
use crate::{
grammar::{Schema, Section, Shape, States, Text, read, squash},
markdown::{self, Heading},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum MatchedBy {
Text,
Shape,
Renamed,
Frontmatter,
Place,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct HeadingMatch {
pub section: usize,
pub by: MatchedBy,
}
impl HeadingMatch {
pub fn new(section: usize, by: MatchedBy) -> Self {
HeadingMatch { section, by }
}
}
pub fn match_headings(
doc: DocView<'_>,
schema: &Schema,
states: &States,
) -> Vec<Option<HeadingMatch>> {
let possible = possible(states, &schema.core.lifecycle);
let admitted: Vec<usize> = (0..schema.sections.len())
.filter(|&j| schema.sections[j].common.only.admits(&possible))
.collect();
let declared: Vec<&Section> = admitted.iter().map(|&j| &schema.sections[j]).collect();
let parent_of = parents(&declared);
let value = |key: &str| {
doc.frontmatter
.and_then(|f| f.get(key))
.and_then(tramlines_core::Spanned::scalar_text)
};
walk(
&doc.body.headings,
&declared,
&parent_of,
schema.sections_ordered,
&value,
)
.into_iter()
.map(|m| m.map(|(j, kind)| HeadingMatch::new(admitted[j], kind.by())))
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Kind {
Exact(MatchedBy),
Shaped,
Renamed(String),
From(String),
Unbound(String),
}
impl Kind {
fn by(&self) -> MatchedBy {
match self {
Kind::Exact(by) => *by,
Kind::Shaped => MatchedBy::Shape,
Kind::Renamed(_) => MatchedBy::Renamed,
Kind::From(_) | Kind::Unbound(_) => MatchedBy::Place,
}
}
}
pub(super) fn expected_text(
section: &Section,
value: &dyn Fn(&str) -> Option<String>,
) -> Option<String> {
match §ion.heading.shape {
Shape::Text(Text::Literal(t)) => Some(t.clone()),
Shape::Text(Text::From(key)) => value(key).map(|v| markdown::heading_text_of(&v)),
_ => None,
}
}
pub(super) fn inside(parent_of: &[Option<usize>], mut k: usize, j: usize) -> bool {
while let Some(p) = parent_of[k] {
if p == j {
return true;
}
k = p;
}
false
}
pub(super) fn walk(
headings: &[Heading],
declared: &[&Section],
parent_of: &[Option<usize>],
ordered: bool,
value: &dyn Fn(&str) -> Option<String>,
) -> Vec<Option<(usize, Kind)>> {
let mut seen = vec![0usize; declared.len()];
let mut pos = 0usize;
let mut out = Vec::with_capacity(headings.len());
for h in headings {
let found = find_match(h, declared, &seen, pos, ordered, value);
if let Some((j, _)) = &found {
let j = *j;
let section = declared[j];
let passed = if seen.get(pos).is_some_and(|&n| n > 0) {
pos + 1
} else {
pos
};
let returns =
section.repeat && j < pos && (j + 1..passed).all(|k| inside(parent_of, k, j));
seen[j] += 1;
if ordered {
let next = if section.repeat { j } else { j + 1 };
pos = if returns { next } else { pos.max(next) };
}
}
out.push(found);
}
out
}
fn find_match(
h: &Heading,
declared: &[&Section],
seen: &[usize],
pos: usize,
ordered: bool,
value: &dyn Fn(&str) -> Option<String>,
) -> Option<(usize, Kind)> {
let order: Vec<usize> = (pos..declared.len()).chain(0..pos).collect();
let read_heading = h.reading.or_written(&h.text);
let reading = read_heading.text.as_str();
for &j in &order {
let (expected, by) = match &declared[j].heading.read {
Shape::Text(Text::Literal(t)) => (Some(t.clone()), MatchedBy::Text),
Shape::Text(Text::From(key)) => (
value(key).map(|v| read(&markdown::heading_text_of(&v))),
MatchedBy::Frontmatter,
),
_ => (None, MatchedBy::Text),
};
if expected.as_deref() == Some(reading) {
return Some((j, Kind::Exact(by)));
}
}
let shaped = |j: usize| {
!declared[j].is_exact() && declared[j].heading.read.matches(&squash(reading), |_| None)
};
for &j in &order {
if declared[j].level == h.level && shaped(j) {
return Some((j, Kind::Shaped));
}
}
for &j in &order {
if declared[j].renamed_read.iter().any(|r| r == reading) {
let current = expected_text(declared[j], value).unwrap_or_else(|| declared[j].label());
return Some((j, Kind::Renamed(current)));
}
}
let candidates: Vec<usize> = if ordered {
pos.min(declared.len().saturating_sub(1))..pos + 1
} else {
0..declared.len()
}
.filter(|&j| j < declared.len())
.collect();
for j in candidates {
if let Shape::Text(Text::From(key)) = &declared[j].heading.shape
&& seen[j] == 0
&& declared[j].level == h.level
{
let kind = match expected_text(declared[j], value) {
Some(expected) => Kind::From(expected),
None => Kind::Unbound(key.clone()),
};
return Some((j, kind));
}
}
order
.iter()
.find(|&&j| declared[j].level != h.level && shaped(j))
.map(|&j| (j, Kind::Shaped))
}