use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use techy::core::node::NodeTree;
use crate::core::registry::{LateInit, LateInitError};
use crate::lang::rewrites::userdefs::template::{CompiledTemplate, TemplateLanguage};
use crate::lang::guard::{on_worker_thread, GuardPolicy};
use crate::lang::{BuiltLang, Flm, FlmDiagnostics, LangOwned};
use crate::model::names::Name;
use crate::stdlib::features::numbering::{
compile_text, instantiate_fixed, number_vocabulary, occurrences_of, StyleError,
};
use super::config::ListsConfig;
pub(super) struct CompiledLabel {
template: CompiledTemplate,
names_number: bool,
fixed: Result<Option<Arc<NodeTree<Flm>>>, String>,
}
impl CompiledLabel {
pub(super) fn compile(
text: &str,
what: &str,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<CompiledLabel, StyleError> {
let template = compile_text(text, what, &number_vocabulary(), lang, language)?;
let names_number = !occurrences_of(&template).is_empty();
let fixed = if names_number { Ok(None) } else { instantiate_fixed(&template).map(Some) };
Ok(CompiledLabel { template, names_number, fixed })
}
pub(super) fn names_number(&self) -> bool {
self.names_number
}
pub(super) fn template(&self) -> &CompiledTemplate {
&self.template
}
pub(super) fn fixed(&self) -> Result<Option<Arc<NodeTree<Flm>>>, String> {
self.fixed.clone()
}
}
struct Compiled {
language: Arc<TemplateLanguage>,
kinds: BTreeMap<Name, Vec<Arc<CompiledLabel>>>,
guard: GuardPolicy,
}
fn at_depth(templates: &[Arc<CompiledLabel>], depth: usize) -> Option<&Arc<CompiledLabel>> {
let index = depth.saturating_sub(1).min(templates.len().checked_sub(1)?);
templates.get(index)
}
pub(crate) fn holds_placeholder(text: &str) -> bool {
let mut chars = text.chars();
while let Some(ch) = chars.next() {
match ch {
'\\' => {
chars.next();
}
'#' if chars.next() != Some('#') => return true,
_ => {}
}
}
false
}
pub(super) struct Labels {
config: ListsConfig,
compiled: LangOwned<Compiled>,
}
impl fmt::Debug for Labels {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Labels").field("config", &self.config).finish_non_exhaustive()
}
}
impl Labels {
pub(super) fn new(config: ListsConfig) -> Labels {
Labels { config, compiled: LangOwned::new() }
}
pub(super) fn of_kind(&self, kind: &Name, depth: usize) -> Option<Arc<CompiledLabel>> {
at_depth(self.compiled.get()?.kinds.get(kind)?, depth).cloned()
}
pub(super) fn language(&self) -> Option<Arc<TemplateLanguage>> {
self.compiled.get().map(|compiled| Arc::clone(&compiled.language))
}
pub(super) fn guard(&self) -> GuardPolicy {
self.compiled.get().map(|compiled| compiled.guard).unwrap_or_default()
}
pub(super) fn compile(
&self,
text: &str,
what: &str,
lang: &BuiltLang,
) -> Result<CompiledLabel, String> {
let language =
self.language().ok_or_else(|| String::from("the list label templates were not compiled"))?;
CompiledLabel::compile(text, what, lang, &language).map_err(|error| match error {
StyleError::Template { diagnostics, .. } => diagnostics
.iter()
.map(|diagnostic| diagnostic.message())
.collect::<Vec<_>>()
.join("; "),
other => other.to_string(),
})
}
}
pub(super) struct CompileLabels {
pub(super) labels: Arc<Labels>,
}
impl CompileLabels {
fn compile_kinds(
&self,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<BTreeMap<Name, Vec<Arc<CompiledLabel>>>, LateInitError> {
let mut kinds = BTreeMap::new();
for (name, kind) in &self.labels.config.environments {
let compile_all = |texts: &[String], which: &str| {
let mut compiled = Vec::with_capacity(texts.len());
for (index, text) in texts.iter().enumerate() {
let what = format!(
"the {which} template of the list environment `{name}` at depth {}",
index + 1
);
let label = CompiledLabel::compile(text, &what, lang, language)
.map_err(|error| LateInitError::new(format!("{what}: {error}")))?;
if label.names_number() && !kind.numbered {
return Err(LateInitError::new(format!(
"the {which} template `{text}` of the list environment `{name}` at \
depth {} must not write a number, since the environment is not \
numbered",
index + 1
)));
}
compiled.push(Arc::new(label));
}
Ok(compiled)
};
let labels = compile_all(&kind.labels, "label")?;
if kind.numbered {
compile_all(&kind.ref_labels, "reference")?;
}
kinds.insert(name.clone(), labels);
}
Ok(kinds)
}
}
impl LateInit for CompileLabels {
fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
let language = TemplateLanguage::new(lang).map_err(|errors| {
LateInitError::new(format!(
"the template language of the lists feature could not be built: {}",
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
))
})?;
let kinds = on_worker_thread(|| self.compile_kinds(lang, &language))
.map_err(|error| LateInitError::new(format!(
"compiling the list label templates needs a thread with a large stack, and \
the operating system refused to create one: {error}"
)))??;
let compiled = Compiled { language: Arc::new(language), kinds, guard: lang.guard() };
let _ = self.labels.compiled.set(lang, compiled);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::holds_placeholder;
#[test]
fn a_placeholder_is_a_hash_neither_doubled_nor_escaped() {
for text in ["#{arabic}", "(#{nosuch})", "#1", "a#", "## #{alph}"] {
assert!(holds_placeholder(text), "{text}");
}
for text in ["", "\u{2022}", "--", "##", "\\#", "(\\#)##"] {
assert!(!holds_placeholder(text), "{text}");
}
}
}