use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use techy::core::node::NodeTree;
use crate::lang::rewrites::userdefs::template::{CompiledTemplate, TemplateLanguage};
use crate::lang::{BuiltLang, Flm};
use crate::model::names::Name;
use super::decl::{Parents, Within, WithinJoinerSpec, PARENT_PLACEHOLDER};
use super::formats::NumberFormat;
use super::style::{
assemble_pieces, number_tree, parse_text, Ancestor, CounterStyle, FormatError, Piece, StyleError,
};
use super::template::{
compile_text, instantiate_template, occurrences_of, parse_keys, placeholder_starts,
within_vocabulary, AncestorKeys, Binding, Bindings,
};
use super::value::CounterValue;
#[derive(Clone, Debug)]
pub struct Part {
pub stands_for: Vec<(Name, CounterValue)>,
pub content: Arc<NodeTree<Flm>>,
}
impl Part {
pub fn new(
stands_for: Vec<(Name, CounterValue)>,
content: Arc<NodeTree<Flm>>,
) -> Part {
Part { stands_for, content }
}
}
pub trait WithinJoiner: Send + Sync {
fn name(&self) -> &Name;
fn compile(&self, cx: &WithinCx<'_>) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError>;
}
#[derive(Clone)]
pub struct WithinJoinerDecl {
joiner: Arc<dyn WithinJoiner>,
}
impl WithinJoinerDecl {
pub fn new(joiner: Arc<dyn WithinJoiner>) -> WithinJoinerDecl {
WithinJoinerDecl { joiner }
}
pub fn joiner(&self) -> &Arc<dyn WithinJoiner> {
&self.joiner
}
}
impl fmt::Debug for WithinJoinerDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WithinJoinerDecl")
.field("name", &self.joiner.name().as_str())
.finish()
}
}
pub trait CompiledWithinJoiner: Send + Sync + fmt::Debug {
fn counters_written(&self, chain: &[Name]) -> Vec<Name>;
fn parts(&self, ancestors: &[Ancestor], cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError>;
}
pub struct WithinCx<'a> {
lang: &'a BuiltLang,
language: &'a TemplateLanguage,
counters: &'a [Name],
joiners: &'a BTreeMap<Name, Arc<dyn WithinJoiner>>,
}
impl<'a> WithinCx<'a> {
pub(super) fn new(
lang: &'a BuiltLang,
language: &'a TemplateLanguage,
counters: &'a [Name],
joiners: &'a BTreeMap<Name, Arc<dyn WithinJoiner>>,
) -> WithinCx<'a> {
WithinCx { lang, language, counters, joiners }
}
pub fn lang(&self) -> &BuiltLang {
self.lang
}
pub fn parse(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, StyleError> {
let mut warnings = Vec::new();
parse_text(text, self.lang, &mut warnings)
}
pub fn compile_template(
&self,
text: &str,
what: &str,
) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError> {
let vocabulary = within_vocabulary(self.counters.iter());
let whole = compile_text(text, what, &vocabulary, self.lang, self.language)?;
let mut occurrences = Vec::new();
for (name, keys) in occurrences_of(&whole) {
let parsed = parse_keys(&keys).map_err(|key| StyleError::UnknownKey {
text: text.to_string(),
key,
})?;
occurrences.push(Occurrence {
counter: Name::new(name.as_str()),
keys: parsed,
written: keys,
});
}
let shape = self.split(text, &whole, &vocabulary, what, &occurrences);
Ok(Arc::new(Templated { text: text.to_string(), whole, occurrences, shape }))
}
fn split(
&self,
text: &str,
whole: &CompiledTemplate,
vocabulary: &crate::lang::rewrites::userdefs::template::PlaceholderVocabulary,
what: &str,
occurrences: &[Occurrence],
) -> Option<Vec<CompiledTemplate>> {
let starts = placeholder_starts(whole);
if starts.len() != occurrences.len() || starts.is_empty() {
return None;
}
let mut cuts: Vec<usize> = Vec::with_capacity(starts.len() + 1);
cuts.push(0);
cuts.extend(starts.iter().skip(1).copied());
cuts.push(text.len());
let mut parts = Vec::with_capacity(starts.len());
for window in cuts.windows(2) {
let piece = text.get(window[0]..window[1])?;
let compiled = compile_text(piece, what, vocabulary, self.lang, self.language).ok()?;
if occurrences_of(&compiled).len() != 1 {
return None;
}
parts.push(compiled);
}
Some(parts)
}
}
impl Within {
pub fn compile(
&self,
lang: &BuiltLang,
counters: &[Name],
joiners: &[Arc<dyn WithinJoiner>],
) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError> {
match &self.joiner {
WithinJoinerSpec::Joined(text) => {
let mut warnings = Vec::new();
return Ok(Arc::new(Joined {
described: described(&self.parents, text),
joiner: parse_text(text, lang, &mut warnings)?,
}));
}
WithinJoinerSpec::Bare => return Ok(Arc::new(Bare)),
_ => {}
}
let language = TemplateLanguage::new(lang).map_err(|errors| StyleError::ParseFailed {
text: joiner_text(self),
detail: errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "),
})?;
let registered: BTreeMap<Name, Arc<dyn WithinJoiner>> =
joiners.iter().map(|joiner| (joiner.name().clone(), Arc::clone(joiner))).collect();
let cx = WithinCx::new(lang, &language, counters, ®istered);
compile_within(self, &format!("the counter written within {}", self.parents.describe()), &cx)
}
}
pub(super) fn compile_within(
within: &Within,
what: &str,
cx: &WithinCx<'_>,
) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError> {
match &within.joiner {
WithinJoinerSpec::Joined(text) => Ok(Arc::new(Joined {
described: described(&within.parents, text),
joiner: cx.parse(text)?,
})),
WithinJoinerSpec::Bare => Ok(Arc::new(Bare)),
WithinJoinerSpec::Template(text) => cx.compile_template(text, what),
WithinJoinerSpec::Named(name) => {
let Some(joiner) = cx.joiners.get(name) else {
return Err(StyleError::UnknownJoiner { name: name.clone() });
};
joiner.compile(cx)
}
}
}
pub struct JoinCx<'a> {
style: &'a CounterStyle,
}
impl<'a> JoinCx<'a> {
pub(super) fn new(style: &'a CounterStyle) -> JoinCx<'a> {
JoinCx { style }
}
pub fn number_of(&self, ancestor: &Ancestor) -> Result<Arc<NodeTree<Flm>>, FormatError> {
number_tree(&ancestor.style, &ancestor.value, None)
}
pub fn number_of_in(
&self,
ancestor: &Ancestor,
format: NumberFormat,
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
number_tree(&ancestor.style, &ancestor.value, Some(format))
}
pub fn parts_before(
&self,
ancestors: &[Ancestor],
index: usize,
) -> Result<Vec<Part>, FormatError> {
let Some(ancestor) = ancestors.get(index) else { return Ok(Vec::new()) };
let Some(joiner) = &ancestor.joiner else { return Ok(Vec::new()) };
joiner.parts(&ancestors[..index], self)
}
pub fn literal(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, FormatError> {
assemble_pieces(self.style, &[Piece::Digits(text.to_string())])
}
pub fn joined(
&self,
contents: &[Arc<NodeTree<Flm>>],
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
let pieces: Vec<Piece<'_>> = contents.iter().map(Piece::Flm).collect();
assemble_pieces(self.style, &pieces)
}
pub(super) fn style(&self) -> &CounterStyle {
self.style
}
}
fn place_of(
ancestors: &[Ancestor],
counter: &Name,
joiner: &str,
) -> Result<usize, FormatError> {
let place = if counter.as_str() == PARENT_PLACEHOLDER {
ancestors.len().checked_sub(1)
} else {
ancestors.iter().rposition(|ancestor| &ancestor.counter == counter)
};
place.ok_or_else(|| FormatError::UnknownAncestor {
joiner: joiner.to_string(),
counter: counter.clone(),
})
}
fn parent_in(chain: &[Name]) -> Vec<Name> {
chain.last().cloned().into_iter().collect()
}
pub(super) fn joiner_text(within: &Within) -> String {
match &within.joiner {
WithinJoinerSpec::Joined(text) | WithinJoinerSpec::Template(text) => text.clone(),
WithinJoinerSpec::Named(name) => name.to_string(),
WithinJoinerSpec::Bare => String::new(),
}
}
fn described(parents: &Parents, text: &str) -> String {
format!("{} joined by {text}", parents.describe())
}
#[derive(Debug)]
struct Joined {
described: String,
joiner: Arc<NodeTree<Flm>>,
}
impl CompiledWithinJoiner for Joined {
fn counters_written(&self, chain: &[Name]) -> Vec<Name> {
parent_in(chain)
}
fn parts(&self, ancestors: &[Ancestor], cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError> {
let place = place_of(ancestors, &Name::new(PARENT_PLACEHOLDER), &self.described)?;
let ancestor = &ancestors[place];
let mut parts = cx.parts_before(ancestors, place)?;
let content = cx.joined(&[cx.number_of(ancestor)?, Arc::clone(&self.joiner)])?;
parts.push(Part::new(
vec![(ancestor.counter.clone(), ancestor.value.clone())],
content,
));
Ok(parts)
}
}
#[derive(Debug)]
struct Bare;
impl CompiledWithinJoiner for Bare {
fn counters_written(&self, _chain: &[Name]) -> Vec<Name> {
Vec::new()
}
fn parts(&self, _ancestors: &[Ancestor], _cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError> {
Ok(Vec::new())
}
}
struct Occurrence {
counter: Name,
keys: AncestorKeys,
written: String,
}
impl fmt::Debug for Occurrence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Occurrence")
.field("counter", &self.counter.as_str())
.field("keys", &self.keys)
.finish()
}
}
struct Templated {
text: String,
whole: CompiledTemplate,
occurrences: Vec<Occurrence>,
shape: Option<Vec<CompiledTemplate>>,
}
impl fmt::Debug for Templated {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Templated").field("text", &self.text).finish_non_exhaustive()
}
}
impl Templated {
fn written(
&self,
occurrence: &Occurrence,
ancestors: &[Ancestor],
cx: &JoinCx<'_>,
) -> Result<Part, FormatError> {
let place = place_of(ancestors, &occurrence.counter, &self.text)?;
written_with_keys(ancestors, place, occurrence.keys, cx)
}
}
pub(super) fn written_with_keys(
ancestors: &[Ancestor],
place: usize,
keys: AncestorKeys,
cx: &JoinCx<'_>,
) -> Result<Part, FormatError> {
let ancestor = &ancestors[place];
let mut stands_for = Vec::new();
let mut contents = Vec::new();
if !keys.bare {
for part in cx.parts_before(ancestors, place)? {
stands_for.extend(part.stands_for);
contents.push(part.content);
}
}
contents.push(match keys.format {
Some(format) => cx.number_of_in(ancestor, format)?,
None => cx.number_of(ancestor)?,
});
stands_for.push((ancestor.counter.clone(), ancestor.value.clone()));
Ok(Part::new(stands_for, cx.joined(&contents)?))
}
impl CompiledWithinJoiner for Templated {
fn counters_written(&self, chain: &[Name]) -> Vec<Name> {
let mut named: Vec<Name> = Vec::new();
for occurrence in &self.occurrences {
let written = if occurrence.counter.as_str() == PARENT_PLACEHOLDER {
parent_in(chain)
} else {
vec![occurrence.counter.clone()]
};
for counter in written {
if !named.contains(&counter) {
named.push(counter);
}
}
}
named
}
fn parts(&self, ancestors: &[Ancestor], cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError> {
let site = cx.style().site();
match &self.shape {
Some(pieces) => {
let mut parts = Vec::with_capacity(pieces.len());
for (piece, occurrence) in pieces.iter().zip(&self.occurrences) {
let written = self.written(occurrence, ancestors, cx)?;
let bindings = Bindings::new(vec![Binding {
name: occurrence.counter.as_str().to_string(),
keys: occurrence.written.clone(),
content: written.content,
}]);
parts.push(Part::new(
written.stands_for,
instantiate_template(&site, piece, &bindings)?,
));
}
Ok(parts)
}
None if self.text.is_empty() => Ok(Vec::new()),
None => {
let mut entries = Vec::with_capacity(self.occurrences.len());
let mut stands_for = Vec::new();
for occurrence in &self.occurrences {
let written = self.written(occurrence, ancestors, cx)?;
stands_for.extend(written.stands_for);
entries.push(Binding {
name: occurrence.counter.as_str().to_string(),
keys: occurrence.written.clone(),
content: written.content,
});
}
let bindings = Bindings::new(entries);
let content = instantiate_template(&site, &self.whole, &bindings)?;
Ok(vec![Part::new(stands_for, content)])
}
}
}
}