use crate::model::names::Name;
pub const COUNTERS_SLOT: &str = "flm.numbering.counters";
pub const STYLES_SLOT: &str = "flm.numbering.styles";
pub const WITHIN_JOINERS_SLOT: &str = "flm.numbering.within-joiners";
pub const NUMBER_WRITERS_SLOT: &str = "flm.numbering.number-writers";
pub const PARENT_SETS_SLOT: &str = "flm.numbering.parent-sets";
pub const RESERVED_PREFIX: &str = "_";
pub const PARENT_PLACEHOLDER: &str = "_parent";
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct ParentSetDecl {
pub name: Name,
pub counters: Vec<Name>,
}
impl ParentSetDecl {
pub fn new(
name: impl Into<Name>,
counters: impl IntoIterator<Item = impl Into<Name>>,
) -> ParentSetDecl {
ParentSetDecl { name: name.into(), counters: counters.into_iter().map(Into::into).collect() }
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Parents {
One(Name),
Any(Vec<Name>),
Set(Name),
}
impl Parents {
pub(super) fn describe(&self) -> String {
match self {
Parents::One(name) => format!("`{name}`"),
Parents::Any(names) => format!("any of {}", quoted_list(names)),
Parents::Set(name) => format!("the parent set `{name}`"),
}
}
}
pub(super) fn quoted_list(names: &[Name]) -> String {
names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", ")
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum WithinJoinerSpec {
Joined(String),
Template(String),
Bare,
Named(Name),
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Within {
pub parents: Parents,
pub joiner: WithinJoinerSpec,
pub no_restart: bool,
}
impl Within {
pub fn parent(parent: impl Into<Name>) -> Within {
Within::with_parents(Parents::One(parent.into()))
}
pub fn parents(parents: impl IntoIterator<Item = impl Into<Name>>) -> Within {
Within::with_parents(Parents::Any(parents.into_iter().map(Into::into).collect()))
}
pub fn parent_set(name: impl Into<Name>) -> Within {
Within::with_parents(Parents::Set(name.into()))
}
fn with_parents(parents: Parents) -> Within {
Within { parents, joiner: WithinJoinerSpec::Joined(".".to_string()), no_restart: false }
}
pub fn no_restart(mut self) -> Within {
self.no_restart = true;
self
}
pub fn joined_by(mut self, text: impl Into<String>) -> Within {
self.joiner = WithinJoinerSpec::Joined(text.into());
self
}
pub fn template(mut self, text: impl Into<String>) -> Within {
self.joiner = WithinJoinerSpec::Template(text.into());
self
}
pub fn displayed_bare(mut self) -> Within {
self.joiner = WithinJoinerSpec::Bare;
self
}
pub fn joiner_named(mut self, name: impl Into<Name>) -> Within {
self.joiner = WithinJoinerSpec::Named(name.into());
self
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct CounterDecl {
pub name: Name,
pub docs: String,
pub default_style: Name,
pub within: Option<Within>,
pub nesting: Option<WithinJoinerSpec>,
}
impl CounterDecl {
pub fn new(name: impl Into<Name>, default_style: impl Into<Name>) -> CounterDecl {
CounterDecl {
name: name.into(),
docs: String::new(),
default_style: default_style.into(),
within: None,
nesting: None,
}
}
pub fn docs(mut self, docs: impl Into<String>) -> CounterDecl {
self.docs = crate::kept_docs(docs);
self
}
pub fn within(mut self, within: Within) -> CounterDecl {
self.within = Some(within);
self
}
pub fn nesting(mut self, joiner: WithinJoinerSpec) -> CounterDecl {
self.nesting = Some(joiner);
self
}
}
impl Within {
pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
let Within { parents, joiner, no_restart } = self;
match parents {
Parents::One(name) => {
out.push(0);
digest_text(out, name.as_str());
}
Parents::Any(names) => {
out.push(1);
out.extend_from_slice(&(names.len() as u64).to_le_bytes());
for name in names {
digest_text(out, name.as_str());
}
}
Parents::Set(name) => {
out.push(2);
digest_text(out, name.as_str());
}
}
joiner.digest_into(out);
out.push(u8::from(*no_restart));
}
}
impl WithinJoinerSpec {
pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
match self {
WithinJoinerSpec::Joined(text) => {
out.push(0);
digest_text(out, text);
}
WithinJoinerSpec::Template(text) => {
out.push(1);
digest_text(out, text);
}
WithinJoinerSpec::Bare => out.push(2),
WithinJoinerSpec::Named(name) => {
out.push(3);
digest_text(out, name.as_str());
}
}
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub(super) enum ParentsError {
UnknownSet(Name),
Empty,
}
impl Parents {
pub(super) fn resolve(
&self,
sets: &std::collections::BTreeMap<Name, Vec<Name>>,
) -> Result<Vec<Name>, ParentsError> {
let resolved = match self {
Parents::One(name) => vec![name.clone()],
Parents::Any(names) => names.clone(),
Parents::Set(name) => {
sets.get(name).cloned().ok_or_else(|| ParentsError::UnknownSet(name.clone()))?
}
};
if resolved.is_empty() {
return Err(ParentsError::Empty);
}
Ok(resolved)
}
}
pub(super) fn chains_of(
counter: &Name,
parents_of: &impl Fn(&Name) -> Vec<Name>,
) -> Result<Vec<Vec<Name>>, Vec<Name>> {
let mut path = vec![counter.clone()];
walk_chains(&mut path, parents_of)
}
fn walk_chains(
path: &mut Vec<Name>,
parents_of: &impl Fn(&Name) -> Vec<Name>,
) -> Result<Vec<Vec<Name>>, Vec<Name>> {
let current = path.last().expect("the path holds the counter walked from").clone();
let parents = parents_of(¤t);
if parents.is_empty() {
return Ok(vec![Vec::new()]);
}
let mut chains = Vec::new();
for parent in parents {
if let Some(start) = path.iter().position(|seen| *seen == parent) {
return Err(path[start..].to_vec());
}
path.push(parent.clone());
let above = walk_chains(path, parents_of);
path.pop();
for mut chain in above? {
chain.push(parent.clone());
chains.push(chain);
}
}
Ok(chains)
}
pub(super) fn digest_text(out: &mut Vec<u8>, text: &str) {
out.extend_from_slice(&(text.len() as u64).to_le_bytes());
out.extend_from_slice(text.as_bytes());
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
fn hierarchy(entries: &[(&str, &[&str])]) -> BTreeMap<Name, Vec<Name>> {
entries
.iter()
.map(|(name, parents)| {
(Name::new(*name), parents.iter().map(|parent| Name::new(*parent)).collect())
})
.collect()
}
fn chains(counters: &BTreeMap<Name, Vec<Name>>, counter: &str) -> Result<Vec<String>, Vec<Name>> {
let walked =
chains_of(&Name::new(counter), &|name| counters.get(name).cloned().unwrap_or_default())?;
Ok(walked
.iter()
.map(|chain| chain.iter().map(Name::as_str).collect::<Vec<_>>().join("."))
.collect())
}
#[test]
fn a_chain_runs_outermost_first() {
let counters = hierarchy(&[
("section", &[]),
("subsection", &["section"]),
("equation", &["subsection"]),
]);
assert_eq!(chains(&counters, "equation"), Ok(vec!["section.subsection".to_string()]));
assert_eq!(chains(&counters, "section"), Ok(vec![String::new()]));
}
#[test]
fn a_counter_with_several_parents_has_one_chain_per_parent() {
let counters = hierarchy(&[
("chapter", &[]),
("section", &["chapter"]),
("equation", &["chapter", "section"]),
]);
let walked = chains(&counters, "equation").expect("acyclic");
assert_eq!(walked, ["chapter", "chapter.section"]);
}
#[test]
fn a_hierarchy_that_leads_back_to_itself_is_a_cycle() {
let counters = hierarchy(&[("a", &["b"]), ("b", &["c"]), ("c", &["a"])]);
let cycle = chains(&counters, "a").expect_err("a cycle");
let names: Vec<&str> = cycle.iter().map(Name::as_str).collect();
assert_eq!(names, ["a", "b", "c"]);
}
#[test]
fn a_cycle_through_any_one_parent_is_a_cycle() {
let counters = hierarchy(&[("a", &["x", "b"]), ("b", &["a"]), ("x", &[])]);
let cycle = chains(&counters, "a").expect_err("a cycle");
let names: Vec<&str> = cycle.iter().map(Name::as_str).collect();
assert_eq!(names, ["a", "b"]);
}
#[test]
fn a_walk_stops_at_a_counter_the_view_does_not_know() {
let counters = hierarchy(&[("equation", &["section"])]);
assert_eq!(chains(&counters, "equation"), Ok(vec!["section".to_string()]));
}
#[test]
fn a_counter_is_declared_within_nothing() {
let decl = CounterDecl::new("equation", "flm.math.style.equation");
assert!(decl.within.is_none());
assert_eq!(decl.name.as_str(), "equation");
}
#[test]
fn the_builders_set_what_they_name() {
let decl = CounterDecl::new("subsection", "flm.heading.style.subsection")
.docs("Subsections.")
.within(Within::parent("section"));
assert_eq!(decl.docs, if cfg!(feature = "docs") { "Subsections." } else { "" });
let within = decl.within.expect("declared");
assert_eq!(within.parents, Parents::One(Name::new("section")));
assert_eq!(within.joiner, WithinJoinerSpec::Joined(".".to_string()));
assert!(!within.no_restart);
let any = Within::parents(["chapter", "section"]).no_restart();
assert_eq!(any.parents, Parents::Any(vec![Name::new("chapter"), Name::new("section")]));
assert!(any.no_restart);
let set = Within::parent_set("flm.headings.levels").displayed_bare();
assert_eq!(set.parents, Parents::Set(Name::new("flm.headings.levels")));
assert_eq!(set.joiner, WithinJoinerSpec::Bare);
}
#[test]
fn a_counter_has_no_nesting_joiner_until_it_declares_one() {
let decl = CounterDecl::new("t.list", "t.style.list");
assert!(decl.nesting.is_none());
let nested = decl.nesting(WithinJoinerSpec::Template("#{_parent}.".to_string()));
assert_eq!(nested.nesting, Some(WithinJoinerSpec::Template("#{_parent}.".to_string())));
}
#[test]
fn every_form_of_a_joiner_digests_differently() {
let digest = |spec: &WithinJoinerSpec| {
let mut out = Vec::new();
spec.digest_into(&mut out);
out
};
let forms = [
WithinJoinerSpec::Joined(".".to_string()),
WithinJoinerSpec::Template(".".to_string()),
WithinJoinerSpec::Bare,
WithinJoinerSpec::Named(Name::new(".")),
];
for (index, one) in forms.iter().enumerate() {
for other in &forms[index + 1..] {
assert_ne!(digest(one), digest(other), "{one:?} and {other:?}");
}
}
}
#[test]
fn every_field_of_a_within_changes_its_digest() {
let digest = |within: &Within| {
let mut out = Vec::new();
within.digest_into(&mut out);
out
};
let base = Within::parent("section");
let variants = [
Within::parent("chapter"),
Within::parents(["section"]),
Within::parent_set("section"),
Within::parent("section").joined_by("-"),
Within::parent("section").template("#{section}."),
Within::parent("section").displayed_bare(),
Within::parent("section").joiner_named("section"),
Within::parent("section").no_restart(),
];
for variant in &variants {
assert_ne!(digest(&base), digest(variant), "{variant:?}");
}
assert_eq!(digest(&base), digest(&Within::parent("section")));
}
}