Skip to main content

flm_core/stdlib/features/theorems/
latex.rs

1//! The lowering rules of the [`theorems`](super) feature for the
2//! `latex-recomposed` backend, and the definition pieces they require. The
3//! rendering guide describes this output for users under [Theorems in the
4//! recomposed LaTeX](crate::guide::rendering#theorems-in-the-recomposed-latex).
5//!
6//! The theorem's rule ([`TheoremLatexRule`], [`THEOREM_LATEX_RULE`]) writes a
7//! theorem back as the environment the author wrote, and writes into the
8//! style file the declarations that define that environment for LaTeX. LaTeX
9//! then sets the theorem's heading (the kind's word, the number and the
10//! title) and a proof's closing mark; the class's heading template is not
11//! used on this backend. A proof's back-reference is written in one of two
12//! forms, which the backend's render option
13//! [`resolved_proof_refs`](LatexRecomposedRenderOptions::resolved_proof_refs)
14//! chooses:
15//!
16//! - the **authored form** (the default): the back-reference is written as
17//!   the author wrote it, for the `phfthm` LaTeX package to read;
18//! - the **resolved form**: the back-reference is written as the proof's
19//!   title, a reference to the statement, and the recomposed LaTeX needs the
20//!   `amsthm` package alone.
21//!
22//! | written | LaTeX, the authored form (the default) | LaTeX, the resolved form |
23//! |---|---|---|
24//! | `\begin{theorem}[My Theorem]\label{thm:a}…\end{theorem}` | `\begin{theorem}[My Theorem]\flmLabels{\label{ref1}}…\end{theorem}` | the same |
25//! | `\begin{proof}[Sketch]…\end{proof}` | `\begin{proof}[{\flmProofTitle{Sketch}}]…\end{proof}` | the same |
26//! | `\begin{proof}[*thm:a]…\end{proof}` | `\begin{proof}[*ref1]…\end{proof}` | `\begin{proof}[{\flmProofTitle{\flmRef{ref1}}}]…\end{proof}` |
27//! | `\begin{proof}[**thm:a]…\end{proof}` | `\begin{proof}[**ref1]…\end{proof}` | `\begin{proof}…\end{proof}` |
28//! | `\begin{lemma}\noproofref…\end{lemma}` | `\begin{lemma}\noproofref…\end{lemma}` | the same |
29//!
30//! The rules use the LaTeX family's vocabulary: a **LaTeX hook** is a macro
31//! that the recomposed LaTeX writes and the style file defines with a plain
32//! default, which a user redefines in the document's preamble
33//! ([`preamble`]; the rendering
34//! guide lists the hooks under [the LaTeX
35//! hooks](crate::guide::rendering#the-latex-hooks)); a **definition
36//! piece** is a unit of LaTeX definitions that a rule requires by identifier
37//! and the style file holds ([`LatexPreambleDef`]); a **package request** is
38//! a LaTeX package that a rule or a definition piece requires by identifier
39//! ([`packages`]); and a **safe
40//! label** is the key the recomposed LaTeX writes for an FLM label (`ref1`,
41//! `ref2`, …; [`SafeLabels`]).
42//!
43//! # A theorem
44//!
45//! [`TheoremLatexRule`] writes a theorem as the environment of its kind's
46//! name. Its title, where it has one, is the environment's optional argument,
47//! lowered through the ordinary rules; the backend writes it as `[My
48//! Theorem]`, or as `[{…}]` as soon as it holds a command. Right after the
49//! begin line come the theorem's labels, each under its safe label, inside
50//! the labels hook `\flmLabels`, as every group of labels is written
51//! ([`stage_label`](crate::stdlib::features::refs::stage_label),
52//! [`stage_label_group`](crate::stdlib::features::refs::stage_label_group));
53//! then `\noproofref` where the author wrote it; then the body.
54//!
55//! **A proof's title** (the title of a kind whose class reads
56//! back-references, [`relation_ref`](super::TheoremClass::relation_ref)) is
57//! written inside the proof title hook, `[{\flmProofTitle{Sketch}}]`
58//! ([`PROOF_TITLE_COMMAND`]). The definition piece of the chosen form
59//! defines the hook with the default that the form's package needs: in the
60//! authored form the title alone, which `phfthm` sets as "Proof of Sketch"
61//! ([`authored_piece`]); in the resolved form "Proof (Sketch)", which
62//! `amsthm` sets as the whole heading, as FLM's other outputs show a proof's
63//! title ([`resolved_piece`]). An author redefines the hook to show a proof's
64//! title otherwise. A title that begins with a star on a proof but is not a
65//! well-formed back-reference is written in the hook as every title is; the
66//! feature's check reports it.
67//!
68//! **`\noproofref`** says that no proof of the statement is coming. It is
69//! written as the author wrote it in both forms, because LaTeX has a use for
70//! it: a statement's environment can print where its proof is ("proof on page
71//! 12"), and needs to know which statements have none. `phfthm` defines the
72//! command; the feature's definition piece ([`definition_piece`]) defines it
73//! as a command that does nothing, with `\ProvideDocumentCommand`, so that
74//! the definition of a package loaded first is kept.
75//!
76//! # A proof's back-reference
77//!
78//! The statement a proof refers to (`[*thm:a]`, `[**thm:a]`) is written under
79//! the safe label of its label, read through
80//! [`target_spelling`], the
81//! function through which every reference site's target is read. A proof
82//! inside a synthesized value that a rule splices at lowering (the use site of
83//! a kept definition: a user definition whose use sites a plan leaves in the
84//! tree; see [kept definitions](crate::stdlib::features::userdefs::kept)) is
85//! therefore written under the value names of that value (`ref-v1`, …;
86//! [`SafeLabels`]). A back-reference whose label a template's placeholder
87//! completes cannot be written in the template of a kept definition:
88//! the rule returns [`LowerError::PlaceholderCharacters`], and each use site
89//! of the definition is expanded instead.
90//!
91//! - **The authored form** (render option off, the default). The rule writes
92//!   the back-reference as the author wrote it, `[*ref1]` or `[**ref1]`, and
93//!   the authored form's definition piece ([`authored_piece`]) requests the `phfthm`
94//!   package ([`packages::PHFTHM`]). The package reads that syntax in a
95//!   proof's optional argument: `[*ref1]` sets the heading "Proof of
96//!   Theorem 1" where the document loads `hyperref` and "Proof of 1" where it
97//!   does not (the package refers to the statement through `hyperref`'s
98//!   `\autoref`, or through `\ref`), and `[**ref1]` sets "Proof". The rule
99//!   does not request `hyperref`: whether a document loads it is its author's
100//!   decision. The package reads any other optional argument as the thing
101//!   the proof proves and writes "Proof of" before it.
102//! - **The resolved form** (render option on). The resolved form's
103//!   definition piece ([`resolved_piece`]) requests `amsthm` alone ([`packages::AMSTHM`]). A
104//!   back-reference that the proof shows is written as a title is, inside the
105//!   proof title hook, the title being the reference hook `\flmRef` around
106//!   the statement's safe label: `[{\flmProofTitle{\flmRef{ref1}}}]`, which
107//!   sets "Proof (theorem 1)" by default. With the render option
108//!   [`label_hooks`](LatexRecomposedRenderOptions::label_hooks) off, the
109//!   reference is `\zcref{ref1}`, the command the hook runs by default. A
110//!   back-reference that is recorded and not shown writes no optional
111//!   argument, and the proof's heading is LaTeX's own, "Proof".
112//!
113//! # The declarations in the style file
114//!
115//! LaTeX must know every theorem kind the document uses, so the rule writes
116//! a declaration of the kind into the style file, in the block of the
117//! definitions a feature writes from its configuration
118//! ([`style`](crate::stdlib::backends::latex::style)). The kind's display
119//! name is its base singular word (`Lemma`), which is FLM text, so the
120//! declaration is lowered through the rules at the theorem. It is staged
121//! (built into the lowered tree; see [`Lowerer`]) as the LaTeX family's
122//! definition construct with the kind
123//! [`LatexDefinitionKind::Declaration`], which the style file writes once per
124//! name, guarded on the name it declares: `\ifcsname lemma\endcsname\else …
125//! \fi`. A kind that the document class, a package or the author's own
126//! preamble defines before the style file is loaded is therefore kept, and
127//! the declaration does nothing; an author with a setup of their own defines
128//! their kinds first. The style file declares only the kinds the document
129//! uses.
130//!
131//! | the declaration | the authored form | the resolved form |
132//! |---|---|---|
133//! | the theorem style of a numbered kind's class | `\newtheoremstyle{theoremlike}{}{}{\itshape}{}{\bfseries}{.}{5pt plus 1pt minus 1pt}{}` | the same |
134//! | the shared counter, before the first kind counting in it | none: `phfthm`'s own counter `phfthmcounter` | `\newcounter{flmtheorem}`, guarded on `c@flmtheorem` |
135//! | a numbered kind counting in the shared counter | `\phfMakeTheorem[thmstyle=theoremlike,counter=phfthmcounter]{lemma}{Lemma}\expandafter\providecommand\csname phfthm@lemmaautorefname\endcsname{Lemma}` | `\edef\flm@thm@style{\the\thm@style}\theoremstyle{theoremlike}\newtheorem{lemma}[flmtheorem]{Lemma}\thm@style\expandafter{\flm@thm@style}` |
136//! | a numbered kind with a counter of its own, expecting no proof | `\phfMakeTheorem[thmstyle=exerciselike,proofref=false]{exercise}{Exercise}` | `\edef\flm@thm@style{\the\thm@style}\theoremstyle{exerciselike}\newtheorem{exercise}{Exercise}\thm@style\expandafter{\flm@thm@style}` |
137//! | an unnumbered kind | `\phfMakeProofEnv[defaultproofname={Proof}]{proof}` | `\newenvironment{proof}[1][{Proof}]{\begin{proof}[{#1}]}{\end{proof}}` |
138//!
139//! - **Theorem styles.** A numbered kind is set in the `amsthm` theorem style
140//!   named after its class. Before the first kind of a class, the style file
141//!   declares that style with the parameters of `amsthm`'s `plain` style (a
142//!   bold heading and an italic body), guarded on the control sequence
143//!   `amsthm` creates for a style (`\th@theoremlike`). A style of that name
144//!   declared first is kept: the feature's definition piece
145//!   ([`definition_piece`]) declares the shipped class `definitionlike` in
146//!   `amsthm`'s `definition` style (an upright body), and an author sets a
147//!   class otherwise by declaring a style of the class's name before loading
148//!   the style file.
149//! - **What `phfthm` provides, in the authored form.** `\phfMakeTheorem`
150//!   declares a numbered theorem environment in a given theorem style
151//!   (`thmstyle`) and counter (`counter`); with `proofref=false`, which the
152//!   rule writes for a kind that expects no proof, the package looks for no
153//!   proof of its statements. `\phfMakeProofEnv` declares a proof environment
154//!   with a default heading word (`defaultproofname`). The kinds that share
155//!   the counter count in the package's own counter, `phfthmcounter`
156//!   ([`PHFTHM_SHARED_COUNTER`]). The style file requests the package with
157//!   the option `thmset=empty` ([`packages::PHFTHM`]), so that the package
158//!   declares no environment of its own and the configuration is the only
159//!   source of the kinds declared; an author who loads the package before the
160//!   style file gives it the same option. Under the LaTeX kernel's first aid
161//!   for `amsthm` (from TeX Live 2026), the environment of a kind in the
162//!   shared counter steps `phfthm@<kind>`, an alias counter that the first
163//!   aid makes, and `hyperref`'s `\autoref` names a reference by that counter:
164//!   the declaration provides that name, `\phfthm@lemmaautorefname`, the
165//!   kind's word, where nothing defined it.
166//! - **What the resolved form declares.** The shared counter is a LaTeX
167//!   counter of the feature's own, `flmtheorem` ([`SHARED_LATEX_COUNTER`]),
168//!   declared once, guarded on its register, before the first kind counting
169//!   in it; every such kind is declared over it with `amsthm`'s
170//!   `\newtheorem`. A kind with a counter of its own counts in the counter of
171//!   its own name. A numbered kind's declaration sets its class's theorem
172//!   style with `\theoremstyle` and restores the style in effect before it,
173//!   which `amsthm` holds in `\thm@style`, so that what follows the style file
174//!   keeps that style. An unnumbered kind is `amsthm`'s `proof`, which the
175//!   package defines, or an environment over it.
176//! - **Reference types.** Every numbered kind's declaration also makes the
177//!   kind a reference type of its own for the `zref-clever` package, with the
178//!   kind's words, and maps the counter its environment steps to that type,
179//!   so that a reference to a lemma
180//!   counting in the shared counter prints "lemma".
181//!
182//! # Limitation: theorems numbered within sections
183//!
184//! The declarations do not yet write the counter's hierarchy: a document that
185//! numbers theorems within sections still gets, from LaTeX, one sequence of
186//! numbers for the kinds, regardless of the document's numbering options.
187//! Writing the hierarchy into the declarations is designed and not yet
188//! implemented.
189
190use std::sync::Arc;
191
192use techy::core::node::{BuildId, NodeRef};
193
194use crate::core::lowering::{
195    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
196};
197use crate::core::registry::{BuildError, FeatureBuilder};
198use crate::lang::Flm;
199use crate::model::element::element_value;
200use crate::model::names::{ElementName, Name};
201use crate::stdlib::backends::latex::construct::{
202    ARG_SLOT, DEFINITION, ENVIRONMENT as ENVIRONMENT_CONSTRUCT, MACRO, RAW,
203};
204use crate::stdlib::backends::latex::{
205    LatexArgShape, LatexDefinitionKind, LatexDefinitionPayload, LatexEnvironmentPayload,
206    LatexMacroPayload, LatexPreambleDef, LatexRawPayload, packages, preamble,
207};
208use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
209use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
210use crate::stdlib::backends::pres::BODY_SLOT;
211use crate::stdlib::features::refs::{
212    self, SAFE_LABELS, SafeLabels, VALUE_SAFE_LABELS, ValueSafeLabels, ZCREF_COMMAND,
213    stage_spelling, target_spelling,
214};
215
216use super::FEATURE;
217use super::elements::{THEOREM, TITLE_ARG, TheoremElement, TitleReading, has_noproofref, title_reading};
218use super::heading::{Headings, NAME_ELEMENT, RELATION, TITLE_POINTER};
219
220/// The name of the theorem's rule on the `latex-recomposed` backend,
221/// `flm.theorems.theorem.lower.latex-recomposed` ([`TheoremLatexRule`]).
222pub const THEOREM_LATEX_RULE: &str = "flm.theorems.theorem.lower.latex-recomposed";
223
224/// The name of the rule of a heading's name node ([`NAME_ELEMENT`]) on the
225/// `latex-recomposed` backend, `flm.theorems.name.lower.latex-recomposed`:
226/// it lowers the node's own body, the kind's word. The recomposed LaTeX
227/// instantiates no heading template, because LaTeX writes a theorem's
228/// heading, so this node, like the title pointer and the back-reference,
229/// never reaches the backend. The three rules exist because a plan checks
230/// that its backend can lower every element a document may hold.
231pub const NAME_LATEX_RULE: &str = "flm.theorems.name.lower.latex-recomposed";
232
233/// The name of the rule of a heading's title pointer ([`TITLE_POINTER`]) on
234/// the `latex-recomposed` backend,
235/// `flm.theorems.title-pointer.lower.latex-recomposed`: it lowers the node's
236/// own body; the node never reaches this backend (see [`NAME_LATEX_RULE`]).
237pub const TITLE_POINTER_LATEX_RULE: &str = "flm.theorems.title-pointer.lower.latex-recomposed";
238
239/// The name of the rule of a heading's back-reference node ([`RELATION`]) on
240/// the `latex-recomposed` backend,
241/// `flm.theorems.relation.lower.latex-recomposed`: it lowers the node's own
242/// body; the node never reaches this backend (see [`NAME_LATEX_RULE`]).
243pub const RELATION_LATEX_RULE: &str = "flm.theorems.relation.lower.latex-recomposed";
244
245/// The command that marks a statement as having no proof, `noproofref`:
246/// written as the author wrote it, and defined by the feature's definition
247/// piece ([`definition_piece`]) where no package defined it first.
248pub const NOPROOFREF_COMMAND: &str = "noproofref";
249
250/// The proof title hook, `flmProofTitle`, a LaTeX hook: a proof's title (a
251/// title the author wrote, or, in the resolved form, the reference hook
252/// around the statement the proof refers back to) is written as its argument
253/// inside the proof environment's optional argument,
254/// `\begin{proof}[{\flmProofTitle{Sketch}}]`. The definition piece of the
255/// form that the render option chooses defines it, with that form's default
256/// ([`authored_piece`], [`resolved_piece`]).
257pub const PROOF_TITLE_COMMAND: &str = "flmProofTitle";
258
259/// The name of the feature's definition piece, `theorems`; its identifier is
260/// `flm.latex.def.theorems` ([`PIECE`]).
261pub const PIECE_NAME: &str = "theorems";
262
263/// The identifier of the feature's definition piece, `flm.latex.def.theorems`
264/// ([`definition_piece`]).
265pub const PIECE: &str = "flm.latex.def.theorems";
266
267/// The name of the authored form's definition piece, `theorems.authored`; its
268/// identifier is `flm.latex.def.theorems.authored` ([`AUTHORED_PIECE`]).
269pub const AUTHORED_PIECE_NAME: &str = "theorems.authored";
270
271/// The identifier of the authored form's definition piece,
272/// `flm.latex.def.theorems.authored` ([`authored_piece`]).
273pub const AUTHORED_PIECE: &str = "flm.latex.def.theorems.authored";
274
275/// The name of the resolved form's definition piece, `theorems.resolved`; its
276/// identifier is `flm.latex.def.theorems.resolved` ([`RESOLVED_PIECE`]).
277pub const RESOLVED_PIECE_NAME: &str = "theorems.resolved";
278
279/// The identifier of the resolved form's definition piece,
280/// `flm.latex.def.theorems.resolved` ([`resolved_piece`]).
281pub const RESOLVED_PIECE: &str = "flm.latex.def.theorems.resolved";
282
283/// The counter that the `phfthm` package defines when it is loaded, and in
284/// which it numbers its own theorem environments, `phfthmcounter`. In the
285/// authored form, every kind of a class that counts in the shared counter is
286/// declared over it.
287pub const PHFTHM_SHARED_COUNTER: &str = "phfthmcounter";
288
289/// The LaTeX counter that holds the feature's shared counter in the resolved
290/// form, `flmtheorem`. The style file declares it once, guarded on its
291/// register (`\ifcsname c@flmtheorem\endcsname\else\newcounter{flmtheorem}\fi`),
292/// and declares every kind of a class that counts in the shared counter over
293/// it, `\newtheorem{lemma}[flmtheorem]{Lemma}`. Its name differs from every
294/// kind's, so that it is never the counter of a kind with a counter of its
295/// own (which counts in the counter of its own name), and so that an author
296/// can number theorems within another counter by giving its name
297/// (`\numberwithin{flmtheorem}{section}`).
298pub const SHARED_LATEX_COUNTER: &str = "flmtheorem";
299
300/// The feature's definition piece, `flm.latex.def.theorems` ([`PIECE`]),
301/// required at every theorem in both forms, beside the definition piece of
302/// the chosen form ([`authored_piece`], [`resolved_piece`]). It defines:
303///
304/// - `\noproofref`, which says that no proof of a statement is coming, as a
305///   command that does nothing, with `\ProvideDocumentCommand`, so that where
306///   a package defines it first (the `phfthm` package among them), the
307///   package's definition is kept. Redefine it, before loading the style file
308///   or after it, to act on statements that have no proof.
309/// - The theorem style of the shipped class `definitionlike`, declared as
310///   `amsthm`'s `definition` style (an upright body), guarded on the control
311///   sequence `amsthm` creates for it, `\th@definitionlike`. Every class's
312///   kinds are set in the theorem style named after the class, and a class
313///   whose style nobody declared gets the `plain` style (see [the declarations
314///   in the style file](self#the-declarations-in-the-style-file)); this
315///   definition piece, which the style file writes before those declarations, gives the
316///   shipped class its own style. Declare a style of the class's name before
317///   the style file is loaded to set its kinds your own way.
318///
319/// The definition piece uses `amsthm`'s `\newtheoremstyle`; the package that each form
320/// requests loads `amsthm`.
321pub fn definition_piece() -> LatexPreambleDef {
322    LatexPreambleDef::new(
323        PIECE_NAME,
324        "\
325% Theorems. \\noproofref, written after a statement's labels, says that no proof
326% of the statement is coming; defined here as nothing where no package (phfthm)
327% defined it first.
328\\ProvideDocumentCommand\\noproofref{}{}
329% The kinds of a class are set in the theorem style of the class's name. The
330% shipped class definitionlike is set in amsthm's definition style (upright);
331% declare a theorem style of that name before loading this file to change it.
332\\ifcsname th@definitionlike\\endcsname\\else\\newtheoremstyle{definitionlike}{}{}{\\normalfont}{}{\\bfseries}{.}{5pt plus 1pt minus 1pt}{}\\fi
333",
334        "`\\noproofref`: a statement with no proof coming, defined as nothing where no package \
335         defined it; the theorem style of the shipped class `definitionlike`",
336    )
337}
338
339/// The authored form's definition piece, `flm.latex.def.theorems.authored`
340/// ([`AUTHORED_PIECE`]), required at every theorem when the render option
341/// [`resolved_proof_refs`](LatexRecomposedRenderOptions::resolved_proof_refs)
342/// is off. It requests the `phfthm` package ([`packages::PHFTHM`]).
343///
344/// It defines the proof title hook `\flmProofTitle{<title>}`
345/// ([`PROOF_TITLE_COMMAND`]), what a proof's heading shows for a title the
346/// author wrote, as the title alone, `#1`: `phfthm` reads a proof's optional
347/// argument as the thing the proof proves and writes the rest of the heading
348/// itself, so that `\begin{proof}[{\flmProofTitle{Sketch}}]` sets "Proof of
349/// Sketch". The hook is defined with `\ProvideDocumentCommand`, so that a
350/// definition made before the style file is loaded is kept; redefine it,
351/// before loading the style file or after it, to show a proof's title your
352/// own way. A document that lists `phfthm` in the render option
353/// [`skip_packages`](LatexRecomposedRenderOptions::skip_packages) keeps this
354/// default, `#1`: the author who provides the proof environment also
355/// provides the heading's wording, and redefines the hook where that
356/// environment reads its optional argument otherwise. The resolved form's
357/// definition piece ([`resolved_piece`]) defines the same hook with the default its
358/// package needs; a style file holds one of the two.
359pub fn authored_piece() -> LatexPreambleDef {
360    LatexPreambleDef::new(
361        AUTHORED_PIECE_NAME,
362        "\
363% \\flmProofTitle{<title>}: what a proof's heading sets for a title the document
364% wrote, which is written as its argument inside the proof environment's
365% optional argument. phfthm reads that argument as the thing the proof proves
366% and words the heading itself (Proof of <title>), so by default the title
367% alone. Redefine \\flmProofTitle to set a proof's title differently.
368\\ProvideDocumentCommand\\flmProofTitle{m}{#1}
369",
370        "`\\flmProofTitle`, the LaTeX hook of a proof's title, setting the title alone, which \
371         `phfthm` words as the thing the proof proves",
372    )
373    .requires([packages::PHFTHM])
374}
375
376/// The resolved form's definition piece, `flm.latex.def.theorems.resolved`
377/// ([`RESOLVED_PIECE`]), required at every theorem when the render option
378/// [`resolved_proof_refs`](LatexRecomposedRenderOptions::resolved_proof_refs)
379/// is on. It requests the `amsthm` package alone ([`packages::AMSTHM`]).
380///
381/// It defines the proof title hook `\flmProofTitle{<title>}`
382/// ([`PROOF_TITLE_COMMAND`]), what a proof's heading shows for a title (one
383/// the author wrote, or the reference hook around the statement the proof
384/// refers back to), as `\proofname\space (#1)`: `amsthm` sets a proof's
385/// optional argument as the whole heading, so that
386/// `\begin{proof}[{\flmProofTitle{Sketch}}]` sets "Proof (Sketch)", as FLM's
387/// other outputs show a proof's title; `\proofname` is the word `amsthm`
388/// defines. The hook is defined with `\ProvideDocumentCommand`, so that a
389/// definition made before the style file is loaded is kept; redefine it,
390/// before loading the style file or after it, to show a proof's title your
391/// own way (`\renewcommand\flmProofTitle[1]{#1}` shows the title alone). The
392/// authored form's definition piece ([`authored_piece`]) defines the same hook with the
393/// default its package needs; a style file holds one of the two.
394pub fn resolved_piece() -> LatexPreambleDef {
395    LatexPreambleDef::new(
396        RESOLVED_PIECE_NAME,
397        "\
398% \\flmProofTitle{<title>}: what a proof's heading sets for a title -- one the
399% document wrote, or the statement the proof refers back to -- which is written
400% as its argument inside the proof environment's optional argument, the whole
401% heading amsthm sets. By default Proof (<title>), \\proofname being the word
402% amsthm defines. Redefine \\flmProofTitle to set a proof's title differently;
403% \\renewcommand\\flmProofTitle[1]{#1} sets the title alone.
404\\ProvideDocumentCommand\\flmProofTitle{m}{\\proofname\\space (#1)}
405",
406        "`\\flmProofTitle`, the LaTeX hook of a proof's title, setting `Proof (<title>)` as the \
407         whole heading `amsthm` sets",
408    )
409    .requires([packages::AMSTHM])
410}
411
412/// Stages the reference hook around the safe label `key`, `\flmRef{<key>}`,
413/// or, with the render option
414/// [`label_hooks`](LatexRecomposedRenderOptions::label_hooks) off, the
415/// command that the hook runs by default, `\zcref{<key>}`; and requires what
416/// defines it, as the references feature does for a `\ref`.
417fn reference_hook(
418    cx: &mut LowerCx<'_>,
419    lw: &mut dyn Lowerer,
420    key: Vec<BuildId>,
421) -> Result<BuildId, LowerError> {
422    let command = if lw.option::<LatexRecomposedRenderOptions>()?.label_hooks {
423        lw.require(&Name::from(preamble::REFS));
424        preamble::REF_COMMAND
425    } else {
426        lw.require(&Name::from(packages::ZREF_CLEVER));
427        ZCREF_COMMAND
428    };
429    lw.pres_slots_with(
430        cx,
431        &ElementName::from(MACRO),
432        LatexMacroPayload::new(command, [LatexArgShape::Mandatory]),
433        vec![(String::from(ARG_SLOT), key)],
434    )
435}
436
437/// Stages the proof title hook around `title`, `\flmProofTitle{<title>}`.
438fn proof_title(
439    cx: &mut LowerCx<'_>,
440    lw: &mut dyn Lowerer,
441    title: Vec<BuildId>,
442) -> Result<BuildId, LowerError> {
443    command(cx, lw, PROOF_TITLE_COMMAND, vec![LatexArgShape::Mandatory], vec![title])
444}
445
446/// The lowering rule [`THEOREM_LATEX_RULE`], the default on the
447/// `latex-recomposed` backend: the environment of the kind's name around the
448/// title, the labels, `\noproofref` and the body, preceded by the
449/// declarations the style file needs for the kind. See the [module
450/// documentation](self).
451#[derive(Debug)]
452pub struct TheoremLatexRule {
453    headings: Arc<Headings>,
454}
455
456impl TheoremLatexRule {
457    /// The optional argument of the theorem `node` of the kind `value`: the
458    /// title lowered through the rules, a back-reference in the form
459    /// `resolved` chooses, or `None` where no title is written.
460    fn title(
461        &self,
462        node: &NodeRef<'_, Flm>,
463        value: &TheoremElement,
464        resolved: bool,
465        cx: &mut LowerCx<'_>,
466        lw: &mut dyn Lowerer,
467    ) -> Result<Option<Vec<BuildId>>, LowerError> {
468        match title_reading(node).unwrap_or(TitleReading::Absent) {
469            TitleReading::Absent => Ok(None),
470            // A malformed back-reference is reported by the `check` workflow
471            // and written as the author wrote it: a title, as every output
472            // shows it.
473            TitleReading::Title | TitleReading::Malformed => {
474                let title = lower_arg_named_or_nothing(cx, lw, node, TITLE_ARG)?;
475                if value.class.relation_ref {
476                    Ok(Some(vec![proof_title(cx, lw, title)?]))
477                } else {
478                    Ok(Some(title))
479                }
480            }
481            // A kept template's title whose characters a call supplies: the
482            // use sites are expanded, and each is lowered with its own.
483            TitleReading::Unknown => Err(LowerError::PlaceholderCharacters),
484            TitleReading::Relation { text, label, shown } if !resolved => {
485                let stars = if shown { "*" } else { "**" };
486                let mut title = vec![raw(cx, lw, stars)?];
487                let spelling = target_spelling(lw, &text, Some(&label))?;
488                title.extend(stage_spelling(cx, lw, &spelling)?);
489                Ok(Some(title))
490            }
491            // The resolved form: the reference hook inside the proof title
492            // hook where the back-reference is shown; LaTeX's own heading
493            // where it is recorded only.
494            TitleReading::Relation { text, label, shown } => {
495                if !shown {
496                    return Ok(None);
497                }
498                let spelling = target_spelling(lw, &text, Some(&label))?;
499                let key = stage_spelling(cx, lw, &spelling)?;
500                let reference = reference_hook(cx, lw, key)?;
501                Ok(Some(vec![proof_title(cx, lw, vec![reference])?]))
502            }
503        }
504    }
505}
506
507impl Lower for TheoremLatexRule {
508    fn lower(
509        &self,
510        node: NodeRef<'_, Flm>,
511        cx: &mut LowerCx<'_>,
512        lw: &mut dyn Lowerer,
513    ) -> Result<Lowering, LowerError> {
514        let value = element_value::<TheoremElement>(&node)
515            .ok_or_else(|| LowerError::structure("a theorem without its element's data"))?;
516        let resolved = lw.option::<LatexRecomposedRenderOptions>()?.resolved_proof_refs;
517        lw.require(&Name::from(PIECE));
518        lw.require(&Name::from(if resolved { RESOLVED_PIECE } else { AUTHORED_PIECE }));
519        let declarations = self.declarations(value, resolved, cx, lw)?;
520        let mut shapes = Vec::new();
521        let mut slots = Vec::new();
522        if let Some(title) = self.title(&node, value, resolved, cx, lw)? {
523            shapes.push(LatexArgShape::Optional);
524            slots.push((String::from(ARG_SLOT), title));
525        }
526        let mut labels = Vec::new();
527        for written in refs::label_uses(&node) {
528            labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
529        }
530        let mut body = refs::stage_label_group(cx, lw, labels, false)?;
531        if has_noproofref(&node) {
532            body.push(lw.pres_slots_with(
533                cx,
534                &ElementName::from(MACRO),
535                LatexMacroPayload::new(NOPROOFREF_COMMAND, []),
536                Vec::new(),
537            )?);
538        }
539        body.extend(lw.lower_body(cx, &node)?);
540        slots.push((String::from(BODY_SLOT), body));
541        let environment = lw.pres_slots_with(
542            cx,
543            &ElementName::from(ENVIRONMENT_CONSTRUCT),
544            LatexEnvironmentPayload::new(value.name.as_str(), shapes),
545            slots,
546        )?;
547        let mut staged = declarations;
548        staged.push(environment);
549        Ok(Lowering::Emit(staged))
550    }
551}
552
553/// The parameters of `amsthm`'s `\newtheoremstyle` after the style's name
554/// that give the `plain` style — a bold heading followed by a full stop, an
555/// italic body, `amsthm`'s own spacing — which a class's theorem style is
556/// declared with where nothing declared it first.
557const PLAIN_STYLE_PARAMETERS: &str = "{}{}{\\itshape}{}{\\bfseries}{.}{5pt plus 1pt minus 1pt}{}";
558
559/// Stages a raw node (`flm.pres.latex.raw`) holding the LaTeX text `text`,
560/// written byte for byte.
561fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
562    lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
563}
564
565/// Stages `\<command>` with arguments of the shapes `shapes`, each slot's
566/// content given in order.
567fn command(
568    cx: &mut LowerCx<'_>,
569    lw: &mut dyn Lowerer,
570    name: &str,
571    shapes: Vec<LatexArgShape>,
572    slots: Vec<Vec<BuildId>>,
573) -> Result<BuildId, LowerError> {
574    lw.pres_slots_with(
575        cx,
576        &ElementName::from(MACRO),
577        LatexMacroPayload::new(name, shapes),
578        slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
579    )
580}
581
582/// Stages a declaration of this feature for the style file, guarded on the
583/// control sequence `guard`, whose text is `body`.
584fn declaration(
585    cx: &mut LowerCx<'_>,
586    lw: &mut dyn Lowerer,
587    guard: &str,
588    body: Vec<BuildId>,
589) -> Result<BuildId, LowerError> {
590    let payload =
591        LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, guard, 0).of_feature(FEATURE);
592    lw.pres_slots_with(
593        cx,
594        &ElementName::from(DEFINITION),
595        payload,
596        vec![(String::from(BODY_SLOT), body)],
597    )
598}
599
600impl TheoremLatexRule {
601    /// The declarations that the theorem of the kind `value` needs in the
602    /// style file, in the form `resolved` chooses: its kind's, preceded, in
603    /// the resolved form and for a kind that counts in the shared counter, by
604    /// the declaration of the LaTeX counter it is declared over. Each is
605    /// guarded on its name, and the style file holds each once.
606    fn declarations(
607        &self,
608        value: &TheoremElement,
609        resolved: bool,
610        cx: &mut LowerCx<'_>,
611        lw: &mut dyn Lowerer,
612    ) -> Result<Vec<BuildId>, LowerError> {
613        let mut staged = Vec::new();
614        let shared = value.counter.is_some() && value.class.shared_counter;
615        if resolved && shared {
616            // The shared counter's LaTeX counter, declared once, guarded on
617            // its register, before the first kind counting in it.
618            let body = vec![raw(cx, lw, &format!("\\newcounter{{{SHARED_LATEX_COUNTER}}}"))?];
619            staged.push(declaration(cx, lw, &format!("c@{SHARED_LATEX_COUNTER}"), body)?);
620        }
621        staged.extend(self.kind_declarations(value, resolved, cx, lw)?);
622        Ok(staged)
623    }
624
625    /// The declarations of the kind `value` itself: the theorem style of its
626    /// class where it is numbered, then its own declaration.
627    fn kind_declarations(
628        &self,
629        value: &TheoremElement,
630        resolved: bool,
631        cx: &mut LowerCx<'_>,
632        lw: &mut dyn Lowerer,
633    ) -> Result<Vec<BuildId>, LowerError> {
634        let mut staged = Vec::new();
635        if value.counter.is_some() {
636            // The theorem style named after the class, guarded on the
637            // control sequence `amsthm` makes for it.
638            let class = value.class_name.as_str();
639            let body = vec![raw(
640                cx,
641                lw,
642                &format!("\\newtheoremstyle{{{class}}}{PLAIN_STYLE_PARAMETERS}"),
643            )?];
644            staged.push(declaration(cx, lw, &format!("th@{class}"), body)?);
645        }
646        staged.push(self.declaration(value, resolved, cx, lw)?);
647        Ok(staged)
648    }
649
650    /// The declaration of the kind `value`, guarded on its environment's
651    /// name: see the [module documentation](self#the-declarations-in-the-style-file).
652    fn declaration(
653        &self,
654        value: &TheoremElement,
655        resolved: bool,
656        cx: &mut LowerCx<'_>,
657        lw: &mut dyn Lowerer,
658    ) -> Result<BuildId, LowerError> {
659        let env = value.name.as_str();
660        let word = self.headings.word(&value.name)?;
661        let word = lw.splice(cx, &word)?;
662        let (mandatory, optional) = (LatexArgShape::Mandatory, LatexArgShape::Optional);
663        let mut body = match (value.counter.is_some(), resolved) {
664            (true, false) => {
665                let mut keys = format!("thmstyle={}", value.class_name);
666                if value.class.shared_counter {
667                    keys.push_str(&format!(",counter={PHFTHM_SHARED_COUNTER}"));
668                }
669                if !value.kind.expects_proof {
670                    keys.push_str(",proofref=false");
671                }
672                let keys = vec![raw(cx, lw, &keys)?];
673                let name = vec![raw(cx, lw, env)?];
674                let mut body =
675                    vec![command(cx, lw, "phfMakeTheorem", vec![optional, mandatory, mandatory], vec![keys, name, word])?];
676                if value.class.shared_counter {
677                    // Under the LaTeX kernel's first aid for `amsthm` (from
678                    // TeX Live 2026), the environment steps
679                    // `phfthm@<kind>`, an alias of the counter that `phfthm`
680                    // gives it, and `hyperref`'s `\autoref` names a
681                    // reference by that counter: the name is provided where
682                    // nothing defined it.
683                    let word = self.headings.word(&value.name)?;
684                    let word = lw.splice(cx, &word)?;
685                    body.push(raw(
686                        cx,
687                        lw,
688                        &format!("\\expandafter\\providecommand\\csname phfthm@{env}autorefname\\endcsname{{"),
689                    )?);
690                    body.extend(word);
691                    body.push(raw(cx, lw, "}")?);
692                }
693                body
694            }
695            (false, false) => {
696                let mut name = vec![raw(cx, lw, "defaultproofname={")?];
697                name.extend(word);
698                name.push(raw(cx, lw, "}")?);
699                let env = vec![raw(cx, lw, env)?];
700                vec![command(cx, lw, "phfMakeProofEnv", vec![optional, mandatory], vec![name, env])?]
701            }
702            (true, true) => {
703                let style = vec![raw(cx, lw, value.class_name.as_str())?];
704                let style = command(cx, lw, "theoremstyle", vec![mandatory], vec![style])?;
705                let name = vec![raw(cx, lw, env)?];
706                let theorem = if value.class.shared_counter {
707                    let counter = vec![raw(cx, lw, SHARED_LATEX_COUNTER)?];
708                    command(cx, lw, "newtheorem", vec![mandatory, optional, mandatory], vec![name, counter, word])?
709                } else {
710                    command(cx, lw, "newtheorem", vec![mandatory, mandatory], vec![name, word])?
711                };
712                // The theorem style in effect before the declaration, which
713                // `amsthm` holds in the token register `\thm@style`, is
714                // restored after it, so that the style it sets does not reach
715                // what follows the style file. A group would lose part of the
716                // declaration: for a kind in a shared counter, the LaTeX
717                // kernel's first aid for `amsthm` (from TeX Live 2026) makes
718                // the kind's counter with `\newcounteralias`, which defines
719                // `\the<kind>` and `\p@<kind>` only inside the current group.
720                vec![
721                    raw(cx, lw, "\\edef\\flm@thm@style{\\the\\thm@style}")?,
722                    style,
723                    theorem,
724                    raw(cx, lw, "\\thm@style\\expandafter{\\flm@thm@style}")?,
725                ]
726            }
727            (false, true) => {
728                // An environment over `amsthm`'s `proof`, its default title
729                // the kind's word.
730                let mut body = vec![raw(cx, lw, &format!("\\newenvironment{{{env}}}[1][{{"))?];
731                body.extend(word);
732                body.push(raw(cx, lw, "}]{\\begin{proof}[{#1}]}{\\end{proof}}")?);
733                body
734            }
735        };
736        if value.counter.is_some() {
737            body.extend(self.reference_type(value, resolved, cx, lw)?);
738        }
739        declaration(cx, lw, env, body)
740    }
741
742    /// The reference type of the numbered kind `value` for the LaTeX
743    /// family's reference command, `\zcref` of the `zref-clever` package, as
744    /// two pieces of LaTeX:
745    ///
746    /// - the type, named after the kind, with the kind's own words mapped to
747    ///   the package's keys as every reference type of the family maps them
748    ///   ([`refs::reference_type_words`]):
749    ///   `\zcRefTypeSetup{lemma}{Name-sg={Lemma},name-sg={lemma},…}`, with the
750    ///   abbreviated keys too (`Name-sg-ab={Lem.}`, …) where the kind declares
751    ///   the variant `abbreviated`;
752    /// - the counters that the kind's environment steps, mapped to that type
753    ///   inside the environment
754    ///   (`\AddToHook{env/lemma/begin}{\zcsetup{countertype={<counter>=lemma}}}`),
755    ///   so that a reference to a lemma counting in a shared counter prints
756    ///   "lemma". The counters are the ones the declaration makes the
757    ///   environment step:
758    ///   - in the authored form, for a kind in the shared counter, the alias
759    ///     counter that `phfthm` creates under the kind's name, and
760    ///     `phfthm@<kind>`, the alias of it that the LaTeX kernel's first aid
761    ///     for `amsthm` (from TeX Live 2026) makes the environment step
762    ///     instead (`countertype={lemma=lemma,phfthm@lemma=lemma}`); for a
763    ///     kind with a counter of its own, the counter `phfthm@<kind>` that
764    ///     `phfthm` creates;
765    ///   - in the resolved form, the shared counter, or the kind's own counter
766    ///     under its name. Under the first aid, a kind in the shared counter
767    ///     steps an alias of it under the kind's name, which `zref-clever`
768    ///     takes as the reference type of that name without a mapping.
769    ///
770    /// Both are written inside the kind's declaration, so a kind defined
771    /// before the style file is loaded keeps the reference type its own
772    /// definition gives it.
773    fn reference_type(
774        &self,
775        value: &TheoremElement,
776        resolved: bool,
777        cx: &mut LowerCx<'_>,
778        lw: &mut dyn Lowerer,
779    ) -> Result<Vec<BuildId>, LowerError> {
780        let env = value.name.as_str();
781        let counters = match (value.class.shared_counter, resolved) {
782            (true, false) => vec![env.to_string(), format!("phfthm@{env}")],
783            (false, true) => vec![env.to_string()],
784            (false, false) => vec![format!("phfthm@{env}")],
785            (true, true) => vec![SHARED_LATEX_COUNTER.to_string()],
786        };
787        let mapping: Vec<String> = counters.iter().map(|counter| format!("{counter}={env}")).collect();
788        let mapping = mapping.join(",");
789        let words = self.headings.reference_words(&value.name)?;
790        let mut body = refs::stage_reference_type_setup(cx, lw, env, &words)?;
791        body.push(raw(
792            cx,
793            lw,
794            &format!("\\AddToHook{{env/{env}/begin}}{{\\zcsetup{{countertype={{{mapping}}}}}}}"),
795        )?);
796        Ok(body)
797    }
798}
799
800/// The rule of the three nodes of an instantiated heading, the name
801/// ([`NAME_ELEMENT`]), the title pointer ([`TITLE_POINTER`]) and the
802/// back-reference ([`RELATION`]), on the `latex-recomposed` backend: the
803/// node's own body, lowered through the rules, and nothing around it. The
804/// body is the kind's word for a name node and empty for the other two.
805///
806/// The three nodes occur only inside a heading that the general theorem rule
807/// instantiates from the class's heading template. This backend leaves the
808/// heading to LaTeX and instantiates no template, so the nodes never reach
809/// it. The rule exists because a plan checks that its backend can lower every
810/// element a document may hold.
811#[derive(Debug, Default, Clone, Copy)]
812struct HeadingNodeLatexRule;
813
814impl Lower for HeadingNodeLatexRule {
815    fn lower(
816        &self,
817        node: NodeRef<'_, Flm>,
818        cx: &mut LowerCx<'_>,
819        lw: &mut dyn Lowerer,
820    ) -> Result<Lowering, LowerError> {
821        Ok(Lowering::Emit(lw.lower_body(cx, &node)?))
822    }
823}
824
825/// The rules of the three nodes of a heading on the `latex-recomposed`
826/// backend ([`HeadingNodeLatexRule`]), each the default there only.
827fn heading_node_latex_rules() -> [LoweringRule; 3] {
828    [(NAME_LATEX_RULE, NAME_ELEMENT), (TITLE_POINTER_LATEX_RULE, TITLE_POINTER), (RELATION_LATEX_RULE, RELATION)]
829        .map(|(name, element)| {
830            LoweringRule::new(
831                name,
832                element,
833                LoweringDecl::new(),
834                Arc::new(HeadingNodeLatexRule),
835                DefaultMark::OnBackends(vec![BACKEND.into()]),
836            )
837            .docs(
838                "a node of a theorem's heading lowers to its own body; the recomposed LaTeX \
839                 instantiates no heading, because LaTeX writes a theorem's heading, so the node \
840                 never reaches this backend",
841            )
842        })
843}
844
845/// The theorem's rule, the default on the `latex-recomposed` backend only.
846fn latex_rule(headings: Arc<Headings>) -> LoweringRule {
847    LoweringRule::new(
848        THEOREM_LATEX_RULE,
849        THEOREM,
850        LoweringDecl::new()
851            .reads_opt(SAFE_LABELS)
852            .reads_opt(VALUE_SAFE_LABELS)
853            .option::<LatexRecomposedRenderOptions>()
854            .produces(DEFINITION)
855            .produces(ENVIRONMENT_CONSTRUCT)
856            .produces(MACRO)
857            .produces(RAW),
858        Arc::new(TheoremLatexRule { headings }),
859        DefaultMark::OnBackends(vec![BACKEND.into()]),
860    )
861    .docs(
862        "a theorem lowers to the environment of its kind's name around its title, its \
863         labels in the LaTeX hook `\\flmLabels`, `\\noproofref` where written, and its body, \
864         with the kind's declaration for the style file; a proof's title is written in the \
865         LaTeX hook `\\flmProofTitle`, and its back-reference as written, or, under the \
866         render option `resolved_proof_refs`, as a reference in `\\flmProofTitle`",
867    )
868}
869
870/// Registers the theorem's rule and the rules of the three nodes of a
871/// heading ([`HeadingNodeLatexRule`]), each the default on the
872/// `latex-recomposed` backend only, and contributes the feature's definition
873/// piece and the definition piece of each form ([`definition_piece`],
874/// [`authored_piece`], [`resolved_piece`]) to the service slot of definition
875/// pieces ([`preamble::SLOT`]). The names they use that other features own
876/// (the backend, the LaTeX family's construct elements, the safe-labels
877/// tables, the service slot of definition pieces) are declared through peer
878/// declarations ([`PeerName`](crate::core::registry::PeerName)), so that a
879/// registry without them still builds, with these rules set aside (excluded
880/// from rule selection).
881///
882/// # Errors
883///
884/// The [`BuildError`] of the registry builder.
885pub(super) fn register(b: &mut FeatureBuilder<'_>, headings: Arc<Headings>) -> Result<(), BuildError> {
886    b.peer_backend(
887        BACKEND,
888        "the latex-recomposed backend, on which the feature's LaTeX rules are the default",
889    )?;
890    b.peer_element::<LatexDefinitionPayload>(
891        DEFINITION,
892        "the LaTeX family's definition construct, which the theorem's rule stages for the \
893         declarations of the kinds",
894    )?;
895    b.peer_element::<LatexEnvironmentPayload>(
896        ENVIRONMENT_CONSTRUCT,
897        "the LaTeX family's environment construct, which the theorem's rule stages",
898    )?;
899    b.peer_element::<LatexMacroPayload>(
900        MACRO,
901        "the LaTeX family's macro-call construct, which the rules stage for the labels, \
902         `\\noproofref`, and the LaTeX hooks `\\flmProofTitle` (a proof's title) and `\\flmRef` \
903         (a reference)",
904    )?;
905    b.peer_element::<LatexRawPayload>(
906        RAW,
907        "the LaTeX family's raw node construct, in which the theorem's rule writes a \
908         back-reference's stars, the declarations' fixed LaTeX, and a label whose label type \
909         the references feature marks as raw (written byte for byte)",
910    )?;
911    b.peer_table::<SafeLabels>(
912        SAFE_LABELS.name(),
913        "the references feature's safe-labels table, which the rules read for the safe label \
914         written for a label",
915    )?;
916    b.peer_table::<ValueSafeLabels>(
917        VALUE_SAFE_LABELS.name(),
918        "the references feature's value names, which the rules read for the safe label of a \
919         back-reference in a proof inside a synthesized value",
920    )?;
921    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
922    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(authored_piece()))?;
923    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(resolved_piece()))?;
924    b.lowering_rule(latex_rule(headings))?;
925    for rule in heading_node_latex_rules() {
926        b.lowering_rule(rule)?;
927    }
928    Ok(())
929}
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934    use crate::stdlib::backends::latex::preamble::piece_id;
935
936    #[test]
937    fn the_piece_is_named_as_its_identifier_says_and_provides_noproofref() {
938        let piece = definition_piece();
939        assert_eq!(piece.id, piece_id(PIECE_NAME));
940        assert_eq!(piece.id.as_str(), PIECE);
941        assert!(piece.content.contains("\\ProvideDocumentCommand\\noproofref{}{}"));
942        assert!(!piece.content.contains("flmProofTitle"));
943        assert!(piece.requires.is_empty());
944    }
945
946    #[test]
947    fn each_form_s_piece_provides_the_proof_title_hook_with_its_own_default() {
948        let authored = authored_piece();
949        assert_eq!(authored.id, piece_id(AUTHORED_PIECE_NAME));
950        assert_eq!(authored.id.as_str(), AUTHORED_PIECE);
951        assert!(authored.content.contains("\\ProvideDocumentCommand\\flmProofTitle{m}{#1}\n"));
952        assert_eq!(authored.requires, [Name::from(packages::PHFTHM)]);
953        let resolved = resolved_piece();
954        assert_eq!(resolved.id, piece_id(RESOLVED_PIECE_NAME));
955        assert_eq!(resolved.id.as_str(), RESOLVED_PIECE);
956        assert!(
957            resolved.content.contains("\\ProvideDocumentCommand\\flmProofTitle{m}{\\proofname\\space (#1)}\n")
958        );
959        assert_eq!(resolved.requires, [Name::from(packages::AMSTHM)]);
960    }
961}