1use std::collections::BTreeMap;
59use std::fmt;
60use std::sync::{Arc, OnceLock};
61
62use techy::core::node::{BuildId, NodeRef, NodeTree};
63
64use crate::core::lowering::{
65 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
66 NodeRegion,
67};
68use crate::core::registry::{LateInit, LateInitError};
69use crate::lang::copy::{SynthesizedPiece, ValueContent, ValuePiece, copy_pieces_into_value};
70use crate::lang::guard::GuardPolicy;
71use crate::lang::mint::FlmSynthesizedSpec;
72use crate::lang::rewrites::userdefs::template::{
73 CONDITIONAL_ELEMENT, CompiledTemplate, PlaceholderTarget, PlaceholderVocabulary,
74 TemplateLanguage,
75};
76use crate::lang::{BuiltLang, Flm, FlmCallableType, FlmDiagnostics};
77use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
78use crate::model::element::{ElementSpec, element_value};
79use crate::model::names::{ElementName, Name};
80use crate::stdlib::backends::lowering::{
81 ContentPointer, lower_content_pointer, lower_region_content,
82};
83use crate::stdlib::backends::pres::{self, SpanPayload};
84use crate::stdlib::features::numbering::{
85 Binding, Bindings, COUNTERS, NumberSegment, StyleError, compile_text, instantiate_fixed,
86 instantiate_template,
87};
88use crate::stdlib::features::refs::{self, REF_RESOLUTIONS, RefTargetText};
89
90use super::config::TheoremsConfig;
91use super::diagnostics::PointerRefused;
92use super::elements::{TITLE_ARG, TheoremElement, TitleReading, relation_site, title_reading};
93
94pub const NAME_PLACEHOLDER: &str = "name";
97
98pub const TITLE_PLACEHOLDER: &str = "title";
101
102pub const NAME_ELEMENT: &str = "flm.theorems.name";
109
110pub const TITLE_POINTER: &str = "flm.theorems.title-pointer";
114
115pub const RELATION: &str = "flm.theorems.relation";
120
121pub const NAME_ROLE: &str = "flm.theorems.name";
124
125pub const TITLE_ROLE: &str = "flm.theorems.title";
129
130pub const NAME_RULE: &str = "flm.theorems.name.lower.default";
133
134pub const TITLE_POINTER_RULE: &str = "flm.theorems.title-pointer.lower.default";
137
138pub const RELATION_RULE: &str = "flm.theorems.relation.lower.default";
141
142const BODY_SLOT: &str = "body";
144
145fn synthesized_element(name: &str, docs: &str) -> Arc<ElementSpec> {
147 Arc::new(
148 ElementSpec::new(name)
149 .docs(docs)
150 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
151 )
152}
153
154pub(super) fn synthesized_elements() -> [Arc<ElementSpec>; 3] {
157 [
158 synthesized_element(
159 NAME_ELEMENT,
160 "The kind's word and the theorem's number in a theorem's heading; synthesized, \
161 never written in a document.",
162 ),
163 synthesized_element(
164 TITLE_POINTER,
165 "The title of a theorem, shown where its heading template places `#{title}`; \
166 synthesized, never written in a document.",
167 ),
168 synthesized_element(
169 RELATION,
170 "The statement a proof refers to, shown where its heading template places \
171 `#{title}`; synthesized, never written in a document.",
172 ),
173 ]
174}
175
176struct Compiled {
180 headings: BTreeMap<Name, CompiledTemplate>,
182 marks: BTreeMap<Name, Arc<NodeTree<Flm>>>,
184 words: BTreeMap<Name, Arc<NodeTree<Flm>>>,
186 reference_words: BTreeMap<Name, ReferenceWords>,
189}
190
191pub(super) type ReferenceWords = Vec<(&'static str, Arc<NodeTree<Flm>>)>;
196
197pub(super) struct Headings {
201 config: TheoremsConfig,
202 name: Arc<FlmSynthesizedSpec>,
203 pointer: Arc<FlmSynthesizedSpec>,
204 relation: Arc<FlmSynthesizedSpec>,
205 compiled: OnceLock<Compiled>,
206}
207
208impl fmt::Debug for Headings {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.debug_struct("Headings").field("config", &self.config).finish_non_exhaustive()
211 }
212}
213
214impl Headings {
215 pub(super) fn new(config: TheoremsConfig, elements: &[Arc<ElementSpec>; 3]) -> Headings {
218 let [name, pointer, relation] = elements;
219 Headings {
220 config,
221 name: Arc::new(FlmSynthesizedSpec::new(Arc::clone(name))),
222 pointer: Arc::new(FlmSynthesizedSpec::new(Arc::clone(pointer))),
223 relation: Arc::new(FlmSynthesizedSpec::new(Arc::clone(relation))),
224 compiled: OnceLock::new(),
225 }
226 }
227
228 fn compiled(&self) -> Result<&Compiled, LowerError> {
230 self.compiled
231 .get()
232 .ok_or_else(|| LowerError::other("the headings of the theorems feature were not compiled"))
233 }
234
235 pub(super) fn mark(&self, class: &Name) -> Result<Option<Arc<NodeTree<Flm>>>, LowerError> {
237 Ok(self.compiled()?.marks.get(class).cloned())
238 }
239
240 pub(super) fn word(&self, kind: &Name) -> Result<Arc<NodeTree<Flm>>, LowerError> {
245 self.compiled()?.words.get(kind).cloned().ok_or_else(|| {
246 LowerError::other(format!("the word of the theorem kind `{kind}` was not compiled"))
247 })
248 }
249
250 pub(super) fn reference_words(&self, kind: &Name) -> Result<ReferenceWords, LowerError> {
252 self.compiled()?.reference_words.get(kind).cloned().ok_or_else(|| {
253 LowerError::other(format!("the words of the theorem kind `{kind}` were not compiled"))
254 })
255 }
256
257 pub(super) fn any_mark(&self) -> bool {
259 self.config.classes.values().any(|class| class.closing_mark.is_some())
260 }
261}
262
263fn describe(error: &StyleError) -> String {
266 match error {
267 StyleError::Template { diagnostics, .. } | StyleError::Parse { diagnostics, .. } => {
268 diagnostics.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
269 }
270 other => other.to_string(),
271 }
272}
273
274fn is_conditional_test(node: &NodeRef<'_, Flm>) -> bool {
278 let mut current = node.parent();
279 while let Some(ancestor) = current {
280 if ancestor.callable_type().is_some() {
281 if ancestor.ext().element.name.as_str() != CONDITIONAL_ELEMENT {
282 return false;
283 }
284 return ancestor.argument_content_nodes(0).is_some_and(|test| {
285 test.iter().any(|top| {
286 top.id() == node.id() || top.descendants().any(|inner| inner.id() == node.id())
287 })
288 });
289 }
290 current = ancestor.parent();
291 }
292 false
293}
294
295fn titles_shown(template: &CompiledTemplate) -> usize {
298 template
299 .tree()
300 .root()
301 .descendants()
302 .filter(|node| node.callable_type() == Some(FlmCallableType::Placeholder))
303 .filter(|node| {
304 template.placeholder(node.id()).is_some_and(|reference| {
305 reference.target == PlaceholderTarget::Extra(TITLE_PLACEHOLDER.to_string())
306 })
307 })
308 .filter(|node| !is_conditional_test(node))
309 .count()
310}
311
312fn compile_heading(
319 class: &Name,
320 text: &str,
321 lang: &BuiltLang,
322 language: &TemplateLanguage,
323) -> Result<CompiledTemplate, String> {
324 let refused = |detail: String| {
325 format!("the heading template `{text}` of the theorem class `{class}`: {detail}")
326 };
327 let vocabulary = PlaceholderVocabulary::new(0)
328 .extra(NAME_PLACEHOLDER, false)
329 .extra(TITLE_PLACEHOLDER, false);
330 let what = format!("the heading of the theorem class `{class}`");
331 let template = compile_text(text, &what, &vocabulary, lang, language)
332 .map_err(|error| refused(describe(&error)))?;
333 if titles_shown(&template) > 1 {
334 return Err(refused(format!(
335 "`#{{{TITLE_PLACEHOLDER}}}` may be used at most once outside a conditional's test, \
336 and the template uses it more than once"
337 )));
338 }
339 Ok(template)
340}
341
342fn compile_fixed(
349 what: &str,
350 text: &str,
351 lang: &BuiltLang,
352 language: &TemplateLanguage,
353) -> Result<Arc<NodeTree<Flm>>, String> {
354 let refused = |detail: String| format!("{what} `{text}`: {detail}");
355 let template = compile_text(text, what, &PlaceholderVocabulary::new(0), lang, language)
356 .map_err(|error| refused(describe(&error)))?;
357 instantiate_fixed(&template).map_err(refused)
358}
359
360pub(super) struct CompileHeadings {
366 pub(super) headings: Arc<Headings>,
367}
368
369impl LateInit for CompileHeadings {
370 fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
371 let language = TemplateLanguage::new(lang).map_err(|errors| {
372 LateInitError::new(format!(
373 "the template language of the theorems feature could not be built: {}",
374 errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
375 ))
376 })?;
377 let config = &self.headings.config;
378 let mut compiled =
379 Compiled {
380 headings: BTreeMap::new(),
381 marks: BTreeMap::new(),
382 words: BTreeMap::new(),
383 reference_words: BTreeMap::new(),
384 };
385 for (name, class) in &config.classes {
386 let heading =
387 compile_heading(name, &class.heading, lang, &language).map_err(LateInitError::new)?;
388 compiled.headings.insert(name.clone(), heading);
389 if let Some(mark) = &class.closing_mark {
390 let what = format!("the closing mark of the theorem class `{name}`");
391 let mark = compile_fixed(&what, mark, lang, &language).map_err(LateInitError::new)?;
392 compiled.marks.insert(name.clone(), mark);
393 }
394 }
395 for (name, kind) in &config.kinds {
396 let what = format!("the word of the theorem kind `{name}`");
397 let word =
398 compile_fixed(&what, &kind.words.base.one, lang, &language).map_err(LateInitError::new)?;
399 let mut reference = ReferenceWords::new();
400 for (key, text) in refs::reference_type_words(&kind.words) {
401 reference.push((key, compile_fixed(&what, text, lang, &language).map_err(LateInitError::new)?));
402 }
403 compiled.words.insert(name.clone(), word);
404 compiled.reference_words.insert(name.clone(), reference);
405 }
406 let _ = self.headings.compiled.set(compiled);
409 Ok(())
410 }
411}
412
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
417pub(super) enum TitleShown {
418 Nothing,
420 Title,
422 Relation,
424}
425
426pub(super) fn heading_instance(
439 headings: &Headings,
440 node: &NodeRef<'_, Flm>,
441 lw: &dyn Lowerer,
442 value: &TheoremElement,
443 number: Option<&[NumberSegment]>,
444 title: TitleShown,
445) -> Result<Arc<NodeTree<Flm>>, LowerError> {
446 let compiled = headings.compiled()?;
447 let template = compiled.headings.get(&value.class_name).ok_or_else(|| {
448 LowerError::other(format!("the heading of the theorem class `{}` was not compiled", value.class_name))
449 })?;
450 let body: Vec<ValuePiece<'_, '_>> = match number {
451 Some(segments) => segments
452 .iter()
453 .flat_map(|segment| segment.content().root().children().iter().map(ValuePiece::Node))
454 .collect(),
455 None => {
456 let word = compiled.words.get(&value.name).ok_or_else(|| {
457 LowerError::other(format!("the word of the theorem kind `{}` was not compiled", value.name))
458 })?;
459 word.root().children().iter().map(ValuePiece::Node).collect()
460 }
461 };
462 let piece = |spec: &Arc<FlmSynthesizedSpec>, body, payload| SynthesizedPiece {
463 spec: Arc::clone(spec),
464 slot: BODY_SLOT,
465 span: node.span().clone(),
466 state: Arc::clone(node.parsing_state()),
467 body,
468 payload,
469 };
470 let value_of = |piece: &SynthesizedPiece<'_, '_>| {
471 copy_pieces_into_value(&[ValuePiece::Synthesized(piece)], node, ValueContent::Own, GuardPolicy::StackBudget)
472 .map_err(|error| LowerError::other(error.to_string()))
473 };
474 let name = value_of(&piece(&headings.name, body, None))?;
475 let mut entries =
476 vec![Binding { name: NAME_PLACEHOLDER.to_string(), keys: String::new(), content: name }];
477 let spec = match title {
478 TitleShown::Nothing => None,
479 TitleShown::Title => Some(&headings.pointer),
480 TitleShown::Relation => Some(&headings.relation),
481 };
482 let bindings = match spec {
485 Some(spec) => {
486 let region = NodeRegion::argument_named(node, TITLE_ARG)
487 .ok_or_else(|| LowerError::structure("a theorem without its title argument"))?;
488 let pointer: Arc<dyn crate::lang::PresPayload> =
489 Arc::new(ContentPointer { target: lw.addr(), region });
490 let content = value_of(&piece(spec, Vec::new(), Some(pointer)))?;
491 entries.push(Binding { name: TITLE_PLACEHOLDER.to_string(), keys: String::new(), content });
492 Bindings::new(entries)
493 }
494 None => Bindings::new(entries).absent(TITLE_PLACEHOLDER),
495 };
496 instantiate_template(node.span(), template, &bindings)
497 .map_err(|error| LowerError::other(error.to_string()))
498}
499
500fn span(
504 cx: &mut LowerCx<'_>,
505 lw: &mut dyn Lowerer,
506 role: &str,
507 body: Vec<BuildId>,
508) -> Result<Vec<BuildId>, LowerError> {
509 if body.is_empty() {
510 return Ok(Vec::new());
511 }
512 let payload = SpanPayload { role: Some(Name::from(role)), ..SpanPayload::default() };
513 Ok(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?])
514}
515
516#[derive(Debug, Default, Clone, Copy)]
521pub struct NameRule;
522
523impl Lower for NameRule {
524 fn lower(
525 &self,
526 node: NodeRef<'_, Flm>,
527 cx: &mut LowerCx<'_>,
528 lw: &mut dyn Lowerer,
529 ) -> Result<Lowering, LowerError> {
530 let body = lw.lower_body(cx, &node)?;
531 Ok(Lowering::Emit(span(cx, lw, NAME_ROLE, body)?))
532 }
533}
534
535fn title_check<'s>(
539 span: &'s crate::lang::FlmSpan,
540) -> impl FnMut(&mut dyn Lowerer, &NodeRef<'_, Flm>, NodeRegion) -> Result<bool, LowerError> + 's {
541 move |lw: &mut dyn Lowerer, named: &NodeRef<'_, Flm>, region: NodeRegion| {
542 if element_value::<TheoremElement>(named).is_some()
543 && NodeRegion::argument_named(named, TITLE_ARG) == Some(region)
544 {
545 return Ok(true);
546 }
547 let element = named.ext().element.name.to_string();
548 lw.error(PointerRefused { element, region: region.to_string() }, span.clone());
549 Ok(false)
550 }
551}
552
553#[derive(Debug, Default, Clone, Copy)]
563pub struct TitlePointerRule;
564
565impl Lower for TitlePointerRule {
566 fn lower(
567 &self,
568 node: NodeRef<'_, Flm>,
569 cx: &mut LowerCx<'_>,
570 lw: &mut dyn Lowerer,
571 ) -> Result<Lowering, LowerError> {
572 let at = node.span().clone();
573 let mut check = title_check(&at);
574 let staged = lower_content_pointer(cx, lw, &node, &mut check, &mut lower_region_content)?;
575 Ok(Lowering::Emit(span(cx, lw, TITLE_ROLE, staged)?))
576 }
577}
578
579#[derive(Debug, Default, Clone, Copy)]
593pub struct RelationRule;
594
595impl Lower for RelationRule {
596 fn lower(
597 &self,
598 node: NodeRef<'_, Flm>,
599 cx: &mut LowerCx<'_>,
600 lw: &mut dyn Lowerer,
601 ) -> Result<Lowering, LowerError> {
602 let at = node.span().clone();
603 let mut check = title_check(&at);
604 let mut shape = |cx: &mut LowerCx<'_>,
607 lw: &mut dyn Lowerer,
608 proof: &NodeRef<'_, Flm>,
609 _content: &[NodeRef<'_, Flm>]| {
610 let (Some(TitleReading::Relation { text, .. }), Some(site)) =
613 (title_reading(proof), relation_site(proof))
614 else {
615 return Ok(Vec::new());
616 };
617 if lw.get(REF_RESOLUTIONS)?.is_none() {
618 return Ok(vec![lw.text(cx, &text)?]);
619 }
620 let target = RefTargetText { text, label: Some(site.target) };
621 let items = refs::lower_reference(cx, lw, proof, &[target], &site.display)?;
622 Ok(items.into_iter().flatten().collect())
623 };
624 let staged = lower_content_pointer(cx, lw, &node, &mut check, &mut shape)?;
625 Ok(Lowering::Emit(span(cx, lw, TITLE_ROLE, staged)?))
626 }
627}
628
629pub(super) fn rules() -> [LoweringRule; 3] {
632 [
633 LoweringRule::new(
634 NAME_RULE,
635 NAME_ELEMENT,
636 LoweringDecl::new().produces(pres::SPAN),
637 Arc::new(NameRule),
638 DefaultMark::Everywhere,
639 )
640 .docs(
641 "the kind's word and number in a theorem's heading lower to `flm.pres.span` of role \
642 `flm.theorems.name` around them",
643 ),
644 LoweringRule::new(
645 TITLE_POINTER_RULE,
646 TITLE_POINTER,
647 LoweringDecl::new().produces(pres::SPAN),
648 Arc::new(TitlePointerRule),
649 DefaultMark::Everywhere,
650 )
651 .docs(
652 "a title pointer lowers to `flm.pres.span` of role `flm.theorems.title` around the \
653 title of the theorem it refers to, lowered where the pointer is placed",
654 ),
655 LoweringRule::new(
656 RELATION_RULE,
657 RELATION,
658 LoweringDecl::new()
659 .reads_opt(REF_RESOLUTIONS)
660 .reads_opt(COUNTERS)
661 .produces(pres::SPAN)
662 .produces(pres::LINK),
663 Arc::new(RelationRule),
664 DefaultMark::Everywhere,
665 )
666 .docs(
667 "a back-reference in a proof's heading lowers to `flm.pres.span` of role \
668 `flm.theorems.title` around what a reference to the proved statement writes",
669 ),
670 ]
671}