use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, OnceLock};
use techy::core::node::{BuildId, NodeRef, NodeTree};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
NodeRegion,
};
use crate::core::registry::{LateInit, LateInitError};
use crate::lang::copy::{SynthesizedPiece, ValueContent, ValuePiece, copy_pieces_into_value};
use crate::lang::guard::GuardPolicy;
use crate::lang::mint::FlmSynthesizedSpec;
use crate::lang::rewrites::userdefs::template::{
CONDITIONAL_ELEMENT, CompiledTemplate, PlaceholderTarget, PlaceholderVocabulary,
TemplateLanguage,
};
use crate::lang::{BuiltLang, Flm, FlmCallableType, FlmDiagnostics};
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::{ElementSpec, element_value};
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::lowering::{
ContentPointer, lower_content_pointer, lower_region_content,
};
use crate::stdlib::backends::pres::{self, SpanPayload};
use crate::stdlib::features::numbering::{
Binding, Bindings, COUNTERS, NumberSegment, StyleError, compile_text, instantiate_fixed,
instantiate_template,
};
use crate::stdlib::features::refs::{self, REF_RESOLUTIONS, RefTargetText};
use super::config::TheoremsConfig;
use super::diagnostics::PointerRefused;
use super::elements::{TITLE_ARG, TheoremElement, TitleReading, relation_site, title_reading};
pub const NAME_PLACEHOLDER: &str = "name";
pub const TITLE_PLACEHOLDER: &str = "title";
pub const NAME_ELEMENT: &str = "flm.theorems.name";
pub const TITLE_POINTER: &str = "flm.theorems.title-pointer";
pub const RELATION: &str = "flm.theorems.relation";
pub const NAME_ROLE: &str = "flm.theorems.name";
pub const TITLE_ROLE: &str = "flm.theorems.title";
pub const NAME_RULE: &str = "flm.theorems.name.lower.default";
pub const TITLE_POINTER_RULE: &str = "flm.theorems.title-pointer.lower.default";
pub const RELATION_RULE: &str = "flm.theorems.relation.lower.default";
const BODY_SLOT: &str = "body";
fn synthesized_element(name: &str, docs: &str) -> Arc<ElementSpec> {
Arc::new(
ElementSpec::new(name)
.docs(docs)
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
)
}
pub(super) fn synthesized_elements() -> [Arc<ElementSpec>; 3] {
[
synthesized_element(
NAME_ELEMENT,
"The kind's word and the theorem's number in a theorem's heading; synthesized, \
never written in a document.",
),
synthesized_element(
TITLE_POINTER,
"The title of a theorem, shown where its heading template places `#{title}`; \
synthesized, never written in a document.",
),
synthesized_element(
RELATION,
"The statement a proof refers to, shown where its heading template places \
`#{title}`; synthesized, never written in a document.",
),
]
}
struct Compiled {
headings: BTreeMap<Name, CompiledTemplate>,
marks: BTreeMap<Name, Arc<NodeTree<Flm>>>,
words: BTreeMap<Name, Arc<NodeTree<Flm>>>,
reference_words: BTreeMap<Name, ReferenceWords>,
}
pub(super) type ReferenceWords = Vec<(&'static str, Arc<NodeTree<Flm>>)>;
pub(super) struct Headings {
config: TheoremsConfig,
name: Arc<FlmSynthesizedSpec>,
pointer: Arc<FlmSynthesizedSpec>,
relation: Arc<FlmSynthesizedSpec>,
compiled: OnceLock<Compiled>,
}
impl fmt::Debug for Headings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Headings").field("config", &self.config).finish_non_exhaustive()
}
}
impl Headings {
pub(super) fn new(config: TheoremsConfig, elements: &[Arc<ElementSpec>; 3]) -> Headings {
let [name, pointer, relation] = elements;
Headings {
config,
name: Arc::new(FlmSynthesizedSpec::new(Arc::clone(name))),
pointer: Arc::new(FlmSynthesizedSpec::new(Arc::clone(pointer))),
relation: Arc::new(FlmSynthesizedSpec::new(Arc::clone(relation))),
compiled: OnceLock::new(),
}
}
fn compiled(&self) -> Result<&Compiled, LowerError> {
self.compiled
.get()
.ok_or_else(|| LowerError::other("the headings of the theorems feature were not compiled"))
}
pub(super) fn mark(&self, class: &Name) -> Result<Option<Arc<NodeTree<Flm>>>, LowerError> {
Ok(self.compiled()?.marks.get(class).cloned())
}
pub(super) fn word(&self, kind: &Name) -> Result<Arc<NodeTree<Flm>>, LowerError> {
self.compiled()?.words.get(kind).cloned().ok_or_else(|| {
LowerError::other(format!("the word of the theorem kind `{kind}` was not compiled"))
})
}
pub(super) fn reference_words(&self, kind: &Name) -> Result<ReferenceWords, LowerError> {
self.compiled()?.reference_words.get(kind).cloned().ok_or_else(|| {
LowerError::other(format!("the words of the theorem kind `{kind}` were not compiled"))
})
}
pub(super) fn any_mark(&self) -> bool {
self.config.classes.values().any(|class| class.closing_mark.is_some())
}
}
fn describe(error: &StyleError) -> String {
match error {
StyleError::Template { diagnostics, .. } | StyleError::Parse { diagnostics, .. } => {
diagnostics.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
}
other => other.to_string(),
}
}
fn is_conditional_test(node: &NodeRef<'_, Flm>) -> bool {
let mut current = node.parent();
while let Some(ancestor) = current {
if ancestor.callable_type().is_some() {
if ancestor.ext().element.name.as_str() != CONDITIONAL_ELEMENT {
return false;
}
return ancestor.argument_content_nodes(0).is_some_and(|test| {
test.iter().any(|top| {
top.id() == node.id() || top.descendants().any(|inner| inner.id() == node.id())
})
});
}
current = ancestor.parent();
}
false
}
fn titles_shown(template: &CompiledTemplate) -> usize {
template
.tree()
.root()
.descendants()
.filter(|node| node.callable_type() == Some(FlmCallableType::Placeholder))
.filter(|node| {
template.placeholder(node.id()).is_some_and(|reference| {
reference.target == PlaceholderTarget::Extra(TITLE_PLACEHOLDER.to_string())
})
})
.filter(|node| !is_conditional_test(node))
.count()
}
fn compile_heading(
class: &Name,
text: &str,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<CompiledTemplate, String> {
let refused = |detail: String| {
format!("the heading template `{text}` of the theorem class `{class}`: {detail}")
};
let vocabulary = PlaceholderVocabulary::new(0)
.extra(NAME_PLACEHOLDER, false)
.extra(TITLE_PLACEHOLDER, false);
let what = format!("the heading of the theorem class `{class}`");
let template = compile_text(text, &what, &vocabulary, lang, language)
.map_err(|error| refused(describe(&error)))?;
if titles_shown(&template) > 1 {
return Err(refused(format!(
"`#{{{TITLE_PLACEHOLDER}}}` may be used at most once outside a conditional's test, \
and the template uses it more than once"
)));
}
Ok(template)
}
fn compile_fixed(
what: &str,
text: &str,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<Arc<NodeTree<Flm>>, String> {
let refused = |detail: String| format!("{what} `{text}`: {detail}");
let template = compile_text(text, what, &PlaceholderVocabulary::new(0), lang, language)
.map_err(|error| refused(describe(&error)))?;
instantiate_fixed(&template).map_err(refused)
}
pub(super) struct CompileHeadings {
pub(super) headings: Arc<Headings>,
}
impl LateInit for CompileHeadings {
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 theorems feature could not be built: {}",
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
))
})?;
let config = &self.headings.config;
let mut compiled =
Compiled {
headings: BTreeMap::new(),
marks: BTreeMap::new(),
words: BTreeMap::new(),
reference_words: BTreeMap::new(),
};
for (name, class) in &config.classes {
let heading =
compile_heading(name, &class.heading, lang, &language).map_err(LateInitError::new)?;
compiled.headings.insert(name.clone(), heading);
if let Some(mark) = &class.closing_mark {
let what = format!("the closing mark of the theorem class `{name}`");
let mark = compile_fixed(&what, mark, lang, &language).map_err(LateInitError::new)?;
compiled.marks.insert(name.clone(), mark);
}
}
for (name, kind) in &config.kinds {
let what = format!("the word of the theorem kind `{name}`");
let word =
compile_fixed(&what, &kind.words.base.one, lang, &language).map_err(LateInitError::new)?;
let mut reference = ReferenceWords::new();
for (key, text) in refs::reference_type_words(&kind.words) {
reference.push((key, compile_fixed(&what, text, lang, &language).map_err(LateInitError::new)?));
}
compiled.words.insert(name.clone(), word);
compiled.reference_words.insert(name.clone(), reference);
}
let _ = self.headings.compiled.set(compiled);
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum TitleShown {
Nothing,
Title,
Relation,
}
pub(super) fn heading_instance(
headings: &Headings,
node: &NodeRef<'_, Flm>,
lw: &dyn Lowerer,
value: &TheoremElement,
number: Option<&[NumberSegment]>,
title: TitleShown,
) -> Result<Arc<NodeTree<Flm>>, LowerError> {
let compiled = headings.compiled()?;
let template = compiled.headings.get(&value.class_name).ok_or_else(|| {
LowerError::other(format!("the heading of the theorem class `{}` was not compiled", value.class_name))
})?;
let body: Vec<ValuePiece<'_, '_>> = match number {
Some(segments) => segments
.iter()
.flat_map(|segment| segment.content().root().children().iter().map(ValuePiece::Node))
.collect(),
None => {
let word = compiled.words.get(&value.name).ok_or_else(|| {
LowerError::other(format!("the word of the theorem kind `{}` was not compiled", value.name))
})?;
word.root().children().iter().map(ValuePiece::Node).collect()
}
};
let piece = |spec: &Arc<FlmSynthesizedSpec>, body, payload| SynthesizedPiece {
spec: Arc::clone(spec),
slot: BODY_SLOT,
span: node.span().clone(),
state: Arc::clone(node.parsing_state()),
body,
payload,
};
let value_of = |piece: &SynthesizedPiece<'_, '_>| {
copy_pieces_into_value(&[ValuePiece::Synthesized(piece)], node, ValueContent::Own, GuardPolicy::StackBudget)
.map_err(|error| LowerError::other(error.to_string()))
};
let name = value_of(&piece(&headings.name, body, None))?;
let mut entries =
vec![Binding { name: NAME_PLACEHOLDER.to_string(), keys: String::new(), content: name }];
let spec = match title {
TitleShown::Nothing => None,
TitleShown::Title => Some(&headings.pointer),
TitleShown::Relation => Some(&headings.relation),
};
let bindings = match spec {
Some(spec) => {
let region = NodeRegion::argument_named(node, TITLE_ARG)
.ok_or_else(|| LowerError::structure("a theorem without its title argument"))?;
let pointer: Arc<dyn crate::lang::PresPayload> =
Arc::new(ContentPointer { target: lw.addr(), region });
let content = value_of(&piece(spec, Vec::new(), Some(pointer)))?;
entries.push(Binding { name: TITLE_PLACEHOLDER.to_string(), keys: String::new(), content });
Bindings::new(entries)
}
None => Bindings::new(entries).absent(TITLE_PLACEHOLDER),
};
instantiate_template(node.span(), template, &bindings)
.map_err(|error| LowerError::other(error.to_string()))
}
fn span(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
role: &str,
body: Vec<BuildId>,
) -> Result<Vec<BuildId>, LowerError> {
if body.is_empty() {
return Ok(Vec::new());
}
let payload = SpanPayload { role: Some(Name::from(role)), ..SpanPayload::default() };
Ok(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?])
}
#[derive(Debug, Default, Clone, Copy)]
pub struct NameRule;
impl Lower for NameRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let body = lw.lower_body(cx, &node)?;
Ok(Lowering::Emit(span(cx, lw, NAME_ROLE, body)?))
}
}
fn title_check<'s>(
span: &'s crate::lang::FlmSpan,
) -> impl FnMut(&mut dyn Lowerer, &NodeRef<'_, Flm>, NodeRegion) -> Result<bool, LowerError> + 's {
move |lw: &mut dyn Lowerer, named: &NodeRef<'_, Flm>, region: NodeRegion| {
if element_value::<TheoremElement>(named).is_some()
&& NodeRegion::argument_named(named, TITLE_ARG) == Some(region)
{
return Ok(true);
}
let element = named.ext().element.name.to_string();
lw.error(PointerRefused { element, region: region.to_string() }, span.clone());
Ok(false)
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct TitlePointerRule;
impl Lower for TitlePointerRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let at = node.span().clone();
let mut check = title_check(&at);
let staged = lower_content_pointer(cx, lw, &node, &mut check, &mut lower_region_content)?;
Ok(Lowering::Emit(span(cx, lw, TITLE_ROLE, staged)?))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct RelationRule;
impl Lower for RelationRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let at = node.span().clone();
let mut check = title_check(&at);
let mut shape = |cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
proof: &NodeRef<'_, Flm>,
_content: &[NodeRef<'_, Flm>]| {
let (Some(TitleReading::Relation { text, .. }), Some(site)) =
(title_reading(proof), relation_site(proof))
else {
return Ok(Vec::new());
};
if lw.get(REF_RESOLUTIONS)?.is_none() {
return Ok(vec![lw.text(cx, &text)?]);
}
let target = RefTargetText { text, label: Some(site.target) };
let items = refs::lower_reference(cx, lw, proof, &[target], &site.display)?;
Ok(items.into_iter().flatten().collect())
};
let staged = lower_content_pointer(cx, lw, &node, &mut check, &mut shape)?;
Ok(Lowering::Emit(span(cx, lw, TITLE_ROLE, staged)?))
}
}
pub(super) fn rules() -> [LoweringRule; 3] {
[
LoweringRule::new(
NAME_RULE,
NAME_ELEMENT,
LoweringDecl::new().produces(pres::SPAN),
Arc::new(NameRule),
DefaultMark::Everywhere,
)
.docs(
"the kind's word and number in a theorem's heading lower to `flm.pres.span` of role \
`flm.theorems.name` around them",
),
LoweringRule::new(
TITLE_POINTER_RULE,
TITLE_POINTER,
LoweringDecl::new().produces(pres::SPAN),
Arc::new(TitlePointerRule),
DefaultMark::Everywhere,
)
.docs(
"a title pointer lowers to `flm.pres.span` of role `flm.theorems.title` around the \
title of the theorem it refers to, lowered where the pointer is placed",
),
LoweringRule::new(
RELATION_RULE,
RELATION,
LoweringDecl::new()
.reads_opt(REF_RESOLUTIONS)
.reads_opt(COUNTERS)
.produces(pres::SPAN)
.produces(pres::LINK),
Arc::new(RelationRule),
DefaultMark::Everywhere,
)
.docs(
"a back-reference in a proof's heading lowers to `flm.pres.span` of role \
`flm.theorems.title` around what a reference to the proved statement writes",
),
]
}