flm_core/stdlib/features/theorems/rules.rs
1//! The general lowering rule of a theorem, [`TheoremRule`] ([`THEOREM_RULE`]),
2//! the default on every backend that has no rule of its own for theorems: a
3//! block that opens with the theorem's heading and, for a class with a
4//! closing mark, closes with the mark.
5//!
6//! [`TheoremRule`] writes a theorem as a
7//! [`flm.pres.block`](crate::stdlib::backends::pres::BLOCK) of role
8//! [`THEOREM`], whose kind tokens are the class's name then the kind's
9//! (`theoremlike lemma`), around the theorem's body laid out as blocks. The
10//! block carries the anchor of the theorem's reference point where the
11//! references feature computed one. The [role and the kind
12//! tokens](crate::stdlib::backends::pres::payload) are what a stylesheet or a
13//! host's lowering rule selects on.
14//!
15//! The **heading** (the class's template instantiated at the theorem; see
16//! [`heading`](super::heading)) is placed at the start of the body's first
17//! paragraph as a
18//! [`flm.pres.deco.runin`](crate::stdlib::backends::pres::DECO_RUNIN)
19//! decoration, which each backend sets as it sets a run-in heading. The
20//! class's **closing mark** is placed at the end of the body's last paragraph
21//! as a [`flm.pres.deco.final`](crate::stdlib::backends::pres::DECO_FINAL)
22//! decoration. Where the body opens or closes with another block (a list, a
23//! quotation), the heading or the mark gets a paragraph of its own; a
24//! displayed formula stands inside its paragraph, so the heading or the mark
25//! shares that paragraph with it. An empty body gets one paragraph holding
26//! both.
27//!
28//! The kind's word and number in the heading are the theorem's number as the
29//! numbering feature wrote it, with the kind's word (`Lemma~4`), read from the
30//! counter table ([`COUNTERS`]) when the theorem is lowered. Where the
31//! document did not number the theorem (an unnumbered kind, or a registry
32//! without the numbering feature), the heading shows the kind's word alone
33//! (`Proof`). The heading's title is the theorem's title, or, where a proof
34//! shows its back-reference, the statement it refers to. The theorem's
35//! fields, `\label{…}` and `\noproofref`, are not written.
36
37use std::sync::Arc;
38
39use techy::core::node::{BuildId, NodeRef};
40
41use crate::core::lowering::{
42 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
43};
44use crate::lang::Flm;
45use crate::model::aspects::PointId;
46use crate::model::element::element_value;
47use crate::model::names::{ElementName, Name};
48use crate::stdlib::backends::lowering::lower_blocks_with_edges;
49use crate::stdlib::backends::pres::{self, BlockPayload, DecorationPayload};
50use crate::stdlib::features::numbering::{COUNTERS, FormatOptions, NumberSegment};
51use crate::stdlib::features::refs::ANCHORS;
52
53use super::elements::{
54 THEOREM, TheoremElement, TitleReading, relation_site, theorem_point, title_reading,
55};
56use super::heading::{Headings, TitleShown, heading_instance};
57use super::html::STYLE;
58
59/// The name of the theorem's general lowering rule,
60/// `flm.theorems.theorem.lower.default` ([`TheoremRule`]).
61pub const THEOREM_RULE: &str = "flm.theorems.theorem.lower.default";
62
63/// The lowering rule [`THEOREM_RULE`]: a theorem as a block with its heading
64/// and closing mark. See the [module documentation](self).
65///
66/// A title that begins with a star, on a kind whose class reads
67/// back-references, but that is not a well-formed back-reference is shown as
68/// written; the feature's check reports it as
69/// [`BadRelationRef`](super::BadRelationRef), under every workflow. A title
70/// in the template of a kept definition ([kept
71/// definitions](crate::stdlib::features::userdefs::kept)) whose first
72/// characters a call supplies
73/// ([`TitleReading::Unknown`]) makes the rule return
74/// [`LowerError::PlaceholderCharacters`], so that each use site is expanded
75/// instead.
76///
77/// At every theorem the rule requires the feature's style identifier
78/// [`STYLE`] (`flm.theorems.style`), which each backend
79/// resolves as it resolves requirements: the stylesheet on the `html`
80/// backend, the definition pieces delivering it on the `latex-rendered`
81/// backend, nothing on the `text` backend.
82#[derive(Debug)]
83pub struct TheoremRule {
84 headings: Arc<Headings>,
85}
86
87impl TheoremRule {
88 /// The rule that writes the headings and closing marks that `headings`
89 /// compiled.
90 pub(super) fn new(headings: Arc<Headings>) -> TheoremRule {
91 TheoremRule { headings }
92 }
93
94 /// The number of the theorem at `point`, as the numbering feature wrote
95 /// it with the kind's word; `None` where this document did not number it,
96 /// or the registry holds no numbering feature.
97 fn number(lw: &dyn Lowerer, point: PointId) -> Result<Option<Vec<NumberSegment>>, LowerError> {
98 let Some(counters) = lw.get(COUNTERS)? else { return Ok(None) };
99 match counters.format(point, &FormatOptions::new()) {
100 None => Ok(None),
101 Some(written) => written.map(Some).map_err(|error| LowerError::structure(error.to_string())),
102 }
103 }
104
105 /// Stages `content` inside a decoration of the element `element`.
106 fn decoration(
107 cx: &mut LowerCx<'_>,
108 lw: &mut dyn Lowerer,
109 element: &str,
110 content: Vec<BuildId>,
111 ) -> Result<Vec<BuildId>, LowerError> {
112 Ok(vec![lw.pres_with(cx, &ElementName::from(element), DecorationPayload, content)?])
113 }
114}
115
116impl Lower for TheoremRule {
117 fn lower(
118 &self,
119 node: NodeRef<'_, Flm>,
120 cx: &mut LowerCx<'_>,
121 lw: &mut dyn Lowerer,
122 ) -> Result<Lowering, LowerError> {
123 lw.require(&Name::from(STYLE));
124 let value = element_value::<TheoremElement>(&node)
125 .ok_or_else(|| LowerError::structure("a theorem without its element's data"))?;
126 // The title is read once; a malformed back-reference is shown as
127 // written, the feature's check reporting it, so that a run that lowers
128 // nothing reports it too.
129 let title = match title_reading(&node).unwrap_or(TitleReading::Absent) {
130 TitleReading::Absent => TitleShown::Nothing,
131 TitleReading::Title => TitleShown::Title,
132 // Shown as the declared site says.
133 TitleReading::Relation { .. } => match relation_site(&node) {
134 Some(site) if site.shown => TitleShown::Relation,
135 _ => TitleShown::Nothing,
136 },
137 TitleReading::Malformed => TitleShown::Title,
138 // A kept template's title whose characters a call supplies: the
139 // use sites are expanded, and each is lowered with its own.
140 TitleReading::Unknown => return Err(LowerError::PlaceholderCharacters),
141 };
142 let point = theorem_point(lw.addr());
143 // The anchors table is absent in a registry holding no references
144 // feature: the theorem is written with no anchor.
145 let anchor = lw.get(ANCHORS)?.and_then(|anchors| anchors.id(point)).map(String::from);
146 let number = TheoremRule::number(lw, point)?;
147 let instance = heading_instance(&self.headings, &node, lw, value, number.as_deref(), title)?;
148 let heading = lw.splice(cx, &instance)?;
149 let leading = TheoremRule::decoration(cx, lw, pres::DECO_RUNIN, heading)?;
150 let trailing = match self.headings.mark(&value.class_name)? {
151 Some(mark) => {
152 let mark = lw.splice(cx, &mark)?;
153 TheoremRule::decoration(cx, lw, pres::DECO_FINAL, mark)?
154 }
155 None => Vec::new(),
156 };
157 let body: Vec<NodeRef<'_, Flm>> =
158 node.body().map(|body| body.iter().collect()).unwrap_or_default();
159 let children = lower_blocks_with_edges(cx, lw, &body, leading, trailing)?;
160 let payload = BlockPayload {
161 role: Some(Name::from(THEOREM)),
162 kinds: vec![value.class_name.clone(), value.name.clone()],
163 anchor,
164 doc_role: None,
165 };
166 let block = lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, children)?;
167 Ok(Lowering::Emit(vec![block]))
168 }
169}
170
171/// The theorem's general lowering rule, [`THEOREM_RULE`], the default on
172/// every backend, writing the headings and closing marks that `headings`
173/// compiled. It reads the anchors table and the counter table optionally, so
174/// that a registry without the references or the numbering feature still
175/// renders a theorem. The rule declares that it produces the final decoration
176/// only where a class has a closing mark, so that a registry in which none can
177/// occur does not require its backend to render one.
178pub(super) fn theorem_rule(headings: Arc<Headings>) -> LoweringRule {
179 LoweringRule::new(
180 THEOREM_RULE,
181 THEOREM,
182 theorem_decl(&headings),
183 Arc::new(TheoremRule::new(headings)),
184 DefaultMark::Everywhere,
185 )
186 .docs(
187 "a theorem lowers to `flm.pres.block` of role `flm.theorems.theorem`, its kind tokens \
188 the class and the kind, carrying its anchor, around its body's blocks; the heading is a \
189 `flm.pres.deco.runin` decoration at the start of the first paragraph and the closing \
190 mark a `flm.pres.deco.final` decoration at the end of the last",
191 )
192}
193
194/// What the theorem's general rule declares: it reads the anchors table and
195/// the counter table optionally, and produces the block, its paragraphs and
196/// the run-in decoration, and the final decoration where a class of
197/// `headings` has a closing mark.
198fn theorem_decl(headings: &Headings) -> LoweringDecl {
199 let decl = LoweringDecl::new()
200 .reads_opt(ANCHORS)
201 .reads_opt(COUNTERS)
202 .produces(pres::BLOCK)
203 .produces(pres::PAR)
204 .produces(pres::DECO_RUNIN);
205 if headings.any_mark() { decl.produces(pres::DECO_FINAL) } else { decl }
206}