flm_core/stdlib/features/theorems/mod.rs
1//! The `theorems` feature: the theorem-like environments of mathematical
2//! writing. These are numbered, titled block environments such as `theorem`,
3//! `lemma` and `definition`, and the `proof` environment, whose title can refer
4//! back to the statement it proves. Every environment is declared from the
5//! feature's configuration ([`TheoremsConfig`]), so a host can add environments
6//! of its own (an `exercise`) or remove shipped ones.
7//!
8//! # What an author writes
9//!
10//! ```text
11//! \begin{lemma}[Key lemma]\label{lem:key}
12//! Every bounded monotone sequence converges.
13//! \end{lemma}
14//!
15//! \begin{proof}[*lem:key]
16//! By completeness.
17//! \end{proof}
18//! ```
19//!
20//! prints, on the text backend,
21//!
22//! ```text
23//! Lemma 1 (Key lemma). Every bounded monotone sequence converges.
24//!
25//! Proof (Lemma 1). By completeness. □
26//! ```
27//!
28//! Each environment is one **theorem kind** (`lemma` above). It takes an
29//! optional title in brackets, then two fields in any order, `\label{…}`
30//! (repeatable) and `\noproofref` (which says that no proof of the statement
31//! is coming), and a body laid out as blocks ([`elements`]). A proof's title
32//! written `[*lem:key]` is a **back-reference**: it refers to the statement
33//! labeled `lem:key` and shows that statement's word and number in the proof's
34//! heading; `[**lem:key]` refers to the same statement and shows nothing in
35//! the heading. The
36//! language guide describes these environments for authors under
37//! [Theorems](crate::guide::language_syntax#theorems).
38//!
39//! # Theorem kinds and theorem classes
40//!
41//! Every theorem kind belongs to one **theorem class** ([`TheoremClass`]),
42//! which holds what a family of kinds shares: whether its kinds are numbered
43//! and in which counter, the heading template, the closing mark, and whether a
44//! title beginning with `*` is read as a back-reference. A kind
45//! ([`TheoremKind`]) adds its words (`Lemma`, `Lemmas`, and variants such as
46//! the abbreviation `Lem.`) and whether each of its statements expects a
47//! proof. The default configuration ([`TheoremsConfig::new`]) declares:
48//!
49//! - `theorem`, `proposition`, `lemma`, `corollary` and `conjecture` in the
50//! class `theoremlike`, and `definition` and `remark` in the class
51//! `definitionlike`, all numbered in one shared counter;
52//! - `proof` in the class `prooflike`: unnumbered, closed by the mark `□`,
53//! its title read as a back-reference.
54//!
55//! The feature's code refers to no kind and no class by name: a host's
56//! `exercise` is an environment in its own right, declared in the
57//! configuration. The configuration is fixed when the registry is built
58//! (see [settings, options and
59//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
60//!
61//! # Numbers, labels and back-references
62//!
63//! Every theorem is one [reference point](crate::model::aspects::RefPoint) of
64//! the reference kind `theorem` (see [reference points, labels and
65//! anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).
66//! A theorem of a numbered kind is numbered by the
67//! [`numbering`](crate::stdlib::features::numbering) feature in its class's
68//! [counter](crate::stdlib::features::numbering::CounterDecl) and shown in a
69//! [counter style](crate::stdlib::features::numbering::CounterStyleDecl) of
70//! its kind, whose words are the kind's ([`numbers`]): `\ref{lem:key}` reads
71//! `Lemma~1`; in a document that numbers theorems within sections it reads
72//! `Lemma~2.3` on every output except the recomposed LaTeX, where LaTeX
73//! numbers the theorems (see [the
74//! limitation](latex#limitation-theorems-numbered-within-sections)). Its anchor is the
75//! environment's name and its number, `lemma-1`. A theorem of an unnumbered
76//! kind accepts no label and has no anchor.
77//!
78//! A back-reference is a [reference site](crate::model::aspects::RefSite),
79//! which the [references](crate::stdlib::features::refs) feature resolves as
80//! it resolves `\ref`. [`title_reading`] is the function that decides whether
81//! a title is a back-reference. On a class that reads back-references, a title
82//! that begins with a star is kept as typed: its reader places it under an
83//! opaque wrapper, so that its label meets the label of a `\label` as written,
84//! and `[*lem:a--b]` refers to `\label{lem:a--b}`. Every other title is content
85//! (see [a starred title is kept as
86//! typed](elements#a-starred-title-is-kept-as-typed)).
87//!
88//! # The check of proofs
89//!
90//! A statement of a kind that [expects a proof](TheoremKind::expects_proof)
91//! (by default `theorem`, `proposition`, `lemma` and `corollary`) should have
92//! a proof whose back-reference refers to it, unless it carries `\noproofref`.
93//! The feature's check stage ([`check`]) reports a statement that has neither
94//! as the Warning `flm.theorems.missing-proof`, and a title that begins with a
95//! star but is not a well-formed back-reference as the Error
96//! `flm.theorems.bad-relation-ref`. The stage is a member of the
97//! [`flm.validated`](crate::stdlib::VALIDATED) collection, which every
98//! standard workflow demands, so it runs, with the same reports, under the
99//! `check` workflow and under every render. It reads the document tree: a
100//! theorem inside a user definition that the plan keeps unexpanded is not
101//! checked (see [`check`]).
102//!
103//! # What the feature provides to the pipeline
104//!
105//! - **Elements.** [`THEOREM`] (`flm.theorems.theorem`), with one element
106//! value per configured kind, available in text mode. Three synthesized
107//! elements, [`NAME_ELEMENT`], [`TITLE_POINTER`] and [`RELATION`], hold the
108//! parts of a theorem's heading ([`heading`]); no document can write them.
109//! - **The general lowering rules**, each the default on every backend:
110//! [`THEOREM_RULE`] and the rules of the three heading elements,
111//! [`NAME_RULE`], [`TITLE_POINTER_RULE`] and [`RELATION_RULE`]. A theorem
112//! becomes a `flm.pres.block` of role `flm.theorems.theorem` whose kind
113//! tokens are the class's name and the kind's (`theoremlike lemma`), with
114//! its heading as a run-in decoration at the head of its first paragraph
115//! and, for a class with a closing mark, the mark as a final decoration at
116//! the end of its last paragraph ([`rules`]; see
117//! [decorations](crate::stdlib::backends::pres::Decoration) and [roles and
118//! kinds](crate::stdlib::backends::pres::payload)). The
119//! heading is the class's heading template, with the kind's word and number
120//! in a span of role `flm.theorems.name` and the title in a span of role
121//! `flm.theorems.title`; the title is lowered where the heading shows it,
122//! never copied ([`heading`]). The text and html backends write a stop
123//! after the heading (their render option `run_in_stop`, a period by
124//! default; see
125//! [`TextRenderOptions::run_in_stop`](crate::stdlib::backends::text::stages::TextRenderOptions::run_in_stop)
126//! and
127//! [`HtmlRenderOptions::run_in_stop`](crate::stdlib::backends::html::feature::HtmlRenderOptions::run_in_stop))
128//! unless the heading already ends in punctuation; the text backend writes a
129//! non-breaking space before the closing mark.
130//! At every theorem the general rule requires the feature's style
131//! identifier `flm.theorems.style` ([`html::STYLE`]).
132//! - **On the `html` backend**, the stylesheet `flm.theorems.style`
133//! ([`html`]), which the requirement brings into a page holding a theorem
134//! and which sets the kind's word and number apart from the title.
135//! - **On the `latex-rendered` backend**, the definition piece
136//! `flm.latex.def.flmx.theorems` ([`latex_rendered`]), which the same
137//! requirement brings into the style file and which registers the look of
138//! each class of theorem.
139//! - **On the `latex-recomposed` backend**, rules of their own ([`latex`]): a
140//! theorem is written back as the environment the author wrote, and the
141//! style file declares each kind the document uses. A proof's
142//! back-reference is written in one of two forms, which the backend's render
143//! option `resolved_proof_refs` chooses: as the author wrote it, for the
144//! `phfthm` LaTeX package to read (the default), or resolved into the
145//! proof's title, over the `amsthm` package alone. The rendering guide
146//! describes this output under [Theorems in the recomposed
147//! LaTeX](crate::guide::rendering#theorems-in-the-recomposed-latex).
148//! - **Counters and counter styles** ([`numbers`]), contributed to the
149//! numbering feature's service slots.
150//! - **A check stage**, [`CHECK_PROOFS`] (`flm.theorems.check-proofs`),
151//! providing the capability of the same name, a member of the
152//! [`flm.validated`](crate::stdlib::VALIDATED) collection ([`check`]).
153//! - **A configuration**, [`TheoremsConfig`], whose fields are the feature's
154//! settings keys. A build hook ([`LateInit`](crate::core::registry::LateInit))
155//! compiles the heading templates, the closing marks and the kinds' words
156//! once the language is built; a text that does not compile fails the
157//! registry build.
158//!
159//! # Interactions with other features
160//!
161//! - **The numbering feature.** Without it, no theorem is numbered: a heading
162//! shows the kind's word alone (`Theorem`), and a theorem's anchor comes from
163//! its first label.
164//! - **The references feature.** It resolves labels and back-references and
165//! computes anchors. Without it, no label resolves, a theorem has no anchor,
166//! a back-reference shows its label's text, and the check reports no missing
167//! proof.
168//! - The feature reads the tables of these two features optionally, and
169//! declares them through peer declarations
170//! ([`PeerName`](crate::core::registry::PeerName)); it declares the same
171//! way the argument role that the references feature gives the argument of
172//! a theorem's `\label` field
173//! ([`DEFINED_LABEL_ARG_ROLE`](crate::stdlib::features::refs::DEFINED_LABEL_ARG_ROLE)).
174//! It therefore builds and renders in a registry that holds neither. The rules of the `latex-recomposed`
175//! backend are registered under peer declarations of their backend and of
176//! the LaTeX family's elements; in a registry without them, those rules are
177//! set aside (excluded from rule selection; see
178//! [`PeerName`](crate::core::registry::PeerName)).
179//! - **User definitions.** A theorem written in a user definition's template is
180//! checked and numbered where the template is expanded in the tree. The
181//! title's reader sees a star written in the template (`[*#1]`), and keeps
182//! that title as typed. It does not see a star that arrives through a
183//! placeholder (a template `[#1]` used as `\pf{*lem:a--b}`): that title is
184//! laid out as content, and a label holding `--`, quotes, an apostrophe or
185//! `...` does not resolve through it. A
186//! theorem in the template of a kept definition (a user definition whose use
187//! sites the plan leaves in the tree; see [kept
188//! definitions](crate::stdlib::features::userdefs::kept)) whose title holds
189//! a placeholder where a back-reference's star could be is expanded at each
190//! use site instead ([`TitleReading::Unknown`]).
191//!
192//! # Map of the items
193//!
194//! - The feature: [`Theorems`], [`feature`], [`FEATURE`].
195//! - The configuration: [`TheoremsConfig`], [`TheoremClass`], [`TheoremKind`]
196//! and their constants ([`DEFAULT_HEADING`], [`DEFAULT_CLOSING_MARK`],
197//! [`DEFAULT_LABEL_TYPES`], [`LOWERCASE_VARIANT`], [`CAPITAL_VARIANT`],
198//! [`ABBREVIATED_VARIANT`]).
199//! - The element and its reading: [`elements`] ([`THEOREM`],
200//! [`TheoremElement`], [`title_reading`], [`TitleReading`],
201//! [`has_noproofref`], [`theorem_args`]).
202//! - The heading: [`heading`]. The general rule of a theorem: [`rules`].
203//! - The counters and counter styles: [`numbers`].
204//! - The check of proofs: [`check`] ([`CHECK_PROOFS`]).
205//! - The conditions: [`MissingProof`], [`BadRelationRef`], [`PointerRefused`],
206//! [`StageFailed`].
207//! - The stylesheet: [`html`]. The `latex-recomposed` backend's own rules:
208//! [`latex`].
209
210pub mod check;
211mod config;
212mod diagnostics;
213pub mod elements;
214pub mod heading;
215pub mod html;
216pub mod latex;
217pub mod latex_rendered;
218pub mod numbers;
219pub mod rules;
220
221use std::sync::Arc;
222
223use crate::core::settings::SettingsDecl;
224use crate::core::registry::{BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature};
225use crate::lang::mint::{BodyDef, ElementDef, SyntaxDef};
226use crate::stdlib::features::numbering::{COUNTERS, Counters};
227use crate::stdlib::VALIDATED;
228use crate::stdlib::features::refs;
229
230pub use config::{
231 ABBREVIATED_VARIANT, CAPITAL_VARIANT, DEFAULT_CLOSING_MARK, DEFAULT_HEADING,
232 DEFAULT_LABEL_TYPES, LOWERCASE_VARIANT, TheoremClass, TheoremKind, TheoremsConfig,
233};
234pub use check::CHECK_PROOFS;
235pub use diagnostics::{BadRelationRef, MissingProof, PointerRefused, StageFailed};
236pub use elements::{
237 NOPROOFREF_FIELD, POINT_KIND, THEOREM, TITLE_ARG, TheoremElement, TitleReading, has_noproofref,
238 theorem_args, title_reading,
239};
240pub use heading::{
241 NAME_ELEMENT, NAME_PLACEHOLDER, NAME_ROLE, NAME_RULE, NameRule, RELATION, RELATION_RULE,
242 RelationRule, TITLE_PLACEHOLDER, TITLE_POINTER, TITLE_POINTER_RULE, TITLE_ROLE,
243 TitlePointerRule,
244};
245pub use rules::{THEOREM_RULE, TheoremRule};
246
247// Theorem kinds are values of one element type, so that a kind the configuration
248// adds is an environment in its own right with no code written for it; the kinds
249// are grouped into classes so that what describes a kind's shape is stated once
250// per class.
251
252/// The feature's registered name, `theorems`.
253pub const FEATURE: &str = "theorems";
254
255/// The declaration of the feature's settings: the fields of [`TheoremsConfig`] are its keys, and
256/// the texts a kind's words, a class's heading template and closing mark, and the number format
257/// hold are FLM markup. See [`crate::core::settings`].
258fn settings() -> SettingsDecl {
259 SettingsDecl::new(FEATURE)
260 .config::<TheoremsConfig>(
261 "The theorem-like environments: the theorem classes (whether numbered, whether \
262 in the shared counter, the heading template, the closing mark, whether a proof's \
263 title is read as a back-reference), the theorem kinds (the class, the words, \
264 whether a proof is expected), the number format and the label types a numbered \
265 kind accepts. Fixed when the registry is built: it cannot vary per document or \
266 per render.",
267 )
268 .merge_entries("classes", || serde_json::to_value(&TheoremsConfig::default().classes).map_err(|error| error.to_string()))
269 .remove_false("classes")
270 .merge_entries("kinds", || serde_json::to_value(&TheoremsConfig::default().kinds).map_err(|error| error.to_string()))
271 .remove_false("kinds")
272 .markup("kinds.*.words")
273 .markup("classes.*.heading")
274 .markup("classes.*.closing_mark")
275 .markup("number_format")
276}
277
278/// The `theorems` feature ([`FlmFeature`]): it registers one element value of
279/// [`THEOREM`] per kind of its [`TheoremsConfig`], each written as the
280/// environment of the kind's name, together with the heading elements, the
281/// lowering rules, the check stage, and the counters and counter styles of the
282/// numbered kinds (contributed to the numbering feature). See the [module
283/// documentation](self).
284///
285/// Construct it with [`Theorems::new`], or use [`feature`] for the default
286/// configuration. Registering it fails with [`BuildError::Feature`] when the
287/// configuration is refused by [`TheoremsConfig::validate`], and the registry
288/// build fails when a heading template, a closing mark or a word does not
289/// compile.
290#[derive(Debug, Default, Clone)]
291pub struct Theorems {
292 config: TheoremsConfig,
293}
294
295impl Theorems {
296 /// Creates the feature with the configuration `config`, which is fixed for
297 /// the life of the registry the feature is registered into.
298 pub fn new(config: TheoremsConfig) -> Theorems {
299 Theorems { config }
300 }
301
302 /// The configuration this feature was constructed with.
303 pub fn config(&self) -> &TheoremsConfig {
304 &self.config
305 }
306}
307
308impl FlmFeature for Theorems {
309 fn info(&self) -> FeatureInfo {
310 FeatureInfo::new(FEATURE, "Theorems").docs(
311 "Theorem-like environments (`theorem`, `lemma`, `proof`, …), one per configured \
312 kind, all of the element `flm.theorems.theorem`: each with an optional title, \
313 numbered and labeled where its kind's class is numbered, a heading at the start of \
314 its first paragraph, an optional closing mark, and, on a proof, a back-reference \
315 to the statement it proves.",
316 )
317 }
318
319 fn settings(&self) -> Option<SettingsDecl> {
320 Some(settings())
321 }
322
323 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
324 let owner = b.feature().clone();
325 self.config
326 .validate()
327 .map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
328 // The `\label` field of a theorem environment is the references
329 // feature's, with that feature's role on its argument; declared as a
330 // peer, so that a registry without that feature still builds.
331 b.peer_argument_role(refs::DEFINED_LABEL_ARG_ROLE)?;
332 for name in self.config.kinds.keys() {
333 // Every kind names a declared class: the configuration was checked.
334 let Some(value) = TheoremElement::of(&self.config, name) else { continue };
335 let args = theorem_args(value.class.relation_ref);
336 let docs = format!(
337 "Writes a statement of the theorem-like kind `{name}`, of the theorem class `{}`: \
338 a heading with an optional title, then a body of blocks.",
339 value.class_name
340 );
341 b.element(
342 ElementDef::new(
343 owner.clone(),
344 [name.as_str()],
345 SyntaxDef::Environment { args, body: BodyDef::new().blocks() },
346 elements::theorem_element(value),
347 )
348 .docs(docs),
349 )?;
350 }
351 if !self.config.kinds.is_empty() {
352 b.element_type_text(
353 elements::THEOREM,
354 "A theorem-like statement, such as a theorem, a definition or a proof: a heading \
355 that shows the kind's word, with the statement's number and title where it has \
356 them, then a body of blocks.",
357 )?;
358 }
359 // The nodes an instantiated heading holds: synthesized, so no
360 // document can write them.
361 let synthesized = heading::synthesized_elements();
362 for element in &synthesized {
363 b.element(
364 ElementDef::new(owner.clone(), Vec::<&str>::new(), SyntaxDef::Synthesized, Arc::clone(element))
365 .docs(element.docs.clone()),
366 )?;
367 }
368 b.element_type_text(
369 heading::NAME_ELEMENT,
370 "The kind's word and the number of a theorem-like statement, in its heading.",
371 )?;
372 b.element_type_text(
373 heading::TITLE_POINTER,
374 "The title of a theorem-like statement, in its heading.",
375 )?;
376 b.element_type_text(
377 heading::RELATION,
378 "The statement a proof refers to, in the proof's heading.",
379 )?;
380 numbers::declare(b, &self.config)?;
381 // The three tables belong to the numbering and the references
382 // features, which may be absent: the rules read them optionally, and
383 // write a theorem with no number, no anchor, and a back-reference as
384 // its label's text.
385 b.peer_table::<Counters>(
386 COUNTERS.name(),
387 "the numbering feature's counter table, which the theorem's rule reads for the \
388 number its heading shows, and the back-reference's rule for the number of the \
389 statement a proof refers to",
390 )?;
391 b.peer_table::<refs::Anchors>(
392 refs::ANCHORS.name(),
393 "the references feature's anchors table, which the theorem's rule reads for the \
394 anchor of the theorem's reference point",
395 )?;
396 b.peer_table::<refs::RefResolutions>(
397 refs::REF_RESOLUTIONS.name(),
398 "the references feature's resolutions table, which the back-reference's rule \
399 reads for the statement a proof refers to",
400 )?;
401 let headings = Arc::new(heading::Headings::new(self.config.clone(), &synthesized));
402 b.late_init(Arc::new(heading::CompileHeadings { headings: Arc::clone(&headings) }))?;
403 b.lowering_rule(rules::theorem_rule(Arc::clone(&headings)))?;
404 for rule in heading::rules() {
405 b.lowering_rule(rule)?;
406 }
407 b.digest_input(&self.config.digest_bytes())?;
408 b.capability(CapabilityDef::new(CHECK_PROOFS).docs(
409 "The theorems have been checked: every statement expecting a proof that no proof \
410 refers back to and that carries no `\\noproofref` was reported as a Warning, and \
411 every title that begins with a star but is not a well-formed back-reference as an \
412 Error. A member of `flm.validated`.",
413 ))?;
414 b.stage(Arc::new(check::CheckProofs::new(&self.config)))?;
415 b.collection_member(VALIDATED, CHECK_PROOFS)?;
416 html::register(b)?;
417 latex_rendered::register(b)?;
418 latex::register(b, headings)?;
419 Ok(())
420 }
421}
422
423/// The [`Theorems`] feature under the default configuration (the eight kinds
424/// of [`TheoremsConfig::new`]), ready to be listed in a package entry
425/// ([`PackageEntry`](crate::core::registry::PackageEntry)).
426///
427/// Use `Arc::new(Theorems::new(config))` to list the feature under a
428/// [`TheoremsConfig`] of your own.
429pub fn feature() -> Arc<dyn FlmFeature> {
430 Arc::new(Theorems::default())
431}