Skip to main content

flm_core/stdlib/features/theorems/
heading.rs

1//! The heading and the closing mark of a theorem: the compilation of every
2//! class's heading template, every class's closing mark and every kind's word
3//! when the registry is built; the instantiation of a heading at a theorem;
4//! and the three synthesized elements that an instantiated heading holds,
5//! with their general lowering rules.
6//!
7//! # What is compiled
8//!
9//! A build hook ([`LateInit`]) compiles, once the language is built:
10//!
11//! - every class's [theorem heading
12//!   template](super::TheoremClass::heading), with the two placeholders
13//!   `#{name}` and `#{title}`;
14//! - every class's [closing mark](super::TheoremClass::closing_mark), as FLM
15//!   markup;
16//! - every kind's base singular word, as FLM markup: the word a heading shows
17//!   alone where the theorem has no number;
18//! - every kind's words as a reference to it shows them, for the recomposed
19//!   LaTeX ([`latex`](super::latex)).
20//!
21//! The registry build fails, with a message that identifies the class or the
22//! kind, on a template that does not compile, uses a placeholder other than
23//! these two, writes a placeholder with keys in brackets (`#[…]{title}`), or
24//! uses `#{title}` more than once; and on a mark or a word that does not
25//! parse. `#{title}` written as the test of a conditional
26//! (`\IfValueT{#{title}}{…}`) shows nothing and is not counted.
27//!
28//! # The heading at a theorem
29//!
30//! The theorem's general rule ([`rules`](super::rules)) instantiates the
31//! class's template at each theorem. Each `#{name}` is replaced by one node of
32//! the element [`NAME_ELEMENT`], which holds the kind's word and the theorem's
33//! number (`Lemma~4`, the number as the numbering feature writes it in the
34//! kind's counter style), or the word alone where the document did not number
35//! the theorem; its rule writes a span of role [`NAME_ROLE`] around it.
36//! `#{title}` is replaced by one of two nodes:
37//!
38//! - for a title, a node of the element [`TITLE_POINTER`], whose payload is a
39//!   [`ContentPointer`] to the theorem's title argument. Its rule
40//!   lowers the title where the heading shows it, through
41//!   [`lower_content_pointer`], so the title is shown as the document's own
42//!   content and never copied;
43//! - for a back-reference that a proof shows, a node of the element
44//!   [`RELATION`], whose payload is a content pointer to the same title
45//!   argument. Its rule writes what a reference to the statement writes (the
46//!   statement's word and number, linked to it) through the references
47//!   feature's
48//!   [`lower_reference`](crate::stdlib::features::refs::lower_reference),
49//!   from the resolution of the theorem's reference site.
50//!
51//! Either rule writes a span of role [`TITLE_ROLE`] around what it lowers. A
52//! theorem with no title, or whose back-reference is not shown, binds nothing
53//! to `#{title}`. The three elements are synthesized: no source text
54//! produces them, so an author cannot write them. The roles are names that a
55//! stylesheet or a host's lowering rule selects on (see
56//! [roles](crate::stdlib::backends::pres::payload)).
57
58use 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
94/// The placeholder of a theorem heading template for the kind's word and
95/// the theorem's number, `name`, written `#{name}`.
96pub const NAME_PLACEHOLDER: &str = "name";
97
98/// The placeholder of a theorem heading template for the theorem's title, or
99/// the statement a proof refers to, `title`, written `#{title}`.
100pub const TITLE_PLACEHOLDER: &str = "title";
101
102/// The element of the node that replaces `#{name}` in an instantiated
103/// heading, `flm.theorems.name`: synthesized, its body the kind's word and
104/// the theorem's number. It is an element, rather than content inserted into
105/// the heading, so that its rule can stage (build into the lowered tree; see
106/// [`Lowerer`]) the span of role [`NAME_ROLE`] around the name: a
107/// presentation span can only be built at lowering.
108pub const NAME_ELEMENT: &str = "flm.theorems.name";
109
110/// The element of the node that replaces `#{title}` where the theorem has a
111/// title, `flm.theorems.title-pointer`: synthesized, its payload a
112/// [`ContentPointer`] to the theorem's title argument ([`TitlePointerRule`]).
113pub const TITLE_POINTER: &str = "flm.theorems.title-pointer";
114
115/// The element of the node that replaces `#{title}` where a proof shows its
116/// back-reference, `flm.theorems.relation`: synthesized, its payload a
117/// [`ContentPointer`] to the proof's title argument, in which the
118/// back-reference is written ([`RelationRule`]).
119pub const RELATION: &str = "flm.theorems.relation";
120
121/// The role of the span around the kind's word and the theorem's number in a
122/// heading, `flm.theorems.name` (written by [`NameRule`]).
123pub const NAME_ROLE: &str = "flm.theorems.name";
124
125/// The role of the span around the title, or the back-reference, in a
126/// heading, `flm.theorems.title` (written by [`TitlePointerRule`] and
127/// [`RelationRule`]).
128pub const TITLE_ROLE: &str = "flm.theorems.title";
129
130/// The name of the general lowering rule of [`NAME_ELEMENT`],
131/// `flm.theorems.name.lower.default` ([`NameRule`]).
132pub const NAME_RULE: &str = "flm.theorems.name.lower.default";
133
134/// The name of the general lowering rule of [`TITLE_POINTER`],
135/// `flm.theorems.title-pointer.lower.default` ([`TitlePointerRule`]).
136pub const TITLE_POINTER_RULE: &str = "flm.theorems.title-pointer.lower.default";
137
138/// The name of the general lowering rule of [`RELATION`],
139/// `flm.theorems.relation.lower.default` ([`RelationRule`]).
140pub const RELATION_RULE: &str = "flm.theorems.relation.lower.default";
141
142/// The name of the body slot of a synthesized node.
143const BODY_SLOT: &str = "body";
144
145/// A synthesized, inline element named `name`.
146fn 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
154/// The elements of the three synthesized nodes, in the order [`NAME_ELEMENT`],
155/// [`TITLE_POINTER`], [`RELATION`].
156pub(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
176// --- what is compiled ------------------------------------------------------------------------
177
178/// What the late-initialization hook compiles.
179struct Compiled {
180    /// Each class's heading template, by class name.
181    headings: BTreeMap<Name, CompiledTemplate>,
182    /// Each class's closing mark, by class name, where it has one.
183    marks: BTreeMap<Name, Arc<NodeTree<Flm>>>,
184    /// Each kind's base singular word, by kind name.
185    words: BTreeMap<Name, Arc<NodeTree<Flm>>>,
186    /// Each kind's words as a reference to it shows them, by kind name:
187    /// [`ReferenceWords`].
188    reference_words: BTreeMap<Name, ReferenceWords>,
189}
190
191/// The words that a reference to a theorem of one kind shows, as the kind's
192/// `zref-clever` reference type declares them for the recomposed LaTeX: each
193/// key of the type with its word, compiled as FLM markup, as
194/// [`refs::reference_type_words`] maps the kind's words to the keys.
195pub(super) type ReferenceWords = Vec<(&'static str, Arc<NodeTree<Flm>>)>;
196
197/// What the feature shares between its registration, its late-initialization
198/// hook and the theorem's rule: the configuration, the specifications of the
199/// three synthesized nodes, and what the hook compiled once it has run.
200pub(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    /// The headings of `config`, their synthesized nodes carrying `elements`
216    /// ([`synthesized_elements`]).
217    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    /// What the hook compiled; an error where it has not run.
229    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    /// The closing mark of the class `class`, where it has one.
236    pub(super) fn mark(&self, class: &Name) -> Result<Option<Arc<NodeTree<Flm>>>, LowerError> {
237        Ok(self.compiled()?.marks.get(class).cloned())
238    }
239
240    /// The base singular word of the kind `kind`, compiled as FLM content:
241    /// the word a heading shows alone where the theorem has no number, and
242    /// the display name the recomposed LaTeX gives the kind's environment in
243    /// its declaration (`Lemma` in `\newtheorem{lemma}{Lemma}`).
244    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    /// The words that a reference to a theorem of the kind `kind` shows.
251    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    /// Whether any class of the configuration has a closing mark.
258    pub(super) fn any_mark(&self) -> bool {
259        self.config.classes.values().any(|class| class.closing_mark.is_some())
260    }
261}
262
263/// What `error` reports, as one sentence: the diagnostics of a text that did
264/// not compile, one after the other.
265fn 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
274/// Whether the placeholder node `node` is the test of a conditional
275/// (`\IfValueT{#{title}}{…}`): the first argument of the nearest callable
276/// enclosing it, which is a conditional of the template language.
277fn 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
295/// How many times the compiled `template` shows `#{title}`: its occurrences
296/// other than the test of a conditional.
297fn 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
312/// Compiles `text`, the heading template of the class `class`.
313///
314/// # Errors
315///
316/// A sentence that identifies the class and says what is wrong with the
317/// template.
318fn 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
342/// Compiles `text` as fixed content (a closing mark, a word), which a
343/// message calls `what`.
344///
345/// # Errors
346///
347/// A sentence that gives `what` and says what is wrong with the text.
348fn 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
360/// The feature's build hook ([`LateInit`]): it compiles every class's
361/// heading template and closing mark and every kind's words once the
362/// language is built. A text that does not compile fails the registry build:
363/// it is configuration, and a mistake in it is reported once rather than at
364/// every theorem.
365pub(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        // The hook runs once per registration of the feature, and a registry
407        // holds the feature once, so the cell is empty here.
408        let _ = self.headings.compiled.set(compiled);
409        Ok(())
410    }
411}
412
413// --- the instance ----------------------------------------------------------------------------
414
415/// What replaces `#{title}` in a theorem's heading.
416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
417pub(super) enum TitleShown {
418    /// Nothing: the theorem has no title, or its back-reference is not shown.
419    Nothing,
420    /// The theorem's title, through a [`TITLE_POINTER`].
421    Title,
422    /// The statement a proof refers to, through a [`RELATION`].
423    Relation,
424}
425
426/// The heading of the theorem `node`, the node being lowered, of the kind
427/// `value`: its class's template with `#{name}` replaced by a
428/// [`NAME_ELEMENT`] node holding `number` (the number the numbering feature
429/// wrote for the theorem, word included), or the kind's word where `number`
430/// is `None`, and `#{title}` replaced as `title` says. The result is a
431/// synthesized value, ready to be spliced where the heading is placed
432/// ([`Lowerer::splice`]).
433///
434/// # Errors
435///
436/// [`LowerError`] when the templates were not compiled — the hook did not
437/// run — or when the instance could not be built.
438pub(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    // No title binds nothing: the name is declared absent, so that the
483    // template's `\IfValueT{#{title}}` takes its false branch.
484    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
500// --- the rules of the three synthesized elements ----------------------------------------------
501
502/// Stages `body` inside a span of role `role`; nothing for an empty body.
503fn 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/// The lowering rule [`NAME_RULE`], the default on every backend: a
517/// `flm.pres.span` of role [`NAME_ROLE`] around the node's body (the kind's
518/// word and the theorem's number), lowered through the rules. An empty body
519/// writes nothing.
520#[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
535/// The check both pointers of a heading make: the node the pointer refers to
536/// is a theorem, and the region is its title argument; anything else is
537/// reported as [`PointerRefused`] at the pointer `span`.
538fn 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/// The lowering rule [`TITLE_POINTER_RULE`], the default on every backend:
554/// the title the pointer refers to, lowered where the pointer is placed, as
555/// it is written in the theorem, through [`lower_content_pointer`], in a
556/// `flm.pres.span` of role [`TITLE_ROLE`].
557///
558/// A pointer to anything but a theorem's title argument is reported as
559/// [`PointerRefused`] and writes nothing; a pointer to a node the lowering
560/// cannot reach is reported as the lowering stage's
561/// `flm.lowering.region-not-found` and writes nothing.
562#[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/// The lowering rule [`RELATION_RULE`], the default on every backend: what a
580/// reference to the statement a proof refers to writes (the statement's
581/// word and number, linked to it), in a `flm.pres.span` of role
582/// [`TITLE_ROLE`]. The rule reads the proof whose title the node's pointer
583/// refers to, and writes the reference through the references feature's
584/// [`lower_reference`](refs::lower_reference); the target and its display
585/// options are those of the reference site the proof declares.
586///
587/// A back-reference that nothing resolves shows the label's text as an
588/// unresolved reference shows it; the references feature has reported it.
589/// Where the registry holds no references feature there is no resolution to
590/// read, and the label's text is shown, linked to nothing. The pointer is
591/// checked as [`TitlePointerRule`] checks it.
592#[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        // The region is lowered with the proof as the node being lowered, so
605        // the site read is the proof's own.
606        let mut shape = |cx: &mut LowerCx<'_>,
607                         lw: &mut dyn Lowerer,
608                         proof: &NodeRef<'_, Flm>,
609                         _content: &[NodeRef<'_, Flm>]| {
610            // The target and its display are the site's, as the proof
611            // declares it; the text is the label as written.
612            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
629/// The general lowering rules of the three synthesized elements, each the
630/// default on every backend.
631pub(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}