Skip to main content

flm_core/stdlib/features/theorems/
elements.rs

1//! The element of the [`theorems`](super) feature, [`THEOREM`]
2//! (`flm.theorems.theorem`), with one element value per configured theorem
3//! kind: its arguments and fields, the reference point every theorem declares,
4//! and the back-reference a proof's title declares ([`title_reading`]).
5//!
6//! # What an author writes
7//!
8//! ```text
9//! \begin{lemma}[Key lemma]\label{lem:key}
10//!   Every bounded monotone sequence converges.
11//! \end{lemma}
12//! \begin{proof}[*lem:key]
13//!   …
14//! \end{proof}
15//! ```
16//!
17//! Every theorem kind is an environment of its own name. It takes an optional
18//! **title**, ordinary inline content, then two fields in any order: the
19//! references feature's `\label{…}`, repeatable, and the feature's own
20//! `\noproofref`, which takes no argument and says that no proof of the
21//! statement is coming. A field is a macro that a construct reads as data
22//! rather than as content (see [fields: data a construct
23//! reads](crate::guide::concepts_overview#fields-data-a-construct-reads)).
24//! The environment's body is laid out as blocks.
25//!
26//! # The reference point
27//!
28//! Every theorem is one [reference point](crate::model::aspects::RefPoint) of
29//! the reference kind [`POINT_KIND`], `theorem`, including a proof.
30//!
31//! - A theorem of a **numbered** kind carries the labels of its `\label`
32//!   fields and accepts the configuration's
33//!   [`label_types`](super::TheoremsConfig::label_types). It counts in its
34//!   class's counter and is shown in its kind's counter style
35//!   ([`numbers`](super::numbers)). Its anchor is the environment's name and
36//!   its number, `lemma-4` (`lemma-2-3` in a document that numbers theorems
37//!   within sections); where the document did not number it, its anchor is
38//!   formed from its first label ([`AnchorPolicy::FromValue`]).
39//! - A theorem of an **unnumbered** kind, such as a proof, is numbered by
40//!   nothing and accepts no label. A `\label` on a proof is reported by the
41//!   references feature as `flm.refs.label-type-not-accepted` (with the
42//!   condition's field `accepted` empty and its field `kind` equal to
43//!   `theorem`), and the proof has no anchor.
44//!
45//! # The back-reference
46//!
47//! On a kind whose class reads back-references
48//! ([`relation_ref`](super::TheoremClass::relation_ref)), a title that is one
49//! run of plain characters beginning with a star is a **back-reference** to
50//! the statement the theorem proves: `[*lem:key]` refers to the statement
51//! labeled `lem:key` and shows its word and number in the heading, and
52//! `[**lem:key]` refers to the same statement and shows nothing in the
53//! heading. The theorem then
54//! declares one [reference site](crate::model::aspects::RefSite), which the
55//! references feature resolves as it resolves `\ref`. Every other title is a
56//! title, whether it begins with a star or not ([`title_reading`]).
57//!
58//! A title on such a kind that begins with a star, comments and whitespace
59//! aside, but is not one run of characters (`[*\emph{x}]`, `[~*lem:key]`), or
60//! whose text after the stars is not of the form `type:label`, is malformed ([`TitleReading::Malformed`]): it declares
61//! no reference site, the feature's check reports it
62//! ([`check`](super::check)), and the theorem's rules show the title as
63//! written.
64//!
65//! # A starred title is kept as typed
66//!
67//! The references feature compares a back-reference's label with the labels
68//! of `\label` as typed. On a kind whose class reads back-references, the
69//! title's reader ([`theorem_args`]) therefore places a title that begins with
70//! a star, comments and whitespace aside, under an opaque wrapper (see [opaque
71//! regions](crate::guide::concepts_overview#opaque-regions)): the
72//! block-structure pass carries it over as written, so `[*lem:a--b]` refers to
73//! the statement labeled `lem:a--b`, and a malformed back-reference is shown as
74//! typed. Every other title is content, laid out and shown as any optional
75//! argument is, with the typographic substitutions applied.
76//!
77//! The reader sees the star only where the theorem's own source writes it. A
78//! star written in a user definition's template (`[*#1]`) is seen, and the
79//! title is kept as typed whatever the use site writes after it. A star that
80//! arrives through a placeholder (a template `[#1]` used as `\pf{*lem:a--b}`)
81//! is not seen: that title is laid out as content, and a label holding `--`,
82//! quotes, an apostrophe or `...` does not resolve through it.
83
84use std::sync::Arc;
85
86use techy::core::constructs::{ArgumentParser, ConstructParserResult, ParseContext, ParsedArgumentNodes};
87use techy::core::node::{BuildId, ContentNodes, NodeKind, NodeRef, StagedNodeView, StagedNodes};
88use techy::core::specs::ArgumentSpec;
89
90use crate::lang::mint::opaque::wrap_argument;
91use crate::lang::mint::{
92    ArgDef, ArgStdKind, DefinitionShape, FlmArgumentParser, IntoFlmArgumentParser, TackOnField,
93    field_name,
94};
95use crate::lang::text::{CharsSegment, is_blank, is_blank_text, is_space, read_chars};
96use crate::lang::{Flm, FlmCallableType, FlmGroupType};
97use crate::model::aspects::{
98    AcceptedRefTypes, AnchorPolicy, ApartFromText, BlockRole, BlockRoleAspect, ContentRef,
99    FixedBlockRole, Label, NumberSource, PointId, RefDisplayOptions, RefPoint, RefSite,
100    Referenceable, Referencing, Whitespace,
101};
102use crate::model::addr::NodeAddr;
103use crate::model::element::{ElementSpec, element_of, element_value};
104use crate::model::names::{Name, RefKind};
105use crate::stdlib::features::refs;
106
107use super::config::{TheoremClass, TheoremKind, TheoremsConfig};
108use super::numbers::{counter_name, style_name};
109
110/// The element name of every theorem, `flm.theorems.theorem`. The element
111/// has one element value per configured theorem kind, each carrying a
112/// [`TheoremElement`] as its data.
113pub const THEOREM: &str = "flm.theorems.theorem";
114
115/// The name of a theorem's optional title argument, `title`.
116pub const TITLE_ARG: &str = "title";
117
118/// The name of the field that marks a statement as having no proof,
119/// `noproofref`, written `\noproofref` after the title. It is one of the
120/// fields of the theorem's tack-on argument (the trailing argument that
121/// absorbs field macros; see [`theorem_args`]).
122pub const NOPROOFREF_FIELD: &str = "noproofref";
123
124/// The reference kind of every theorem's reference point, `theorem`, for
125/// every theorem kind alike.
126pub const POINT_KIND: &str = "theorem";
127
128/// The data of one element value of [`THEOREM`]: the theorem kind an
129/// environment is, its class, and what its reference point needs. The
130/// feature creates one per configured kind ([`TheoremElement::of`]).
131///
132/// The element value carries this data and the aspects it implements: one
133/// reference point ([`Referenceable`]), one reference site for a
134/// back-reference ([`Referencing`]), and its fields kept apart from its text
135/// ([`ApartFromText`]). A rule or a stage reads it from a node with
136/// [`element_value`].
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct TheoremElement {
139    /// The kind's name, which is also the environment's name.
140    pub name: Name,
141    /// The kind as configured.
142    pub kind: TheoremKind,
143    /// The name of the kind's class.
144    pub class_name: Name,
145    /// The kind's class as configured.
146    pub class: TheoremClass,
147    /// The counter a theorem of this kind counts in
148    /// ([`counter_name`]), or `None` for an
149    /// unnumbered kind.
150    pub counter: Option<Name>,
151    /// The label types a theorem of this kind accepts: the configuration's
152    /// [`label_types`](TheoremsConfig::label_types) for a numbered kind, none
153    /// for an unnumbered kind.
154    pub label_types: Vec<String>,
155}
156
157impl TheoremElement {
158    /// The data of the kind `name` of `config`; `None` where the kind or its
159    /// class is not declared.
160    pub fn of(config: &TheoremsConfig, name: &Name) -> Option<TheoremElement> {
161        let (kind, class) = config.kind_and_class(name.as_str())?;
162        let counter = counter_name(config, name.as_str());
163        let label_types = if counter.is_some() { config.label_types.clone() } else { Vec::new() };
164        Some(TheoremElement {
165            name: name.clone(),
166            kind: kind.clone(),
167            class_name: kind.class.clone(),
168            class: class.clone(),
169            counter,
170            label_types,
171        })
172    }
173}
174
175/// What a theorem's title argument is, as [`title_reading`] reads it: no
176/// title, a title, a back-reference, a malformed back-reference, or not yet
177/// known.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub enum TitleReading {
180    /// No title argument is written.
181    Absent,
182    /// A title, shown as the theorem's own content.
183    Title,
184    /// A back-reference to the statement labeled `label`: shown in the
185    /// heading where `shown` (one star), recorded only where not (two stars).
186    Relation {
187        /// The text after the stars, trimmed.
188        text: String,
189        /// The label that `text` is the written form of.
190        label: Label,
191        /// Whether the heading shows the reference: one star.
192        shown: bool,
193    },
194    /// A title beginning with a star, on a kind that reads back-references,
195    /// that is not one run of characters or whose text after the stars is
196    /// not of the form `type:label`. It declares no reference site; the
197    /// feature's check reports it ([`BadRelationRef`](super::BadRelationRef)),
198    /// and the theorem's rules show the title as written.
199    Malformed,
200    /// A title in the template of a kept definition (a user definition whose
201    /// use sites a plan leaves in the tree; see [kept
202    /// definitions](crate::stdlib::features::userdefs::kept)), with a
203    /// placeholder where a back-reference's first characters would be:
204    /// whether it is a back-reference is not known until the
205    /// template is called. It declares no reference site, and the theorem's
206    /// rules return
207    /// [`LowerError::PlaceholderCharacters`](crate::core::lowering::LowerError::PlaceholderCharacters),
208    /// so that each use site of the definition is expanded instead.
209    Unknown,
210}
211
212/// What the title of the theorem `node` is (see the [module
213/// documentation](self#the-back-reference)); `None` for a node that is not a
214/// theorem. On a kind whose class does not read back-references, every
215/// written title is a [`Title`](TitleReading::Title).
216///
217/// This is the only function that says what a title is: the theorem's
218/// reference site, its rules, the feature's check and every later reader of
219/// the relation call it, so they all agree. The title's reader that
220/// [`theorem_args`] gives a class reading back-references decides, while it
221/// parses the title, whether to keep the title as typed; the tree does not
222/// exist yet, so that reader holds a copy of this function's test for a star,
223/// run over the nodes it stages. A change to the test here is made there
224/// too, so that a title is kept as typed exactly where this function reads it
225/// as starred.
226pub fn title_reading(node: &NodeRef<'_, Flm>) -> Option<TitleReading> {
227    let value = element_value::<TheoremElement>(node)?;
228    let Ok(Some(title)) = node.argument_content_nodes_named(TITLE_ARG) else {
229        return Some(TitleReading::Absent);
230    };
231    if !value.class.relation_ref {
232        return Some(TitleReading::Title);
233    }
234    // The title's reader makes the same test for a star over the nodes it
235    // stages (`begins_with_star`); the two tests change together.
236    let Ok(read) = read_chars(title.iter()) else {
237        // Not one run of characters: a back-reference only where the title's
238        // first node, comments, blank characters and whitespace nodes (`~`)
239        // aside, is characters beginning with a star; a title opening with a
240        // command, a group or a formula is a title.
241        let starred = title
242            .iter()
243            .find(|node| !(node.is_comment() || is_blank(node)))
244            .and_then(|node| node.chars())
245            .is_some_and(|text| text.trim_start_matches(is_space).starts_with('*'));
246        return Some(if starred { TitleReading::Malformed } else { TitleReading::Title });
247    };
248    // The characters before the first placeholder, if any stands.
249    let leading: String = read
250        .segments()
251        .iter()
252        .map_while(|segment| segment.as_text())
253        .collect();
254    let leading = leading.trim_start_matches(is_space);
255    let placeholder = read.segments().iter().any(|segment| matches!(segment, CharsSegment::Placeholder(_)));
256    if placeholder && (leading.is_empty() || leading.starts_with('*')) {
257        return Some(TitleReading::Unknown);
258    }
259    let Some(starred) = leading.strip_prefix('*') else {
260        return Some(TitleReading::Title);
261    };
262    let (rest, shown) = match starred.strip_prefix('*') {
263        Some(rest) => (rest, false),
264        None => (starred, true),
265    };
266    let text = rest.trim_matches(is_space).to_string();
267    Some(match Label::parse(&text) {
268        Some(label) => TitleReading::Relation { text, label, shown },
269        None => TitleReading::Malformed,
270    })
271}
272
273/// The back-reference site the theorem `node` declares, read through its
274/// element's [`Referencing`] aspect: the site the references feature
275/// resolves, whose [`shown`](RefSite::shown) and
276/// [`display`](RefSite::display) say how the heading shows it. `None` where
277/// the title declares no site.
278pub(super) fn relation_site(node: &NodeRef<'_, Flm>) -> Option<RefSite> {
279    element_of(node).aspect::<dyn Referencing>()?.sites(node).into_iter().next()
280}
281
282/// The reference point the theorem at `addr` declares: its first and only
283/// point ([`Referenceable`] below declares one).
284pub(super) fn theorem_point(addr: NodeAddr) -> PointId {
285    PointId { addr, index: 0 }
286}
287
288/// The back-reference site the theorem at `addr` declares, where its title
289/// declares one: its first and only site ([`Referencing`] below declares at
290/// most one).
291pub(super) fn relation_site_id(addr: NodeAddr) -> refs::SiteId {
292    refs::SiteId { addr, index: 0 }
293}
294
295/// Whether the theorem `node` carries the field `\noproofref`.
296pub fn has_noproofref(node: &NodeRef<'_, Flm>) -> bool {
297    let Ok(Some(fields)) = node.argument_content_nodes_named(refs::FIELDS_ARG) else {
298        return false;
299    };
300    fields.iter().any(|field| field_name(&field) == Some(NOPROOFREF_FIELD))
301}
302
303/// One reference point per theorem, carrying the theorem's labels. For a
304/// numbered kind, the point is numbered in its class's counter, shown in the
305/// kind's counter style and anchored on its number. For an unnumbered kind,
306/// the point is numbered by nothing and accepts no label.
307impl Referenceable for TheoremElement {
308    fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
309        let (labels, malformed) = refs::point_labels(&refs::label_uses(node));
310        // An unnumbered kind's point accepts no label, so the references feature
311        // reports a label written on a proof; this feature needs no check of
312        // its own for it.
313        let (anchor, number) = match &self.counter {
314            Some(counter) => (
315                AnchorPolicy::FromValue { prefix: self.name.to_string() },
316                Some(NumberSource {
317                    counter: counter.clone(),
318                    instances: Vec::new(),
319                    style: style_name(self.name.as_str()),
320                    advance: vec![0],
321                    number_format: None,
322                }),
323            ),
324            None => (AnchorPolicy::FromFirstLabel, None),
325        };
326        vec![RefPoint {
327            kind: RefKind::from(POINT_KIND),
328            labels,
329            computed: 0,
330            malformed,
331            anchor,
332            number,
333            content: None,
334            accepts: AcceptedRefTypes::these(self.label_types.iter().map(String::as_str)),
335        }]
336    }
337}
338
339/// One reference site for a back-reference ([`TitleReading::Relation`]),
340/// whose target is the back-reference's label, shown with the reference's
341/// default display (the target's word and number), and shown in the heading
342/// or not as the stars say; no site for any other title.
343impl Referencing for TheoremElement {
344    fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
345        match title_reading(node) {
346            Some(TitleReading::Relation { label, shown, .. }) => vec![RefSite {
347                target: label,
348                display: RefDisplayOptions { variant: None, with_prefix: true },
349                shown,
350            }],
351            _ => Vec::new(),
352        }
353    }
354}
355
356/// A theorem's fields, its `\label{…}` and `\noproofref`, are not part of its
357/// text: they label the theorem and say something about it.
358impl ApartFromText for TheoremElement {
359    fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
360        vec![ContentRef::ArgumentNamed(refs::FIELDS_ARG.to_string())]
361    }
362}
363
364/// The element value of the kind `value`: a block with one reference point,
365/// the back-reference's site, and its fields kept apart from its text.
366pub(super) fn theorem_element(value: TheoremElement) -> Arc<ElementSpec> {
367    let docs = format!("`{}`: a theorem-like environment of the theorem class `{}`.", value.name, value.class_name);
368    let value = Arc::new(value);
369    Arc::new(
370        ElementSpec::new(THEOREM)
371            .docs(docs)
372            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
373            .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
374            .with::<dyn Referencing>(Arc::clone(&value) as Arc<dyn Referencing>)
375            .with::<dyn ApartFromText>(Arc::clone(&value) as Arc<dyn ApartFromText>)
376            .with_value(value),
377    )
378}
379
380/// The arguments of the theorem environments of a class, in order: the
381/// optional title ([`TITLE_ARG`]), then the tack-on argument (the trailing
382/// argument that absorbs field macros; [`ArgStdKind::TackOn`]) under the
383/// references feature's argument name ([`FIELDS_ARG`](refs::FIELDS_ARG)),
384/// holding the fields `\label{…}` (the references feature's declaration,
385/// [`label_field`](refs::label_field)), repeatable, and `\noproofref`
386/// ([`NOPROOFREF_FIELD`]).
387///
388/// `relation_ref` is the class's
389/// [`relation_ref`](super::TheoremClass::relation_ref). Where it is false, the
390/// title is an optional argument of the standard kind
391/// ([`ArgStdKind::Optional`]). Where it is true, the title is read by the
392/// feature's own reader, which reads the same optional `[…]` group and places
393/// a title that begins with a star under an opaque wrapper, so that a
394/// back-reference is read as typed (see the [module
395/// documentation](self#a-starred-title-is-kept-as-typed)).
396pub fn theorem_args(relation_ref: bool) -> Vec<ArgDef> {
397    let noproofref = TackOnField::new(NOPROOFREF_FIELD, Vec::new())
398        .docs("Says that no proof of the statement is coming.");
399    let fields = ArgStdKind::TackOn { fields: vec![refs::label_field(), noproofref] };
400    let title = if relation_ref {
401        ArgDef::named(TITLE_ARG, RelationTitleParser::new())
402    } else {
403        ArgDef::named(TITLE_ARG, ArgStdKind::Optional)
404    };
405    vec![
406        title
407            .docs(
408                "The theorem's title, or, on a proof, a back-reference `*type:label` to the \
409                 statement it proves.",
410            ),
411        ArgDef::named(refs::FIELDS_ARG, fields)
412            .docs(
413                "The `\\label{…}` and `\\noproofref` fields written after the title: they label \
414                 the theorem and mark it as having no proof.",
415            ),
416    ]
417}
418
419/// The identity of the title reader of a class that reads back-references
420/// ([`RelationTitleParser`]) in the registry digest,
421/// `flm.theorems.relation-title`.
422const RELATION_TITLE_IDENTITY: &str = "flm.theorems.relation-title";
423
424/// The reader of the title of a theorem whose class reads back-references
425/// ([`relation_ref`](super::TheoremClass::relation_ref)): an optional `[…]`
426/// group, read by the reader of an optional argument of the standard kind
427/// ([`ArgStdKind::Optional`]), and placed under an opaque wrapper when it
428/// begins with a star ([`begins_with_star`]). See the [module
429/// documentation](self#a-starred-title-is-kept-as-typed).
430///
431/// The content designation names the same nodes with or without the
432/// wrapper, so [`title_reading`] reads the title the same way in both cases.
433/// An argument that is not written is absent.
434///
435/// What it states through [`FlmArgumentParser`]: its identity is
436/// [`RELATION_TITLE_IDENTITY`]; it is written as a value in a recomposed user
437/// definition, as an optional argument is; its description is "an optional
438/// `[…]` group, kept as written when it begins with `*`".
439#[derive(Debug)]
440struct RelationTitleParser {
441    /// The parser of an optional argument of the standard kind.
442    optional: Arc<dyn FlmArgumentParser>,
443}
444
445impl RelationTitleParser {
446    /// Creates the reader.
447    fn new() -> RelationTitleParser {
448        RelationTitleParser { optional: ArgStdKind::Optional.into_flm_argument_parser() }
449    }
450}
451
452impl ArgumentParser<Flm> for RelationTitleParser {
453    fn parse_argument(
454        &self,
455        cx: &mut ParseContext<'_, '_, Flm>,
456        spec: &ArgumentSpec<Flm>,
457    ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
458        let Some(read) = self.optional.parse_argument(cx, spec)? else {
459            return Ok(None);
460        };
461        let staged = cx.staged_nodes();
462        let content = match &read.content {
463            ContentNodes::InRegion(range) => read.nodes.get(range.start as usize..range.end as usize),
464            ContentNodes::InChildrenOf(parent, range) => staged
465                .get(*parent)
466                .and_then(|view| view.children().get(range.start as usize..range.end as usize)),
467        };
468        if !begins_with_star(staged, content.unwrap_or_default()) {
469            return Ok(Some(read));
470        }
471        wrap_argument(cx, read).map(Some)
472    }
473
474    fn can_match_empty(&self) -> bool {
475        self.optional.can_match_empty()
476    }
477}
478
479impl FlmArgumentParser for RelationTitleParser {
480    fn identity(&self) -> Vec<u8> {
481        RELATION_TITLE_IDENTITY.as_bytes().to_vec()
482    }
483
484    fn definition_shape(&self) -> DefinitionShape {
485        DefinitionShape::Value
486    }
487
488    fn description(&self) -> String {
489        String::from("an optional `[…]` group, kept as written when it begins with `*`")
490    }
491}
492
493/// Whether the staged nodes `content`, the content of a title just read,
494/// begin with a star as [`title_reading`] reads a title: where they are one
495/// run of characters (characters, comments, placeholders and groups that are
496/// not formulas), whether their characters before the first placeholder,
497/// whitespace aside, begin with a star; otherwise, whether their first node,
498/// comments, blank characters and whitespace nodes (`~`) aside, is
499/// characters beginning with a star.
500/// So the wrapper stands over exactly the titles that [`title_reading`] reads
501/// as a back-reference, a malformed one, or a placeholder after a star.
502///
503/// This is a copy of [`title_reading`]'s test for a star, and
504/// [`leading_characters`] walks the nodes as [`read_chars`] does: the reader
505/// runs before the tree exists, so it has no [`NodeRef`] to give
506/// [`title_reading`]. A change to either test is made to both.
507fn begins_with_star(staged: StagedNodes<'_, Flm>, content: &[BuildId]) -> bool {
508    match leading_characters(staged, content) {
509        Some(leading) => leading.trim_start_matches(is_space).starts_with('*'),
510        None => content
511            .iter()
512            .filter_map(|id| staged.get(*id))
513            .filter(|view| {
514                !matches!(view.kind(), NodeKind::Comment(_))
515                    && !view.ext().element.has_aspect::<dyn Whitespace>()
516            })
517            .find(|view| staged_chars(view).is_none_or(|text| !is_blank_text(text)))
518            .and_then(|view| staged_chars(&view))
519            .is_some_and(|text| text.trim_start_matches(is_space).starts_with('*')),
520    }
521}
522
523/// The characters of the staged nodes `content` before their first
524/// placeholder, in document order, where the nodes are one run of
525/// characters as [`read_chars`] reads one; `None` where they hold a command
526/// other than a placeholder, or a formula.
527fn leading_characters(staged: StagedNodes<'_, Flm>, content: &[BuildId]) -> Option<String> {
528    let mut leading = String::new();
529    let mut at_placeholder = false;
530    // Document order without recursion, as in `read_chars`.
531    let mut pending: Vec<BuildId> = content.iter().rev().copied().collect();
532    while let Some(id) = pending.pop() {
533        let view = staged.get(id)?;
534        match view.kind() {
535            NodeKind::Chars { .. } => {
536                if !at_placeholder {
537                    leading.push_str(staged_chars(&view).unwrap_or_default());
538                }
539            }
540            NodeKind::Comment(_) => {}
541            NodeKind::Group(group) if matches!(group.group_type, Some(FlmGroupType::Math(_))) => {
542                return None;
543            }
544            NodeKind::Group(_) | NodeKind::List => pending.extend(view.children().iter().rev()),
545            NodeKind::Callable(callable) => {
546                if callable.callable_type != FlmCallableType::Placeholder {
547                    return None;
548                }
549                at_placeholder = true;
550            }
551        }
552    }
553    Some(leading)
554}
555
556/// The characters of the staged node `view`, where it is a node of
557/// characters.
558fn staged_chars<'b>(view: &StagedNodeView<'b, Flm>) -> Option<&'b str> {
559    match view.kind() {
560        NodeKind::Chars { content } => Some(content.resolve(view.span().source())),
561        _ => None,
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568
569    #[test]
570    fn a_kind_of_a_numbered_class_counts_and_accepts_the_label_types() {
571        let config = TheoremsConfig::new();
572        let lemma = TheoremElement::of(&config, &Name::from("lemma")).expect("declared");
573        assert_eq!(lemma.counter.as_deref(), Some("flm.theorems.theorem"));
574        assert_eq!(lemma.label_types, config.label_types);
575        assert_eq!(lemma.class_name.as_str(), "theoremlike");
576        let proof = TheoremElement::of(&config, &Name::from("proof")).expect("declared");
577        assert_eq!(proof.counter, None);
578        assert!(proof.label_types.is_empty());
579        assert!(TheoremElement::of(&config, &Name::from("nosuch")).is_none());
580    }
581}