use std::sync::Arc;
use techy::core::node::{NodeSlice, NodeTree};
use techy::latexlike::Mode;
use crate::lang::flm::FlmCallableType;
use crate::lang::guard::{on_worker_thread, GuardPolicy};
use crate::lang::rewrites::userdefs::hook::{PlaceholderBindings, PlaceholderValue};
use crate::lang::rewrites::userdefs::instantiate::instantiate;
use crate::lang::rewrites::userdefs::template::{
compile_template_with, CompiledTemplate, PlaceholderTarget, PlaceholderVocabulary,
TemplateLanguage, TemplateSpec,
};
use crate::lang::text::is_space;
use crate::lang::{BuiltLang, Flm, FlmSpan};
use crate::model::names::Name;
use super::decl::PARENT_PLACEHOLDER;
use super::formats::NumberFormat;
use super::style::{FormatError, StyleError};
pub(crate) fn number_vocabulary() -> PlaceholderVocabulary {
let mut vocabulary = PlaceholderVocabulary::new(0);
for format in NumberFormat::ALL {
vocabulary = vocabulary.extra(format.written_name(), false);
}
vocabulary
}
pub(super) fn within_vocabulary<'a>(
counters: impl Iterator<Item = &'a Name>,
) -> PlaceholderVocabulary {
let mut vocabulary = PlaceholderVocabulary::new(0).extra(PARENT_PLACEHOLDER, true);
for counter in counters {
vocabulary = vocabulary.extra(counter.as_str(), true);
}
vocabulary
}
pub(crate) fn compile_text(
text: &str,
what: &str,
vocabulary: &PlaceholderVocabulary,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<CompiledTemplate, StyleError> {
let label = format!("template of {what}");
let spec = TemplateSpec {
text,
mode: Mode::Text,
vocabulary,
offset: 0,
definition: what,
label: &label,
origin_label: &label,
user_definition: false,
};
compile_template_with(&spec, lang, language).map_err(|diagnostics| StyleError::Template {
text: text.to_string(),
diagnostics,
})
}
pub(crate) fn instantiate_template(
site: &FlmSpan,
template: &CompiledTemplate,
bindings: &dyn PlaceholderBindings,
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
instantiate(site, template, bindings, GuardPolicy::StackBudget).map(Arc::new).map_err(
|error| match error.descent_refusal() {
Some(detail) => FormatError::NestingTooDeep { detail: detail.to_string() },
None => FormatError::Failed { detail: error.to_string() },
},
)
}
pub(crate) fn instantiate_fixed(template: &CompiledTemplate) -> Result<Arc<NodeTree<Flm>>, String> {
let site = template.tree().root().span().clone();
on_worker_thread(|| {
instantiate_template(&site, template, &Bindings::new(Vec::new())).map_err(|error| error.to_string())
})
.map_err(|error| format!(
"instantiating a template needs a thread with a large stack, and the operating \
system refused to create one: {error}"
))?
}
pub(crate) fn occurrences_of(template: &CompiledTemplate) -> Vec<(String, String)> {
let mut found = Vec::new();
for node in template.tree().root().descendants() {
if node.callable_type() != Some(FlmCallableType::Placeholder) {
continue;
}
let Some(reference) = template.placeholder(node.id()) else { continue };
let PlaceholderTarget::Extra(name) = &reference.target else { continue };
let keys = node.argument_content_nodes(0).map(slice_text).unwrap_or_default();
found.push((name.clone(), keys));
}
found
}
pub(super) fn placeholder_starts(template: &CompiledTemplate) -> Vec<usize> {
let mut starts = Vec::new();
for node in template.tree().root().descendants() {
if node.callable_type() != Some(FlmCallableType::Placeholder) {
continue;
}
if template.placeholder(node.id()).is_none() {
continue;
}
starts.push(node.span().start());
}
starts.sort_unstable();
starts
}
pub(super) fn slice_text(nodes: NodeSlice<'_, Flm>) -> String {
let mut text = String::new();
for node in nodes.iter() {
match node.chars() {
Some(chars) => text.push_str(chars),
None => return String::new(),
}
}
text.trim_matches(is_space).to_string()
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(crate) struct AncestorKeys {
pub(crate) format: Option<NumberFormat>,
pub(crate) bare: bool,
}
const BARE_KEY: &str = "bare";
pub(crate) fn parse_keys(text: &str) -> Result<AncestorKeys, String> {
let mut keys = AncestorKeys::default();
for key in text.split(',') {
let key = key.trim_matches(is_space);
if key.is_empty() {
continue;
}
if key == BARE_KEY {
keys.bare = true;
continue;
}
match NumberFormat::from_written_name(key) {
Some(format) => keys.format = Some(format),
None => return Err(key.to_string()),
}
}
Ok(keys)
}
pub(crate) struct Binding {
pub(crate) name: String,
pub(crate) keys: String,
pub(crate) content: Arc<NodeTree<Flm>>,
}
pub(crate) struct Bindings {
entries: Vec<Binding>,
absent: Vec<String>,
}
impl Bindings {
pub(crate) fn new(entries: Vec<Binding>) -> Bindings {
Bindings { entries, absent: Vec::new() }
}
pub(crate) fn absent(mut self, name: impl Into<String>) -> Bindings {
self.absent.push(name.into());
self
}
}
impl PlaceholderBindings for Bindings {
fn value<'a>(
&'a self,
target: &PlaceholderTarget,
substitution: Option<NodeSlice<'_, Flm>>,
) -> PlaceholderValue<'a> {
let PlaceholderTarget::Extra(name) = target else {
return PlaceholderValue::Unresolvable;
};
let keys = substitution.map(slice_text).unwrap_or_default();
match self
.entries
.iter()
.find(|entry| entry.name == *name && entry.keys == keys)
{
Some(entry) => PlaceholderValue::Tree(&entry.content),
None if self.absent.iter().any(|absent| absent == name) => PlaceholderValue::NoValue,
None => PlaceholderValue::Unresolvable,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_keys_are_a_format_and_the_bare_mark() {
assert_eq!(parse_keys(""), Ok(AncestorKeys::default()));
assert_eq!(
parse_keys("Roman"),
Ok(AncestorKeys { format: Some(NumberFormat::CapitalRoman), bare: false })
);
assert_eq!(parse_keys("bare"), Ok(AncestorKeys { format: None, bare: true }));
assert_eq!(
parse_keys(" Roman , bare "),
Ok(AncestorKeys { format: Some(NumberFormat::CapitalRoman), bare: true })
);
}
#[test]
fn a_key_that_is_neither_is_refused() {
assert_eq!(parse_keys("nosuchkey"), Err("nosuchkey".to_string()));
assert_eq!(parse_keys("Roman,nosuchkey"), Err("nosuchkey".to_string()));
}
}