Skip to main content

flm_core/stdlib/features/theorems/
config.rs

1//! The configuration of the [`theorems`](super) feature, [`TheoremsConfig`]:
2//! the theorem classes ([`TheoremClass`]), the theorem kinds
3//! ([`TheoremKind`]), the number format of every kind's number, and the label
4//! types a numbered kind accepts; with the three shipped sets of classes and
5//! kinds and the constants they use.
6
7use std::collections::BTreeMap;
8use std::hash::{Hash, Hasher};
9
10use crate::model::names::Name;
11use crate::stdlib::features::numbering::{NumberTemplate, PluralWords, PrefixWords};
12
13/// The heading template of every shipped theorem class,
14/// `#{name}\IfValueT{#{title}}{ (#{title})}`: the kind's word and number,
15/// then the title between parentheses where the theorem has one, as in
16/// `Lemma 4 (Key lemma)`, or `Lemma 4` alone ([`TheoremClass::heading`]
17/// describes the placeholders).
18pub const DEFAULT_HEADING: &str = r"#{name}\IfValueT{#{title}}{ (#{title})}";
19
20/// The closing mark of the shipped theorem class `prooflike`, `□`
21/// ([`TheoremClass::closing_mark`]).
22pub const DEFAULT_CLOSING_MARK: &str = "\u{25a1}";
23
24/// The label types a numbered theorem kind accepts by default
25/// ([`TheoremsConfig::label_types`]): `thm`, `prop`, `cor`, `lem`, `rem`,
26/// `def`, `dfn`, `x` and `topic`. Every numbered kind accepts every one of
27/// them: `\label{lem:x}` on a `theorem` is accepted.
28pub const DEFAULT_LABEL_TYPES: [&str; 9] =
29    ["thm", "prop", "cor", "lem", "rem", "def", "dfn", "x", "topic"];
30
31/// The name of the variant of a theorem kind's words written all in
32/// lowercase, `lowercase`: `\ref[lowercase]{lem:x}` reads `lemma~4`. The
33/// references feature defines the name.
34pub const LOWERCASE_VARIANT: &str = crate::stdlib::features::refs::LOWERCASE_VARIANT;
35
36/// The name of the variant of a theorem kind's words written with a capital
37/// initial, `capital`: the variant that `\ref[S]{…}` and `\ref[capital]{…}`
38/// ask for. The references feature defines the name.
39pub const CAPITAL_VARIANT: &str = crate::stdlib::features::refs::CAPITAL_VARIANT;
40
41/// The name of the variant of a theorem kind's words written abbreviated,
42/// `abbreviated`: `\ref[abbreviated]{lem:x}` reads `Lem.~4` where the kind
43/// declares that variant. The references feature defines the name.
44pub const ABBREVIATED_VARIANT: &str = crate::stdlib::features::refs::ABBREVIATED_VARIANT;
45
46/// One **theorem class**: what a family of theorem kinds shares. A class
47/// says whether its kinds are numbered and in which counter, how their
48/// heading is written, whether a closing mark ends them, and whether a title
49/// beginning with `*` is read as a back-reference to the statement a theorem
50/// proves.
51///
52/// A class is declared under its name in [`TheoremsConfig::classes`], and a
53/// kind refers to it by that name ([`TheoremKind::class`]). The three shipped
54/// classes are `theoremlike` and `definitionlike`, numbered in the shared
55/// counter, and `prooflike`, unnumbered, closed by the mark `□` and reading a
56/// back-reference from its title (see [`TheoremsConfig`]). The constructors
57/// [`numbered`](TheoremClass::numbered) and
58/// [`unnumbered`](TheoremClass::unnumbered) start a class, and the builders
59/// set its other fields.
60///
61/// # Examples
62///
63/// ```
64/// use flm_core::stdlib::features::theorems::{TheoremClass, DEFAULT_HEADING};
65///
66/// // Numbered, each kind in a counter of its own, the title joined by "of".
67/// let exercise = TheoremClass::numbered()
68///     .shared_counter(false)
69///     .heading(r"#{name}\IfValueT{#{title}}{ of #{title}}");
70/// assert!(exercise.numbered && !exercise.shared_counter);
71///
72/// // Unnumbered, with a closing mark, reading `[*lem:x]` as a back-reference.
73/// let prooflike = TheoremClass::unnumbered()
74///     .closing_mark(Some(r"\(\blacksquare\)".to_string()))
75///     .relation_ref(true);
76/// assert_eq!(prooflike.heading, DEFAULT_HEADING);
77/// ```
78#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
79#[derive(schemars::JsonSchema)]
80#[serde(deny_unknown_fields)]
81pub struct TheoremClass {
82    /// Whether the kinds of this class are numbered. A theorem of a numbered
83    /// kind is one reference point numbered in the class's counter; a theorem
84    /// of an unnumbered kind is a reference point that nothing numbers and that
85    /// accepts no label.
86    pub numbered: bool,
87    /// For a numbered class, whether its kinds count in the shared counter
88    /// `flm.theorems.theorem` (`true`), or each kind in a counter of its own,
89    /// `flm.theorems.counter.<kind>` (`false`); see
90    /// [`numbers`](super::numbers). Unused for an unnumbered class.
91    pub shared_counter: bool,
92    /// The **theorem heading template**: how the heading that opens every
93    /// theorem of the class joins the kind's word and number with the
94    /// theorem's title. It is written in the [template
95    /// language](crate::guide::concepts_overview#the-template-language-shared-by-features)
96    /// (the language guide describes it for authors under [the template
97    /// language](crate::guide::language_syntax#the-template-language)), with
98    /// two placeholders:
99    ///
100    /// - `#{name}` is the kind's word and the theorem's number (`Lemma~4`), or
101    ///   the word alone where the theorem has no number;
102    /// - `#{title}` is the theorem's title, or, for a class that reads
103    ///   back-references, the statement a proof refers to. A theorem with no
104    ///   title, or whose back-reference is not shown, binds nothing to
105    ///   `#{title}`, so `\IfValueT{#{title}}{…}` tests whether there is one.
106    ///   The template may show `#{title}` at most once; an occurrence as the
107    ///   test of a conditional (`\IfValueT{#{title}}`) is not counted.
108    ///
109    /// [`DEFAULT_HEADING`] by default. A template that does not compile fails
110    /// the registry build ([`heading`](super::heading)). The recomposed LaTeX
111    /// does not use the template: LaTeX writes the heading
112    /// ([`latex`](super::latex)).
113    pub heading: String,
114    /// The closing mark written at the end of every theorem of the class, as
115    /// FLM markup (`□` for the shipped class `prooflike`), or `None` for no
116    /// mark. A mark that does not parse fails the registry build.
117    pub closing_mark: Option<String>,
118    /// Whether a title beginning with `*` is read as a back-reference to the
119    /// statement the theorem proves: `[*lem:x]` shows the statement's word
120    /// and number in the heading, and `[**lem:x]` refers to the same
121    /// statement and shows nothing in the heading
122    /// ([`title_reading`](super::title_reading)). A class that does not read
123    /// back-references takes every title as a title.
124    pub relation_ref: bool,
125}
126
127impl TheoremClass {
128    /// A numbered class counting in the shared counter, with the heading
129    /// template [`DEFAULT_HEADING`], no closing mark, and titles that are
130    /// never read as back-references.
131    pub fn numbered() -> TheoremClass {
132        TheoremClass {
133            numbered: true,
134            shared_counter: true,
135            heading: DEFAULT_HEADING.to_string(),
136            closing_mark: None,
137            relation_ref: false,
138        }
139    }
140
141    /// An unnumbered class, with the heading template [`DEFAULT_HEADING`], no
142    /// closing mark, and titles that are never read as back-references.
143    pub fn unnumbered() -> TheoremClass {
144        TheoremClass { numbered: false, ..TheoremClass::numbered() }
145    }
146
147    /// Builder: whether the kinds count in the shared counter.
148    pub fn shared_counter(mut self, shared_counter: bool) -> TheoremClass {
149        self.shared_counter = shared_counter;
150        self
151    }
152
153    /// Builder: sets the heading template.
154    pub fn heading(mut self, heading: impl Into<String>) -> TheoremClass {
155        self.heading = heading.into();
156        self
157    }
158
159    /// Builder: sets the closing mark (FLM markup), or `None` for no mark.
160    pub fn closing_mark(mut self, closing_mark: Option<String>) -> TheoremClass {
161        self.closing_mark = closing_mark;
162        self
163    }
164
165    /// Builder: whether a title beginning with `*` is read as a
166    /// back-reference.
167    pub fn relation_ref(mut self, relation_ref: bool) -> TheoremClass {
168        self.relation_ref = relation_ref;
169        self
170    }
171}
172
173/// One **theorem kind**: one environment an author writes, such as
174/// `theorem`, `lemma`, `proof` or a host's `exercise`. Its key in
175/// [`TheoremsConfig::kinds`] is the environment's name.
176///
177/// A kind declares its theorem class, its words, and whether each of its
178/// statements expects a proof.
179///
180/// The words are a [`PrefixWords`] value, the numbering feature's words
181/// written before a number: a base pair (the singular and the plural), which
182/// the heading and a plain `\ref` write, and named variants, each a pair,
183/// which a reference asks for by name (`\ref[abbreviated]{lem:x}`). The base
184/// pair of every shipped kind is the capitalized form (`Lemma`, `Lemmas`),
185/// and every shipped kind declares the variants [`LOWERCASE_VARIANT`],
186/// [`CAPITAL_VARIANT`] and [`ABBREVIATED_VARIANT`]. The words are FLM markup
187/// and hold no space before the number: the kind's counter style writes a
188/// non-breaking space after each ([`numbers`](super::numbers)). The base
189/// singular word is also the word a heading shows alone where the theorem
190/// has no number, and the display name the recomposed LaTeX gives the
191/// environment in its declaration (`Lemma` in `\newtheorem{lemma}{Lemma}`).
192///
193/// # Examples
194///
195/// ```
196/// use flm_core::stdlib::features::numbering::{PluralWords, PrefixWords};
197/// use flm_core::stdlib::features::theorems::TheoremKind;
198///
199/// // The two regular forms derived from one word, no abbreviation.
200/// let lemma = TheoremKind::from_word("theoremlike", "lemma");
201/// assert_eq!(lemma.words.base, PluralWords::new("Lemma", "Lemmas"));
202/// assert_eq!(lemma.words.variants["lowercase"], PluralWords::new("lemma", "lemmas"));
203/// assert!(!lemma.words.variants.contains_key("abbreviated"));
204///
205/// // Every form written out, with a variant of the host's own naming.
206/// let exercise = TheoremKind::new(
207///     "definitionlike",
208///     PrefixWords::new("Exercise", "Exercises")
209///         .with_variant("short", PluralWords::new("Ex.", "Exs.")),
210/// );
211/// assert!(!exercise.expects_proof);
212/// ```
213#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
214#[derive(schemars::JsonSchema)]
215#[serde(deny_unknown_fields)]
216pub struct TheoremKind {
217    /// The name of the kind's theorem class, a key of
218    /// [`TheoremsConfig::classes`].
219    pub class: Name,
220    /// The kind's words: the word written before the number, singular and
221    /// plural, with its named variants.
222    pub words: PrefixWords,
223    /// Whether each statement of this kind should have a proof that refers
224    /// back to it, unless the statement carries `\noproofref`. `false` unless
225    /// set. The feature's check reports a statement without such a proof
226    /// ([`check`](super::check)).
227    ///
228    /// A proof refers back to a statement through one of its labels, so a
229    /// kind that expects a proof must accept a label: it must be a kind of a
230    /// numbered class, under a configuration declaring at least one of the
231    /// [`label_types`](TheoremsConfig::label_types). A kind of an unnumbered
232    /// class accepts no label and could never be proved, so
233    /// [`TheoremsConfig::validate`] refuses such a configuration when the
234    /// registry is built.
235    pub expects_proof: bool,
236}
237
238impl TheoremKind {
239    /// A kind of the class `class` with the words `words`, expecting no
240    /// proof.
241    pub fn new(class: impl Into<Name>, words: PrefixWords) -> TheoremKind {
242        TheoremKind { class: class.into(), words, expects_proof: false }
243    }
244
245    /// A kind of the class `class`, expecting no proof, whose words are
246    /// derived from the single lowercase word `word`: the plural adds an `s`,
247    /// and the capitalized forms capitalize the first letter (`lemma`,
248    /// `lemmas`, `Lemma`, `Lemmas`). The capitalized pair is the base, and the
249    /// two pairs are the variants [`LOWERCASE_VARIANT`] and
250    /// [`CAPITAL_VARIANT`]. No [`ABBREVIATED_VARIANT`] is declared: to declare
251    /// an abbreviation, write the words out with [`TheoremKind::new`]. A
252    /// `\ref[abbreviated]{…}` to a kind made with this function is reported by
253    /// the references feature as an Error, because the kind does not declare
254    /// the variant.
255    pub fn from_word(class: impl Into<Name>, word: &str) -> TheoremKind {
256        let plural = format!("{word}s");
257        TheoremKind::new(class, regular(word, &plural))
258    }
259
260    /// Builder: whether each statement of this kind expects a proof.
261    pub fn expects_proof(mut self, expects_proof: bool) -> TheoremKind {
262        self.expects_proof = expects_proof;
263        self
264    }
265}
266
267/// `text` with its first letter capitalized.
268fn capitalized(text: &str) -> String {
269    let mut chars = text.chars();
270    match chars.next() {
271        Some(first) => first.to_uppercase().chain(chars).collect(),
272        None => String::new(),
273    }
274}
275
276/// The words of the lowercase pair `one`, `other`: the capitalized pair as
277/// the base, and the two pairs as the variants `lowercase` and `capital`.
278fn regular(one: &str, other: &str) -> PrefixWords {
279    let capital = PluralWords::new(capitalized(one), capitalized(other));
280    PrefixWords { base: capital.clone(), variants: BTreeMap::new() }
281        .with_variant(LOWERCASE_VARIANT, PluralWords::new(one, other))
282        .with_variant(CAPITAL_VARIANT, capital)
283}
284
285/// The configuration of the [`Theorems`](super::Theorems) feature: the
286/// theorem classes and the theorem kinds, the number format of every kind,
287/// and the label types every numbered kind accepts.
288///
289/// Every kind is an environment of its own name, `\begin{lemma}…\end{lemma}`,
290/// with no code written for it: a host adds `exercise` by declaring it here.
291///
292/// The default ([`TheoremsConfig::new`]) declares three classes and eight
293/// kinds:
294///
295/// | class | numbered | counter | closing mark | back-reference | kinds |
296/// |---|---|---|---|---|---|
297/// | `theoremlike` | yes | shared | none | no | `theorem`, `proposition`, `lemma`, `corollary`, `conjecture` |
298/// | `definitionlike` | yes | shared | none | no | `definition`, `remark` |
299/// | `prooflike` | no | — | `□` | yes | `proof` |
300///
301/// with the heading [`DEFAULT_HEADING`] for every class. `theorem`,
302/// `proposition`, `lemma` and `corollary` expect a proof; the others do not.
303/// [`simpleset`](TheoremsConfig::simpleset) and
304/// [`richset`](TheoremsConfig::richset) are two other complete sets a host
305/// may start from. A host edits any of them through the builders:
306///
307/// ```
308/// use flm_core::stdlib::features::numbering::{PluralWords, PrefixWords};
309/// use flm_core::stdlib::features::theorems::{TheoremKind, TheoremsConfig};
310///
311/// let config = TheoremsConfig::new()
312///     .kind(
313///         "exercise",
314///         TheoremKind::new(
315///             "definitionlike",
316///             PrefixWords::new("Exercise", "Exercises")
317///                 .with_variant("short", PluralWords::new("Ex.", "Exs.")),
318///         ),
319///     )
320///     .without_kind("conjecture");
321/// assert_eq!(config.kinds.len(), 8);
322/// assert!(config.validate().is_ok());
323/// ```
324///
325/// The value is what [`Theorems::new`](super::Theorems::new) takes, and a
326/// host passes it through
327/// [`StdlibConfig::theorems`](crate::stdlib::StdlibConfig::theorems). It is
328/// the feature's configuration, fixed when the registry is built (see
329/// [settings, options and
330/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
331/// because the environments are part of the language and the counters and
332/// counter styles the feature declares depend on it. For the same reason it
333/// enters the registry digest ([`digest_bytes`](TheoremsConfig::digest_bytes)).
334///
335/// The configuration is checked when the registry is built. The feature's
336/// registration fails, with a message that identifies the class or the kind,
337/// on what [`validate`](TheoremsConfig::validate) refuses: a kind whose class
338/// the configuration does not declare, a class or kind name that is not a
339/// valid environment name, or a kind that expects a proof but accepts no
340/// label. Once the language is built, the registry build also fails on a
341/// heading template that does not compile, a closing mark that does not
342/// parse and a word that does not parse. A kind whose environment name another
343/// feature already declares is reported as any clash of names in the
344/// registry is.
345#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
346#[derive(schemars::JsonSchema)]
347#[serde(default, deny_unknown_fields)]
348pub struct TheoremsConfig {
349    /// The theorem classes, by name.
350    pub classes: BTreeMap<Name, TheoremClass>,
351    /// The theorem kinds, by environment name.
352    pub kinds: BTreeMap<Name, TheoremKind>,
353    /// The number format every kind's number is written in, a number
354    /// template of the numbering feature, `#{arabic}` by default. To write
355    /// one kind's number otherwise, a host replaces that kind's counter style
356    /// (`flm.theorems.style.<kind>`, see [`numbers`](super::numbers)) by name
357    /// through the numbering feature's configuration.
358    pub number_format: NumberTemplate,
359    /// The label types that every numbered kind accepts on a `\label` written
360    /// on one of its theorems; [`DEFAULT_LABEL_TYPES`] by default. A theorem
361    /// of an unnumbered kind accepts no label.
362    pub label_types: Vec<String>,
363}
364
365impl Default for TheoremsConfig {
366    fn default() -> TheoremsConfig {
367        TheoremsConfig::new()
368    }
369}
370
371// The shipped classes and kinds, with the Python product's words. Every form of
372// a word is written out, the abbreviation included: an abbreviation derived from
373// the word (its first letters and a period) is wrong for many words.
374impl TheoremsConfig {
375    /// A configuration holding the three shipped classes and no kind.
376    fn with_shipped_classes() -> TheoremsConfig {
377        TheoremsConfig {
378            classes: BTreeMap::new(),
379            kinds: BTreeMap::new(),
380            number_format: NumberTemplate::formats("#{arabic}"),
381            label_types: DEFAULT_LABEL_TYPES.iter().map(|ty| ty.to_string()).collect(),
382        }
383        .class("theoremlike", TheoremClass::numbered())
384        .class("definitionlike", TheoremClass::numbered())
385        .class(
386            "prooflike",
387            TheoremClass::unnumbered()
388                .closing_mark(Some(DEFAULT_CLOSING_MARK.to_string()))
389                .relation_ref(true),
390        )
391    }
392
393    /// Builder: adds the shipped kind `name` of the class `class`, whose
394    /// lowercase words are `one`, `other` and whose abbreviated words are
395    /// `abbreviated`.
396    fn shipped(
397        self,
398        name: &str,
399        class: &str,
400        (one, other): (&str, &str),
401        abbreviated: (&str, &str),
402        expects_proof: bool,
403    ) -> TheoremsConfig {
404        let words = regular(one, other)
405            .with_variant(ABBREVIATED_VARIANT, PluralWords::new(abbreviated.0, abbreviated.1));
406        let kind = TheoremKind::new(class, words).expects_proof(expects_proof);
407        self.kind(name, kind)
408    }
409
410    /// The four theorem-like kinds every set holds.
411    fn statements(self) -> TheoremsConfig {
412        self.shipped("theorem", "theoremlike", ("theorem", "theorems"), ("Thm.", "Thms."), true)
413            .shipped(
414                "proposition",
415                "theoremlike",
416                ("proposition", "propositions"),
417                ("Prop.", "Props."),
418                true,
419            )
420            .shipped("lemma", "theoremlike", ("lemma", "lemmas"), ("Lem.", "Lems."), true)
421            .shipped(
422                "corollary",
423                "theoremlike",
424                ("corollary", "corollaries"),
425                ("Cor.", "Cors."),
426                true,
427            )
428    }
429
430    /// The kind `definition`.
431    fn definition(self) -> TheoremsConfig {
432        self.shipped(
433            "definition",
434            "definitionlike",
435            ("definition", "definitions"),
436            ("Def.", "Defs."),
437            false,
438        )
439    }
440
441    /// The kind `proof`.
442    fn proof(self) -> TheoremsConfig {
443        self.shipped("proof", "prooflike", ("proof", "proofs"), ("Proof", "Proofs"), false)
444    }
445
446    /// The default set of kinds, the set the Python implementation of FLM
447    /// calls `defaultset`: eight kinds in the three shipped classes,
448    /// `theorem`, `proposition`, `lemma`, `corollary`, `conjecture`,
449    /// `definition`, `remark` and `proof` ([`TheoremsConfig`] lists them by
450    /// class).
451    pub fn new() -> TheoremsConfig {
452        TheoremsConfig::with_shipped_classes()
453            .statements()
454            .shipped(
455                "conjecture",
456                "theoremlike",
457                ("conjecture", "conjectures"),
458                ("Conj.", "Conjs."),
459                false,
460            )
461            .definition()
462            .shipped("remark", "definitionlike", ("remark", "remarks"), ("Rem.", "Rems."), false)
463            .proof()
464    }
465
466    /// The smallest shipped set, the set the Python implementation of FLM
467    /// calls `simpleset`: six kinds, `theorem`, `proposition`, `lemma`,
468    /// `corollary`, `definition` and `proof`, in the three shipped classes.
469    pub fn simpleset() -> TheoremsConfig {
470        TheoremsConfig::with_shipped_classes().statements().definition().proof()
471    }
472
473    /// The largest shipped set, the set the Python implementation of FLM
474    /// calls `richset`: thirteen kinds, the eight of [`TheoremsConfig::new`],
475    /// and `idea`, `question`, `claim`, `observation` and `problem` in the
476    /// class `definitionlike`.
477    pub fn richset() -> TheoremsConfig {
478        let mut config = TheoremsConfig::new();
479        for (name, plural, abbreviated) in [
480            ("idea", "ideas", ("Idea", "Ideas")),
481            ("question", "questions", ("Qtn.", "Qtns.")),
482            ("claim", "claims", ("Clm.", "Clms.")),
483            ("observation", "observations", ("Obs.", "Obs.")),
484            ("problem", "problems", ("Prob.", "Probs.")),
485        ] {
486            config = config.shipped(name, "definitionlike", (name, plural), abbreviated, false);
487        }
488        config
489    }
490
491    /// A configuration declaring no class and no kind, with the default
492    /// number format and label types: the start of a configuration built
493    /// entirely by the builders.
494    pub fn empty() -> TheoremsConfig {
495        TheoremsConfig { classes: BTreeMap::new(), kinds: BTreeMap::new(), ..TheoremsConfig::new() }
496    }
497
498    /// Builder: declares the kind `name`, replacing the kind of that name if
499    /// there is one.
500    pub fn kind(mut self, name: impl Into<Name>, kind: TheoremKind) -> TheoremsConfig {
501        self.kinds.insert(name.into(), kind);
502        self
503    }
504
505    /// Builder: removes the kind `name`, if there is one.
506    pub fn without_kind(mut self, name: &str) -> TheoremsConfig {
507        self.kinds.remove(&Name::from(name));
508        self
509    }
510
511    /// Builder: declares the class `name`, replacing the class of that name
512    /// if there is one.
513    pub fn class(mut self, name: impl Into<Name>, class: TheoremClass) -> TheoremsConfig {
514        self.classes.insert(name.into(), class);
515        self
516    }
517
518    /// Builder: sets the number format of every kind.
519    pub fn number_format(mut self, number_format: NumberTemplate) -> TheoremsConfig {
520        self.number_format = number_format;
521        self
522    }
523
524    /// Builder: sets the label types that every numbered kind accepts.
525    pub fn label_types(
526        mut self,
527        label_types: impl IntoIterator<Item = impl Into<String>>,
528    ) -> TheoremsConfig {
529        self.label_types = label_types.into_iter().map(Into::into).collect();
530        self
531    }
532
533    /// The kind `name` and its class; `None` where the kind or its class is
534    /// not declared.
535    pub fn kind_and_class(&self, name: &str) -> Option<(&TheoremKind, &TheoremClass)> {
536        let kind = self.kinds.get(&Name::from(name))?;
537        Some((kind, self.classes.get(&kind.class)?))
538    }
539
540    /// Checks the parts of the configuration that can be checked before the
541    /// language is built. The feature calls it when it registers; a host may
542    /// call it earlier to report a mistake in its own terms.
543    ///
544    /// The texts (heading templates, closing marks, words) are compiled only
545    /// once the language is built, so a text that does not compile passes
546    /// this check and fails the registry build later.
547    ///
548    /// # Errors
549    ///
550    /// A sentence that describes the first problem found: a class or kind
551    /// name that is empty or holds whitespace, a brace, a backslash or a
552    /// comment character (`%`); a kind whose class is not declared; a kind
553    /// that [expects a proof](TheoremKind::expects_proof) but accepts no
554    /// label (a kind of an unnumbered class, or any kind under a
555    /// configuration declaring no [`label_types`](TheoremsConfig::label_types)),
556    /// which no proof could refer back to.
557    pub fn validate(&self) -> Result<(), String> {
558        let cannot_name = |text: &str| {
559            text.is_empty()
560                || text.chars().any(|ch| ch.is_whitespace() || matches!(ch, '{' | '}' | '\\' | '%'))
561        };
562        for name in self.classes.keys() {
563            if cannot_name(name.as_str()) {
564                return Err(format!(
565                    "the theorem class name `{name}` must not be empty or contain whitespace, \
566                     a brace, a backslash or `%`"
567                ));
568            }
569        }
570        for (name, kind) in &self.kinds {
571            if cannot_name(name.as_str()) {
572                return Err(format!(
573                    "the theorem kind name `{name}` must not be empty or contain whitespace, a \
574                     brace, a backslash or `%`, since it is the name of an environment"
575                ));
576            }
577            if !self.classes.contains_key(&kind.class) {
578                return Err(format!(
579                    "the theorem kind `{name}` belongs to the class `{}`, which the \
580                     configuration does not declare",
581                    kind.class
582                ));
583            }
584        }
585        // A proof refers back to a statement through a label; a kind that
586        // expects a proof and accepts none would draw the Warning at every
587        // statement.
588        for (name, kind) in self.kinds.iter().filter(|(_, kind)| kind.expects_proof) {
589            let numbered = self.classes.get(&kind.class).is_some_and(|class| class.numbered);
590            if !numbered {
591                return Err(format!(
592                    "the theorem kind `{name}` expects a proof, but its class `{}` is unnumbered \
593                     and accepts no label, so no proof can refer back to it",
594                    kind.class
595                ));
596            }
597            if self.label_types.is_empty() {
598                return Err(format!(
599                    "the theorem kind `{name}` expects a proof, but the configuration declares no \
600                     label types, so no proof can refer back to it"
601                ));
602            }
603        }
604        Ok(())
605    }
606
607    /// The configuration written out as bytes: what the feature feeds into
608    /// the registry digest, and what the `Hash` implementation hashes.
609    ///
610    /// Every class and every kind is written in the order of its name, with
611    /// every field of it, each text preceded by its length; then the number
612    /// format and the label types. Two configurations give the same bytes
613    /// exactly when they are equal. The code takes the fields apart by name,
614    /// so a field added to a type and not written here fails to compile.
615    pub fn digest_bytes(&self) -> Vec<u8> {
616        let TheoremsConfig { classes, kinds, number_format, label_types } = self;
617        let mut out = Vec::new();
618        push_len(&mut out, classes.len());
619        for (name, class) in classes {
620            let TheoremClass { numbered, shared_counter, heading, closing_mark, relation_ref } = class;
621            push_text(&mut out, name.as_str());
622            out.push(u8::from(*numbered));
623            out.push(u8::from(*shared_counter));
624            push_text(&mut out, heading);
625            match closing_mark {
626                Some(mark) => {
627                    out.push(1);
628                    push_text(&mut out, mark);
629                }
630                None => out.push(0),
631            }
632            out.push(u8::from(*relation_ref));
633        }
634        push_len(&mut out, kinds.len());
635        for (name, kind) in kinds {
636            let TheoremKind { class, words, expects_proof } = kind;
637            push_text(&mut out, name.as_str());
638            push_text(&mut out, class.as_str());
639            push_plural(&mut out, &words.base);
640            push_len(&mut out, words.variants.len());
641            for (variant, plural) in &words.variants {
642                push_text(&mut out, variant);
643                push_plural(&mut out, plural);
644            }
645            out.push(u8::from(*expects_proof));
646        }
647        match number_format {
648            NumberTemplate::Formats(text) => {
649                out.push(0);
650                push_text(&mut out, text);
651            }
652            NumberTemplate::Initial(text) => {
653                out.push(1);
654                push_text(&mut out, text);
655            }
656        }
657        push_len(&mut out, label_types.len());
658        for label_type in label_types {
659            push_text(&mut out, label_type);
660        }
661        out
662    }
663}
664
665/// Writes a count as eight little-endian bytes.
666fn push_len(out: &mut Vec<u8>, len: usize) {
667    out.extend_from_slice(&(len as u64).to_le_bytes());
668}
669
670/// Writes a text as its length and its bytes.
671fn push_text(out: &mut Vec<u8>, text: &str) {
672    push_len(out, text.len());
673    out.extend_from_slice(text.as_bytes());
674}
675
676/// Writes a pair of words.
677fn push_plural(out: &mut Vec<u8>, plural: &PluralWords) {
678    push_text(out, &plural.one);
679    push_text(out, &plural.other);
680}
681
682impl Hash for TheoremsConfig {
683    fn hash<H: Hasher>(&self, state: &mut H) {
684        state.write(&self.digest_bytes());
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691
692    #[test]
693    fn a_word_is_capitalized_by_its_first_letter() {
694        assert_eq!(capitalized("lemma"), "Lemma");
695        assert_eq!(capitalized("énoncé"), "Énoncé");
696        assert_eq!(capitalized(""), "");
697    }
698
699    #[test]
700    fn the_digest_bytes_change_with_every_field() {
701        let base = TheoremsConfig::new();
702        let changed = [
703            base.clone().without_kind("remark"),
704            base.clone().kind("remark", TheoremKind::from_word("definitionlike", "note")),
705            base.clone().kind(
706                "remark",
707                TheoremKind::from_word("definitionlike", "remark").expects_proof(true),
708            ),
709            base.clone().class("prooflike", TheoremClass::unnumbered()),
710            base.clone().class("theoremlike", TheoremClass::numbered().shared_counter(false)),
711            base.clone().class("theoremlike", TheoremClass::numbered().heading("#{name}")),
712            base.clone().class("theoremlike", TheoremClass::numbered().relation_ref(true)),
713            base.clone().class(
714                "theoremlike",
715                TheoremClass::numbered().closing_mark(Some(String::new())),
716            ),
717            base.clone().number_format(NumberTemplate::formats("#{roman}")),
718            base.clone().number_format(NumberTemplate::initial("#{arabic}")),
719            base.clone().label_types(["thm"]),
720        ];
721        for other in &changed {
722            assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
723        }
724        assert_eq!(TheoremsConfig::new().digest_bytes(), base.digest_bytes());
725    }
726}