Skip to main content

flm_core/stdlib/features/numbering/
feature.rs

1//! This module defines the `numbering` feature ([`Numbering`]) and its
2//! configuration ([`NumberingConfig`]), along with the checks of the
3//! declarations made in other features for the numbering feature.
4//!
5//! The checks run in two steps of the registry build. The finalizer
6//! [`Validate`] runs once every feature has registered. It reads the
7//! declarations from the five service slots of the numbering feature, and
8//! checks that every name used in a declaration is declared. The
9//! late-initialization hook [`Compile`] runs once the language is built. It
10//! compiles the texts of the counter styles and of the within-joiners, and
11//! checks which counters each within-joiner writes. If either step finds a
12//! mistake, the registry build fails.
13//!
14//! The [module documentation of the numbering feature](super) describes the
15//! feature and lists the mistakes for which the registry build fails.
16
17use std::collections::BTreeMap;
18use std::hash::{Hash, Hasher};
19use std::sync::{Arc, OnceLock};
20
21use crate::core::settings::SettingsDecl;
22use crate::model::names::Name;
23use crate::model::options::Bind;
24use crate::core::registry::{
25    BuildError, FeatureBuilder, FeatureInfo, Finalizer, FlmFeature, LateInit, LateInitError,
26};
27use crate::core::services::Arity;
28use crate::lang::{BuiltLang, FlmDiagnostics};
29
30use crate::lang::rewrites::userdefs::template::TemplateLanguage;
31
32use super::decl::{
33    chains_of, digest_text, CounterDecl, ParentSetDecl, Parents,
34    ParentsError, Within, WithinJoinerSpec, COUNTERS_SLOT, NUMBER_WRITERS_SLOT, PARENT_SETS_SLOT,
35    RESERVED_PREFIX, STYLES_SLOT, WITHIN_JOINERS_SLOT,
36};
37use super::joiner::{
38    compile_within, CompiledWithinJoiner, WithinCx, WithinJoiner, WithinJoinerDecl,
39};
40use super::options::NumberingOptions;
41use super::stage::NumberStage;
42use super::formats::NumberTemplate;
43use super::style::{CounterStyle, CounterStyleDecl};
44use super::writer::{NumberWriter, NumberWriterDecl};
45use super::table::COUNTERS;
46
47/// The registered name of the numbering feature, `numbering`.
48pub const FEATURE: &str = "numbering";
49
50/// Returns the settings declaration of the numbering feature
51/// ([`settings`](crate::core::settings)). The settings keys are `styles`, the
52/// field of [`NumberingConfig`], and `counters`, the field of
53/// [`NumberingOptions`]. The texts of the counter styles and of the
54/// within-joiners in these settings are declared as FLM markup.
55fn settings() -> SettingsDecl {
56    SettingsDecl::new(FEATURE)
57        .config::<NumberingConfig>(
58            "Counter styles that are used in place of the counter styles declared with the \
59            same names. The fields missing from an entry take their default values, and not \
60            the values of the declared counter style. Fixed when the registry is built; it \
61            cannot vary per document or per render.",
62        )
63        .options::<NumberingOptions>(
64            Bind::Either,
65            "For each counter, the counters within which it is numbered and the value it has \
66            before it is first advanced. Set on the document. These options can also be set \
67            on a render request; the values set there are used in place of those of the \
68            document for that render.",
69        )
70        .merge_entries("styles", || crate::core::settings::named::to_data(&NumberingConfig::default().styles, "name"))
71        .remove_false("styles")
72        .markup("styles.*.prefix_words")
73        .markup("styles.*.delimiters")
74        .markup("styles.*.join")
75        .markup("styles.*.number_format")
76        .markup("styles.*.sub_levels")
77        .markup("counters.*.within.counter.joiner.joined")
78        .markup("counters.*.within.counter.joiner.template")
79}
80
81/// The configuration of the [`numbering`](super) feature: counter styles to be
82/// used in place of declared counter styles.
83///
84/// A counter style ([`CounterStyleDecl`]) specifies how the numbers of a
85/// counter are written: the number format, the word before the number (e.g.,
86/// `Eq.~`), the delimiters (e.g., parentheses), and the texts that join
87/// several numbers. Counter styles are declared in the features that number
88/// constructs, such as the headings feature. With this configuration, a host
89/// program can change a declared counter style without writing a feature.
90/// Each entry of [`styles`](NumberingConfig::styles) is a complete counter
91/// style that is used in place of the declared counter style with the same
92/// name. If no
93/// counter style with this name is declared in any feature, the registry build
94/// fails.
95///
96/// The configuration is fixed when the registry is built, because the texts
97/// of the counter styles are parsed at that time ([settings, options and
98/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
99/// The counter styles cannot be changed for a single document. The numbering
100/// options of a document ([`NumberingOptions`](super::NumberingOptions)) can
101/// only change the counters within which a counter is numbered, how their
102/// numbers are written before the number of the counter, and the initial
103/// value of the counter.
104///
105/// A host program passes the configuration as the `numbering` field of
106/// [`StdlibConfig`](crate::stdlib::StdlibConfig), or in settings data as
107/// the settings key `styles` of the `numbering` feature. In settings data,
108/// `styles` is a map from the name of a counter style to its replacement. The
109/// fields missing from an entry take the defaults of
110/// [`CounterStyleDecl::new`] (a decimal number, no word, no delimiters, the
111/// default join texts), and not the values of the declared counter style.
112/// Therefore each field of the declared counter style that is to be kept must
113/// be repeated in the entry.
114///
115/// # Examples
116///
117/// ```
118/// use flm_core::stdlib::features::numbering::{
119///     CounterStyleDecl, Delimiters, NumberingConfig, PrefixWords,
120/// };
121///
122/// let mut equations = CounterStyleDecl::new("flm.math.style.equation");
123/// equations.delimiters = Delimiters::new("[", "]");
124/// equations.prefix_words = PrefixWords::new("Gl.~", "Gln.~");
125/// let config = NumberingConfig::new().style(equations);
126/// assert_eq!(config.styles.len(), 1);
127/// ```
128#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)]
129#[derive(schemars::JsonSchema)]
130#[serde(default, deny_unknown_fields)]
131pub struct NumberingConfig {
132    /// The replacement counter styles. Each entry is used in place of the
133    /// counter style declared with the same name.
134    ///
135    /// In settings data, the fields missing from an entry take the defaults
136    /// of [`CounterStyleDecl::new`], and not the values of the declared
137    /// counter style.
138    #[serde(deserialize_with = "crate::core::settings::named::deserialize")]
139    #[schemars(
140        transform = crate::core::settings::named::map_schema,
141        with = "std::collections::BTreeMap<String, CounterStyleDecl>"
142    )]
143    pub styles: Vec<CounterStyleDecl>,
144}
145
146impl NumberingConfig {
147    /// Returns the default configuration, which contains no replacement counter
148    /// style.
149    pub fn new() -> NumberingConfig {
150        NumberingConfig::default()
151    }
152
153    /// Adds `style` to the replacement counter styles, and returns the
154    /// configuration. `style` is used in place of the counter style declared
155    /// with the same name.
156    pub fn style(mut self, style: CounterStyleDecl) -> NumberingConfig {
157        self.styles.push(style);
158        self
159    }
160
161    /// Returns the bytes that this configuration contributes to the [registry
162    /// digest](crate::model::digest).
163    ///
164    /// The bytes contain every field of every replacement counter style.
165    /// Therefore two configurations that differ in any field give different
166    /// bytes.
167    pub fn digest_bytes(&self) -> Vec<u8> {
168        let mut out = Vec::new();
169        out.extend_from_slice(&(self.styles.len() as u64).to_le_bytes());
170        for style in &self.styles {
171            digest_style(&mut out, style);
172        }
173        out
174    }
175}
176
177impl Hash for NumberingConfig {
178    fn hash<H: Hasher>(&self, state: &mut H) {
179        state.write(&self.digest_bytes());
180    }
181}
182
183/// Writes the counter style declaration `style` into `out`, as part of a
184/// registry digest. Every field is written, and each text is preceded by its
185/// length. The citations feature also uses this function for the counter
186/// style of its own configuration.
187pub(crate) fn digest_style(out: &mut Vec<u8>, style: &CounterStyleDecl) {
188    digest_text(out, style.name.as_str());
189    digest_text(out, style.number_format.text());
190    out.push(u8::from(matches!(
191        style.number_format,
192        NumberTemplate::Initial(_)
193    )));
194    out.extend_from_slice(&(style.sub_levels.len() as u64).to_le_bytes());
195    for level in &style.sub_levels {
196        digest_text(out, &level.separator);
197        digest_text(out, level.number_format.text());
198        out.push(u8::from(matches!(
199            level.number_format,
200            NumberTemplate::Initial(_)
201        )));
202    }
203    digest_text(out, &style.prefix_words.base.one);
204    digest_text(out, &style.prefix_words.base.other);
205    out.extend_from_slice(&(style.prefix_words.variants.len() as u64).to_le_bytes());
206    for (name, words) in &style.prefix_words.variants {
207        digest_text(out, name);
208        digest_text(out, &words.one);
209        digest_text(out, &words.other);
210    }
211    digest_text(out, &style.delimiters.open);
212    digest_text(out, &style.delimiters.close);
213    style.join.digest_into(out);
214    out.push(u8::from(style.name_in_link));
215    out.push(u8::from(style.repeat_parents_in_range));
216    out.push(u8::from(style.ranges));
217    out.push(u8::from(style.number_writer.is_some()));
218    digest_text(out, style.number_writer.as_ref().map_or("", Name::as_str));
219}
220
221/// The place of a counter in the hierarchy of counters: the counters within
222/// which the counter may be numbered, and whether its parent restarts its
223/// count.
224#[derive(Clone, Debug, Default)]
225pub(super) struct Hierarchy {
226    /// The counters within which the counter may be numbered, in the declared
227    /// order. If the list contains several counters, the parent at a
228    /// reference point is the one advanced most recently. The list is empty
229    /// for a counter that is numbered within nothing.
230    pub(super) parents: Vec<Name>,
231    /// If `true`, the parent does not restart the count of the counter (see
232    /// [`Within::no_restart`]).
233    pub(super) no_restart: bool,
234}
235
236/// The declarations of the numbering feature, checked and compiled when the
237/// registry is built.
238///
239/// The late-initialization hook [`Compile`] creates this value once, and the
240/// numbering stage reads it in every run.
241pub(super) struct Compiled {
242    /// The declared counters, by name.
243    pub(super) counters: BTreeMap<Name, CounterDecl>,
244    /// The place of each counter in the declared hierarchy, by counter name. A
245    /// counter that is numbered within nothing has no entry.
246    pub(super) hierarchy: BTreeMap<Name, Hierarchy>,
247    /// The declared parent sets, by name, each with its counters. These
248    /// parent sets can be used in the numbering options of a document.
249    pub(super) parent_sets: BTreeMap<Name, Vec<Name>>,
250    /// The compiled counter styles, by name, with the replacements of
251    /// [`NumberingConfig`] applied. The map is shared through an `Arc` because
252    /// the counter table of every run contains it
253    /// ([`Counters::style`](super::Counters::style)).
254    pub(super) styles: Arc<BTreeMap<Name, Arc<CounterStyle>>>,
255    /// The compiled within-joiner of each counter, by counter name. The
256    /// within-joiner writes the numbers of the ancestors of the counter before
257    /// the number of the counter. A counter that is numbered within nothing
258    /// has no entry.
259    pub(super) within: BTreeMap<Name, Arc<dyn CompiledWithinJoiner>>,
260    /// The compiled nesting joiner of each counter, by counter name. Every
261    /// counter has an entry. The nesting joiner writes the number of the
262    /// enclosing instance before the number of a reference point in a nested
263    /// scoped instance of the counter. For a counter declared without a
264    /// nesting joiner, the entry writes nothing.
265    pub(super) nesting: BTreeMap<Name, Arc<dyn CompiledWithinJoiner>>,
266    /// The within-joiners declared by name in the registry, by name. These
267    /// within-joiners can be selected by name in the numbering options of a
268    /// document.
269    pub(super) joiners: BTreeMap<Name, Arc<dyn WithinJoiner>>,
270    /// The template language with which the templates of the counter styles
271    /// and of the within-joiners are compiled. The numbering stage also
272    /// compiles with it the templates given in the numbering options of a
273    /// document and the number template of a reference point.
274    pub(super) language: TemplateLanguage,
275    /// The names of all declared counters, in name order. These counters can
276    /// be referred to in a within template.
277    pub(super) names: Vec<Name>,
278}
279
280/// The state of one registration of the numbering feature, shared by the
281/// finalizer [`Validate`], the late-initialization hook [`Compile`] and the
282/// numbering stage. The finalizer stores the checked declarations, and the
283/// hook stores the compiled declarations ([`Compiled`]).
284///
285/// Each call of [`register`](FlmFeature::register) creates its own `Shared`
286/// value. Therefore one [`Numbering`] value registered into two registries
287/// has a separate state in each registry.
288#[derive(Default)]
289pub(super) struct Shared {
290    declared: OnceLock<Declared>,
291    compiled: OnceLock<Compiled>,
292}
293
294impl Shared {
295    /// Returns the compiled declarations, or `None` before the
296    /// late-initialization hook has run.
297    pub(super) fn compiled(&self) -> Option<&Compiled> {
298        self.compiled.get()
299    }
300}
301
302/// The declarations of the numbering feature, after the checks of the
303/// finalizer [`Validate`]. The late-initialization hook [`Compile`] compiles
304/// them.
305struct Declared {
306    counters: BTreeMap<Name, CounterDecl>,
307    hierarchy: BTreeMap<Name, Hierarchy>,
308    parent_sets: BTreeMap<Name, Vec<Name>>,
309    styles: BTreeMap<Name, CounterStyleDecl>,
310    joiners: BTreeMap<Name, Arc<dyn WithinJoiner>>,
311    writers: Vec<Arc<dyn NumberWriter>>,
312}
313
314/// The `numbering` feature, which numbers the reference points of a document,
315/// such as headings, equations and theorems, with counters.
316///
317/// The counters, the counter styles, the within-joiners, the number writers
318/// and the parent sets are declared in other features, in the five service
319/// slots of this feature. The feature checks these declarations when the
320/// registry is built, and the registry build fails if a declaration contains
321/// a mistake. For each document, the numbering stage
322/// [`NUMBER`](super::NUMBER) numbers the reference points and writes their
323/// numbers to the counter table [`COUNTERS`]. The numbering of a document can
324/// be changed with the option type [`NumberingOptions`].
325///
326/// Create the feature with [`Numbering::new`] and a [`NumberingConfig`], or
327/// with [`feature()`] for the default configuration. The [module
328/// documentation](super) describes the feature in full.
329#[derive(Debug, Clone, Default)]
330pub struct Numbering {
331    config: NumberingConfig,
332}
333
334impl Numbering {
335    /// Returns the feature, configured with `config`.
336    pub fn new(config: NumberingConfig) -> Numbering {
337        Numbering { config }
338    }
339}
340
341impl FlmFeature for Numbering {
342    fn info(&self) -> FeatureInfo {
343        FeatureInfo::new(FEATURE, "Numbering").docs(
344            "The numbers of headings, equations, theorems and other reference points of a \
345             document. Each reference point that has a number source is numbered with a \
346             counter, in document order, and its number is written in a counter style. \
347             Counters, counter styles, within-joiners, number writers and parent sets are \
348             declared in other features, in the five service slots of this feature. The \
349             numbering of a document can be changed with its numbering options. The numbers \
350             are written to the table `flm.counters`.",
351        )
352    }
353
354    fn settings(&self) -> Option<SettingsDecl> {
355        Some(settings())
356    }
357
358    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
359        let shared = Arc::new(Shared::default());
360        b.service_slot::<CounterDecl>(
361            COUNTERS_SLOT,
362            Arity::OrderedMany,
363            "The counters with which reference points are numbered, one value per counter. \
364             A value contains the name of the counter, the default counter style of its \
365             numbers, and the counters within which it is numbered.",
366        )?;
367        b.service_slot::<CounterStyleDecl>(
368            STYLES_SLOT,
369            Arity::OrderedMany,
370            "The counter styles in which numbers are written, one value per counter style. \
371             A value contains the number format, the sub-levels, the word before the number, \
372             the delimiters and the texts that join several numbers.",
373        )?;
374        b.service_slot::<WithinJoinerDecl>(
375            WITHIN_JOINERS_SLOT,
376            Arity::OrderedMany,
377            "The within-joiners that can be selected by name, one value per within-joiner. \
378             A within-joiner is code that writes the numbers of the counters within which a \
379             counter is numbered, before the number of the counter.",
380        )?;
381        b.service_slot::<NumberWriterDecl>(
382            NUMBER_WRITERS_SLOT,
383            Arity::OrderedMany,
384            "The number writers that can be selected by name in a counter style, one value \
385             per number writer. A number writer is code that writes counter values as \
386             content, for the counter styles in which it is selected.",
387        )?;
388        b.service_slot::<ParentSetDecl>(
389            PARENT_SETS_SLOT,
390            Arity::OrderedMany,
391            "The parent sets, one value per parent set. A parent set is a named list of \
392             counters within which a counter can be numbered. At each reference point, the \
393             counter of the set that was advanced most recently is the parent.",
394        )?;
395        b.table(
396            COUNTERS,
397            "The numbers of the reference points of a document. For each numbered reference \
398             point, the table contains its counter, its counter value, the values of the \
399             counters within which it is numbered, and its counter style.",
400        )?;
401        b.stage(Arc::new(NumberStage::new(Arc::clone(&shared))))?;
402        b.digest_input(&self.config.digest_bytes())?;
403        b.finalizer(Arc::new(Validate { shared, config: self.config.clone() }))?;
404        Ok(())
405    }
406}
407
408/// Returns the [`Numbering`] feature with the default configuration, which
409/// contains no replacement counter style. You can pass the result to
410/// [`PackageEntry::feature`](crate::core::registry::PackageEntry::feature) to
411/// add the feature to a package.
412pub fn feature() -> Arc<dyn FlmFeature> {
413    Arc::new(Numbering::default())
414}
415
416/// The finalizer of the numbering feature, which runs once every feature has
417/// registered.
418///
419/// The finalizer reads the declarations from the five service slots of the
420/// feature, and applies the replacement counter styles of
421/// [`NumberingConfig`]. It checks that no name is declared twice, that no
422/// counter or parent set has a name that begins with `_`
423/// ([`RESERVED_PREFIX`]), that every name used in a declaration is declared,
424/// and that no counters are numbered within each other. At the first mistake,
425/// the finalizer returns an error, and the registry build fails. Finally, the
426/// finalizer stores the
427/// checked declarations in [`Shared`] and registers the late-initialization
428/// hook [`Compile`].
429struct Validate {
430    shared: Arc<Shared>,
431    config: NumberingConfig,
432}
433
434impl Validate {
435    /// Returns the error with the message `detail`, attributed to the
436    /// numbering feature, with which the registry build fails.
437    fn refuse(&self, b: &FeatureBuilder<'_>, detail: String) -> BuildError {
438        BuildError::Feature { feature: b.feature().clone(), detail }
439    }
440}
441
442impl Finalizer for Validate {
443    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
444        let services = b.services().expect("a finalizer runs after the slots are assembled");
445
446        let mut styles: BTreeMap<Name, CounterStyleDecl> = BTreeMap::new();
447        for style in services.services_named::<CounterStyleDecl>(STYLES_SLOT) {
448            if styles.insert(style.name.clone(), style.clone()).is_some() {
449                return Err(self.refuse(
450                    b,
451                    format!("Duplicate declaration of counter style ‘{}’", style.name),
452                ));
453            }
454        }
455        for replacement in &self.config.styles {
456            if !styles.contains_key(&replacement.name) {
457                return Err(self.refuse(
458                    b,
459                    format!(
460                        "Invalid replacement for undeclared counter style ‘{}’",
461                        replacement.name
462                    ),
463                ));
464            }
465            styles.insert(replacement.name.clone(), replacement.clone());
466        }
467
468        let mut joiners: BTreeMap<Name, Arc<dyn WithinJoiner>> = BTreeMap::new();
469        for declared in services.services_named::<WithinJoinerDecl>(WITHIN_JOINERS_SLOT) {
470            let joiner = declared.joiner();
471            if joiners.insert(joiner.name().clone(), Arc::clone(joiner)).is_some() {
472                return Err(self.refuse(
473                    b,
474                    format!("Duplicate declaration of within-joiner ‘{}’", joiner.name()),
475                ));
476            }
477        }
478
479        let mut writers: Vec<Arc<dyn NumberWriter>> = Vec::new();
480        for declared in services.services_named::<NumberWriterDecl>(NUMBER_WRITERS_SLOT) {
481            let writer = declared.writer();
482            if writers.iter().any(|other| other.name() == writer.name()) {
483                return Err(self.refuse(
484                    b,
485                    format!("Duplicate declaration of number writer ‘{}’", writer.name()),
486                ));
487            }
488            writers.push(Arc::clone(writer));
489        }
490        for style in styles.values() {
491            let Some(name) = &style.number_writer else { continue };
492            if !writers.iter().any(|writer| writer.name() == name) {
493                return Err(self.refuse(
494                    b,
495                    format!(
496                        "Unknown number writer ‘{name}’ of counter style ‘{}’",
497                        style.name
498                    ),
499                ));
500            }
501        }
502
503        let mut counters: BTreeMap<Name, CounterDecl> = BTreeMap::new();
504        for counter in services.services_named::<CounterDecl>(COUNTERS_SLOT) {
505            if counter.name.as_str().starts_with(RESERVED_PREFIX) {
506                return Err(self.refuse(b, format!(
507                    "Invalid counter name ‘{}’: counter names may not begin with \
508                     ‘{RESERVED_PREFIX}’",
509                    counter.name
510                )));
511            }
512            if counters.insert(counter.name.clone(), counter.clone()).is_some() {
513                return Err(self.refuse(
514                    b,
515                    format!("Duplicate declaration of counter ‘{}’", counter.name),
516                ));
517            }
518        }
519
520        let mut parent_sets: BTreeMap<Name, Vec<Name>> = BTreeMap::new();
521        for set in services.services_named::<ParentSetDecl>(PARENT_SETS_SLOT) {
522            if set.name.as_str().starts_with(RESERVED_PREFIX) {
523                return Err(self.refuse(b, format!(
524                    "Invalid parent set name ‘{}’: parent set names may not begin \
525                     with ‘{RESERVED_PREFIX}’",
526                    set.name
527                )));
528            }
529            if let Some(unknown) = set.counters.iter().find(|name| !counters.contains_key(*name)) {
530                return Err(self.refuse(b, format!(
531                    "Unknown counter ‘{unknown}’ in parent set ‘{}’",
532                    set.name
533                )));
534            }
535            if parent_sets.insert(set.name.clone(), set.counters.clone()).is_some() {
536                return Err(self.refuse(
537                    b,
538                    format!("Duplicate declaration of parent set ‘{}’", set.name),
539                ));
540            }
541        }
542
543        let mut hierarchy: BTreeMap<Name, Hierarchy> = BTreeMap::new();
544        for counter in counters.values() {
545            if let Some(WithinJoinerSpec::Named(name)) = &counter.nesting {
546                if !joiners.contains_key(name) {
547                    return Err(self.refuse(
548                        b,
549                        format!(
550                            "Unknown within-joiner ‘{name}’ for the nesting joiner of \
551                             counter ‘{}’",
552                            counter.name
553                        ),
554                    ));
555                }
556            }
557            if !styles.contains_key(&counter.default_style) {
558                return Err(self.refuse(
559                    b,
560                    format!(
561                        "Unknown default counter style ‘{}’ of counter ‘{}’",
562                        counter.default_style, counter.name
563                    ),
564                ));
565            }
566            let Some(within) = &counter.within else { continue };
567            let parents = within.parents.resolve(&parent_sets).map_err(|error| {
568                self.refuse(b, match (error, &within.parents) {
569                    (ParentsError::UnknownSet(set), _) => format!(
570                        "Unknown parent set ‘{set}’ for counter ‘{}’",
571                        counter.name
572                    ),
573                    (ParentsError::Empty, Parents::Set(set)) => format!(
574                        "Empty parent set ‘{set}’ for counter ‘{}’",
575                        counter.name
576                    ),
577                    (ParentsError::Empty, _) => format!(
578                        "Empty list of parent counters for counter ‘{}’",
579                        counter.name
580                    ),
581                })
582            })?;
583            if let Some(unknown) = parents.iter().find(|name| !counters.contains_key(*name)) {
584                return Err(self.refuse(
585                    b,
586                    format!(
587                        "Unknown parent counter ‘{unknown}’ for counter ‘{}’",
588                        counter.name
589                    ),
590                ));
591            }
592            if let WithinJoinerSpec::Named(name) = &within.joiner {
593                if !joiners.contains_key(name) {
594                    return Err(self.refuse(
595                        b,
596                        format!(
597                            "Unknown within-joiner ‘{name}’ for counter ‘{}’",
598                            counter.name
599                        ),
600                    ));
601                }
602            }
603            hierarchy.insert(
604                counter.name.clone(),
605                Hierarchy { parents, no_restart: within.no_restart },
606            );
607        }
608
609        for counter in counters.keys() {
610            chains_of(counter, &|name| parents_of(&hierarchy, name)).map_err(|cycle| {
611                let quoted: Vec<String> =
612                    cycle.iter().map(|name| format!("‘{name}’")).collect();
613                self.refuse(
614                    b,
615                    format!(
616                        "Circular hierarchy of counters (counters concerned: {})",
617                        quoted.join(", ")
618                    ),
619                )
620            })?;
621        }
622
623        // Which counters a joiner writes is known only once it is compiled — a
624        // template's names are read off the compiled template — so the check
625        // that a counter names only counters it may be numbered within is made
626        // by the late-initialization hook, which also fails the build.
627        let declared = Declared { counters, hierarchy, parent_sets, styles, joiners, writers };
628        let compile = Compile { shared: Arc::clone(&self.shared) };
629        if self.shared.declared.set(declared).is_err() {
630            return Err(self.refuse(
631                b,
632                "Finalizer of feature ‘numbering’ called twice for one registration"
633                    .into(),
634            ));
635        }
636        b.late_init(Arc::new(compile))?;
637        Ok(())
638    }
639}
640
641/// Returns the counters within which the counter `name` may be numbered in the
642/// declared hierarchy `hierarchy`. Returns an empty list for a counter that
643/// `hierarchy` does not contain. During the registry build, this function is
644/// passed to [`chains_of`].
645fn parents_of(hierarchy: &BTreeMap<Name, Hierarchy>, name: &Name) -> Vec<Name> {
646    hierarchy.get(name).map(|entry| entry.parents.clone()).unwrap_or_default()
647}
648
649/// The late-initialization hook of the numbering feature, which runs once the
650/// language that documents are parsed with is built.
651///
652/// The hook compiles the counter styles, each with the number writer selected
653/// in it. It also compiles the within-joiner and the nesting joiner of each
654/// counter. It then checks that each within-joiner and each nesting joiner
655/// writes only the numbers of ancestors of the counter. A counter with several
656/// possible parents has several possible chains of ancestors ([`chains_of`]),
657/// and a counter that a joiner writes must be in each of these chains (see
658/// [`written_outside`] and [`nesting_outside`]). Finally, the hook stores the
659/// compiled declarations ([`Compiled`]) in [`Shared`].
660///
661/// If a text is not valid FLM or does not compile, the hook returns an error,
662/// and the registry build fails. A counter style is configuration, so a mistake in it is reported
663/// once, when the registry is built, and not in every document. The warnings
664/// reported while the counter styles are compiled are added to the build
665/// diagnostics of the registry.
666struct Compile {
667    shared: Arc<Shared>,
668}
669
670impl LateInit for Compile {
671    fn late_init(&self, lang: &BuiltLang, diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
672        let Some(declared) = self.shared.declared.get() else { return Ok(()) };
673        let language = TemplateLanguage::new(lang).map_err(|errors| {
674            LateInitError::new(format!(
675                "Failed to build the template language of the numbering feature: {}",
676                errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
677            ))
678        })?;
679        let mut styles = BTreeMap::new();
680        for (name, decl) in &declared.styles {
681            let style = decl
682                .compile_with(lang, &language, &declared.writers)
683                .map_err(|error| {
684                    LateInitError::new(format!("Invalid counter style ‘{name}’: {error}"))
685                })?;
686            for warning in style.warnings() {
687                diags.push(warning.clone());
688            }
689            styles.insert(name.clone(), Arc::new(style));
690        }
691        let names: Vec<Name> = declared.counters.keys().cloned().collect();
692        let cx = WithinCx::new(lang, &language, &names, &declared.joiners);
693        let mut within = BTreeMap::new();
694        for (name, decl) in &declared.counters {
695            let Some(declared_within) = &decl.within else { continue };
696            let joiner = compile_within(declared_within, name.as_str(), &cx).map_err(|error| {
697                LateInitError::new(format!(
698                    "Invalid within-joiner of counter ‘{name}’: {error}"
699                ))
700            })?;
701            // Under every chain the counter may have, the joiner may write only
702            // counters of that chain: the check is made here, where the joiner
703            // can be asked, and it fails the build as every other mistake in a
704            // declaration does.
705            if let Some(named) = written_outside(joiner.as_ref(), name, |counter| {
706                parents_of(&declared.hierarchy, counter)
707            }) {
708                return Err(LateInitError::new(format!(
709                    "Invalid reference to counter ‘{named}’ in the within-joiner of counter \
710                     ‘{name}’: ‘{name}’ is not always numbered within ‘{named}’"
711                )));
712            }
713            within.insert(name.clone(), joiner);
714        }
715        let mut nesting = BTreeMap::new();
716        for (name, decl) in &declared.counters {
717            let joiner = compile_nesting(decl, &cx).map_err(|error| {
718                LateInitError::new(format!(
719                    "Invalid nesting joiner of counter ‘{name}’: {error}"
720                ))
721            })?;
722            if let Some(named) = nesting_outside(joiner.as_ref(), name, |counter| {
723                parents_of(&declared.hierarchy, counter)
724            }) {
725                return Err(LateInitError::new(format!(
726                    "Invalid reference to counter ‘{named}’ in the nesting joiner of counter \
727                     ‘{name}’: ‘{name}’ is not always numbered within ‘{named}’"
728                )));
729            }
730            nesting.insert(name.clone(), joiner);
731        }
732        // The hook is registered once per registration of the feature, the
733        // finalizer refusing a second registration into one registry, so the
734        // cell is empty here. Were it ever called twice, what the stage reads
735        // stays the first whole compilation rather than becoming half of two.
736        let _ = self.shared.compiled.set(Compiled {
737            counters: declared.counters.clone(),
738            hierarchy: declared.hierarchy.clone(),
739            parent_sets: declared.parent_sets.clone(),
740            styles: Arc::new(styles),
741            within,
742            nesting,
743            joiners: declared.joiners.clone(),
744            language,
745            names,
746        });
747        Ok(())
748    }
749}
750
751/// Checks the counters that the within-joiner `joiner` of the counter
752/// `counter` writes. Returns the first written counter that is missing from
753/// one of the chains of ancestors of `counter`, or `None` if every written
754/// counter is in every chain.
755///
756/// The chains of ancestors are computed by [`chains_of`], with `parents_of`
757/// as the hierarchy of counters. A counter with several possible parents has
758/// several chains, and `joiner` is checked with each chain. For instance, the
759/// joining text is written after the number of the parent of the chain, and
760/// `#{_parent}` is replaced by this number, so both are valid for every chain.
761/// A within template that contains the name of a counter, as in
762/// `#{flm.headings.section}`, is valid only if this counter is in every
763/// chain.
764///
765/// If the hierarchy contains a cycle, the function returns `None`, because
766/// the cycle is reported separately.
767pub(super) fn written_outside(
768    joiner: &dyn CompiledWithinJoiner,
769    counter: &Name,
770    parents_of: impl Fn(&Name) -> Vec<Name>,
771) -> Option<Name> {
772    let chains = chains_of(counter, &parents_of).ok()?;
773    chains.iter().find_map(|chain| {
774        joiner.counters_written(chain).into_iter().find(|named| !chain.contains(named))
775    })
776}
777
778/// Compiles the nesting joiner of the counter declared by `decl`. For a counter
779/// declared without a nesting joiner, the function compiles the bare form
780/// ([`WithinJoinerSpec::Bare`]), which writes nothing.
781///
782/// The nesting joiner is compiled as a within-joiner whose only parent is the
783/// counter itself, because the number that it writes is the number of the
784/// enclosing instance of the same counter. In the nesting joiner, `#{_parent}`
785/// and the name of the counter therefore both refer to the enclosing
786/// instance.
787///
788/// # Errors
789///
790/// Returns the error of [`compile_within`] if the nesting joiner cannot be
791/// compiled.
792pub(super) fn compile_nesting(
793    decl: &CounterDecl,
794    cx: &WithinCx<'_>,
795) -> Result<Arc<dyn CompiledWithinJoiner>, super::style::StyleError> {
796    let spec = decl.nesting.clone().unwrap_or(WithinJoinerSpec::Bare);
797    let within = Within { parents: Parents::One(decl.name.clone()), joiner: spec, no_restart: false };
798    compile_within(&within, decl.name.as_str(), cx)
799}
800
801/// Checks the counters that the nesting joiner `joiner` of the counter
802/// `counter` writes. Returns the first written counter that is missing from
803/// one of the chains of ancestors of a reference point in a nested instance
804/// of `counter`, or `None` if every written counter is in every chain.
805///
806/// For a reference point in a nested instance, each chain of ancestors is a
807/// chain of ancestors of `counter` followed by `counter` itself, for the
808/// enclosing instance. The chains of ancestors of `counter` are computed by
809/// [`chains_of`], with `parents_of` as the hierarchy of counters.
810///
811/// If the hierarchy contains a cycle, the function returns `None`, because
812/// the cycle is reported separately.
813pub(super) fn nesting_outside(
814    joiner: &dyn CompiledWithinJoiner,
815    counter: &Name,
816    parents_of: impl Fn(&Name) -> Vec<Name>,
817) -> Option<Name> {
818    let chains = chains_of(counter, &parents_of).ok()?;
819    chains.into_iter().find_map(|mut chain| {
820        chain.push(counter.clone());
821        joiner.counters_written(&chain).into_iter().find(|named| !chain.contains(named))
822    })
823}
824
825/// Reads a counter style from an entry of the settings key `styles`
826/// ([`NumberingConfig::styles`]). In settings data, `styles` is a map from the
827/// name of a counter style to its fields. The entry is read over the result of
828/// [`CounterStyleDecl::new`] for its name, so the fields missing from the entry
829/// keep the defaults of [`CounterStyleDecl::new`].
830impl crate::core::settings::named::NamedEntry for CounterStyleDecl {
831    fn read_entry(name: &str, data: serde_json::Value) -> Result<CounterStyleDecl, String> {
832        crate::core::settings::named::read_over(&CounterStyleDecl::new(name), "name", name, data)
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839
840    #[test]
841    fn the_declared_parents_are_the_ones_the_hierarchy_holds() {
842        let mut hierarchy = BTreeMap::new();
843        hierarchy.insert(
844            Name::new("equation"),
845            Hierarchy { parents: vec![Name::new("section"), Name::new("subsection")], no_restart: false },
846        );
847        assert_eq!(
848            parents_of(&hierarchy, &Name::new("equation")),
849            [Name::new("section"), Name::new("subsection")]
850        );
851        assert!(parents_of(&hierarchy, &Name::new("section")).is_empty());
852    }
853
854    #[test]
855    fn two_configurations_that_replace_different_texts_digest_differently() {
856        let one = NumberingConfig::new().style(CounterStyleDecl::new("a.style"));
857        let other = NumberingConfig::new().style(CounterStyleDecl::new("b.style"));
858        assert_ne!(one.digest_bytes(), other.digest_bytes());
859        assert_eq!(NumberingConfig::new().digest_bytes(), NumberingConfig::new().digest_bytes());
860    }
861}