Skip to main content

flm_core/stdlib/features/numbering/
style.rs

1//! Counter styles: the declaration ([`CounterStyleDecl`] and its parts), the
2//! compiled form ([`CounterStyle`]), and the writing of one value with it
3//! ([`format()`]), with the errors of compiling ([`StyleError`]) and of
4//! writing ([`FormatError`]).
5//!
6//! The module also holds what the writing shares with the rest of the
7//! numbering module: the counters a value is numbered within ([`Ancestor`],
8//! [`Parent`]), the options of a request ([`FormatOptions`]), the segments of
9//! the result ([`Segment`]), the assembly of content on a worker thread, and the
10//! join texts ([`JoinDecl`]), which the refs feature also uses for a
11//! reference to several targets.
12
13use std::collections::BTreeMap;
14use std::convert::Infallible;
15use std::fmt;
16use std::sync::Arc;
17
18use techy::core::node::{BuildId, NodeKind, NodeRef, NodeTree};
19use techy::core::{Lang, ParsingState};
20use techy::error::Severity;
21use techy::source::{SourceSpan, TextContent};
22use techy::transform::{Restage, RestageContext, RestageError, RestageVisitor};
23
24use crate::model::addr::NodeAddr;
25use crate::model::doc::FragmentLayout;
26use crate::model::names::Name;
27use crate::lang::guard::{self, GuardPolicy};
28use crate::lang::{
29    parse_fragment, BuiltLang, Flm, FlmDiagnostic, FlmOrigin, FlmSource, FlmSpan, ParseOptions,
30};
31
32use crate::lang::rewrites::userdefs::template::TemplateLanguage;
33
34use super::formats::{CompiledNumber, NumberFormat, NumberPart, NumberTemplate};
35use super::joiner::{CompiledWithinJoiner, JoinCx, Part};
36use super::template::{instantiate_template, Binding, Bindings};
37use super::value::CounterValue;
38use super::writer::{
39    default_writer, CompiledNumberWriter, JoinText, NumberOut, NumberWriter, NumberedValue,
40    WriteCx, WriterCx,
41};
42
43// --- errors ---------------------------------------------------------------------------------
44
45/// Why a counter style, a within-joiner or a number writer could not be
46/// compiled.
47///
48/// The numbering feature compiles once, when the registry is built, so each of
49/// these errors reveals a mistake in a declaration or in configuration. The
50/// numbering stage also compiles the within-joiners of a document's numbering
51/// options and a point's own number template; there, an error is reported as
52/// a diagnostic of the document.
53#[derive(Clone, Debug)]
54pub enum StyleError {
55    /// A template did not compile: it is not valid FLM, it holds a `#{…}`
56    /// whose name the template does not accept (a name that is not a number
57    /// format, a counter no feature declares), or it puts keys in brackets on
58    /// a name that accepts none.
59    Template {
60        /// The template, as it was declared.
61        text: String,
62        /// What the compilation reported.
63        diagnostics: Vec<FlmDiagnostic>,
64    },
65    /// A `#[…]{counter}` of a within template carries a key that is neither
66    /// `bare` nor the name of a number format.
67    UnknownKey {
68        /// The template that holds the key.
69        text: String,
70        /// The key, as it was written.
71        key: String,
72    },
73    /// A counter is numbered within another through a within-joiner name that
74    /// no feature registers.
75    UnknownJoiner {
76        /// The name the counter asked for.
77        name: Name,
78    },
79    /// A counter style asks for a number writer that no feature registers.
80    UnknownWriter {
81        /// The name the counter style asked for.
82        name: Name,
83    },
84    /// A `${…}` of a join text refers to a name that is not a join key.
85    UnknownVariable {
86        /// The join text that holds the substitution.
87        text: String,
88        /// The name written between the braces.
89        name: String,
90    },
91    /// A text of the counter style is not valid FLM: the parse reported
92    /// errors.
93    Parse {
94        /// The text, as it was declared. A single-letter number template is
95        /// cut at its letter and parsed in pieces, and the error gives the
96        /// whole template, as its author wrote it.
97        text: String,
98        /// The parse's errors.
99        diagnostics: Vec<FlmDiagnostic>,
100    },
101    /// A text of the counter style could not be parsed at all: it nests too
102    /// deeply, or no worker thread was available.
103    ParseFailed {
104        /// The text, as it was declared, given whole as in
105        /// [`Parse`](StyleError::Parse).
106        text: String,
107        /// What the parse reported.
108        detail: String,
109    },
110}
111
112impl StyleError {
113    /// Returns the same error, with `text` (a text as its author declared it)
114    /// in place of the piece of it that was being parsed. A single-letter
115    /// number template is cut at its letter, and nobody wrote the piece on
116    /// either side of the letter on its own.
117    pub(super) fn in_text(self, text: &str) -> StyleError {
118        let text = text.to_string();
119        match self {
120            StyleError::Template { diagnostics, .. } => StyleError::Template { text, diagnostics },
121            StyleError::UnknownKey { key, .. } => StyleError::UnknownKey { text, key },
122            StyleError::UnknownJoiner { name } => StyleError::UnknownJoiner { name },
123            StyleError::UnknownWriter { name } => StyleError::UnknownWriter { name },
124            StyleError::UnknownVariable { name, .. } => StyleError::UnknownVariable { text, name },
125            StyleError::Parse { diagnostics, .. } => StyleError::Parse { text, diagnostics },
126            StyleError::ParseFailed { detail, .. } => StyleError::ParseFailed { text, detail },
127        }
128    }
129}
130
131impl fmt::Display for StyleError {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        // The messages of the diagnostics of a text, after a colon.
134        let messages = |diagnostics: &[FlmDiagnostic]| {
135            let joined: Vec<String> =
136                diagnostics.iter().map(|diagnostic| diagnostic.message()).collect();
137            if joined.is_empty() { String::new() } else { format!(": {}", joined.join("; ")) }
138        };
139        match self {
140            StyleError::Template { text, diagnostics } => write!(
141                f,
142                "Invalid template ‘{text}’{}",
143                messages(diagnostics)
144            ),
145            StyleError::UnknownKey { text, key } => write!(
146                f,
147                "Invalid key ‘{key}’ in template ‘{text}’: keys in \
148                 brackets must be ‘bare’ or the name of a number format"
149            ),
150            StyleError::UnknownJoiner { name } => {
151                write!(f, "Unknown within-joiner ‘{name}’")
152            }
153            StyleError::UnknownWriter { name } => {
154                write!(f, "Unknown number writer ‘{name}’")
155            }
156            StyleError::UnknownVariable { text, name } => write!(
157                f,
158                "Unknown join key ‘{name}’ in join text ‘{text}’"
159            ),
160            StyleError::Parse { text, diagnostics } => write!(
161                f,
162                "Invalid FLM text ‘{text}’{}",
163                messages(diagnostics)
164            ),
165            StyleError::ParseFailed { text, detail } => {
166                write!(f, "Failed to parse ‘{text}’: {detail}")
167            }
168        }
169    }
170}
171
172impl std::error::Error for StyleError {}
173
174/// Why a number could not be written.
175///
176/// The first two variants say that a value and the counter style or the
177/// ancestors it is written with do not fit each other; the numbering stage
178/// refuses such a record when it makes it, so for a record of the counter
179/// table they reveal a fault in the program. The last two are failures of the
180/// writing itself, not of any input.
181#[derive(Clone, Debug)]
182pub enum FormatError {
183    /// A value has a sub-number at a level for which its counter style
184    /// declares no format.
185    UndeclaredSubLevel {
186        /// The counter style asked to write the value.
187        style: Name,
188        /// The sub-level, counted from zero for the first sub-number.
189        level: usize,
190        /// The sub-number at that level.
191        number: i64,
192    },
193    /// A within-joiner refers to a counter that is not among the ancestors it
194    /// was given. The within-joiner may be the point's own or, since an
195    /// ancestor is written with its own ancestors before it, an ancestor's.
196    UnknownAncestor {
197        /// The within-joiner that refers to the counter, as it was declared: a
198        /// joining text, a within template, or the description a registered
199        /// within-joiner gives of itself.
200        joiner: String,
201        /// The counter referred to.
202        counter: Name,
203    },
204    /// The content nests too deeply to be copied into the result.
205    NestingTooDeep {
206        /// What the recursion guard reported.
207        detail: String,
208    },
209    /// Building the result failed, or no worker thread was available. This
210    /// reveals a fault in the program or a refusal of the operating system,
211    /// not a problem of any input.
212    Failed {
213        /// What failed.
214        detail: String,
215    },
216}
217
218impl fmt::Display for FormatError {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        match self {
221            FormatError::UndeclaredSubLevel { style, level, number } => write!(
222                f,
223                "the counter style `{style}` must declare a format for sub-level {level} \
224                 (counting the first sub-level as 0), since the value has the sub-number \
225                 {number} there"
226            ),
227            FormatError::UnknownAncestor { joiner, counter } => write!(
228                f,
229                "the within-joiner `{joiner}` may write only counters this number is numbered \
230                 within, but it writes the counter `{counter}`"
231            ),
232            FormatError::NestingTooDeep { detail } => {
233                write!(f, "the content nests too deeply to write a number with: {detail}")
234            }
235            FormatError::Failed { detail } => write!(f, "writing the number failed: {detail}"),
236        }
237    }
238}
239
240impl std::error::Error for FormatError {}
241
242// --- what a feature declares ----------------------------------------------------------------
243
244/// The delimiters of a counter style: the text before and the text after a
245/// number, such as `(` and `)` for an equation number shown as `(3)`.
246///
247/// Both are FLM, and both are left out when a number is asked for without
248/// delimiters ([`FormatOptions::without_delimiters`]).
249#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
250#[derive(schemars::JsonSchema)]
251#[serde(default, deny_unknown_fields)]
252pub struct Delimiters {
253    /// The text written before the number.
254    pub open: String,
255    /// The text written after the number.
256    pub close: String,
257}
258
259impl Delimiters {
260    /// Returns the delimiters `open` and `close`.
261    pub fn new(open: impl Into<String>, close: impl Into<String>) -> Delimiters {
262        Delimiters { open: open.into(), close: close.into() }
263    }
264}
265
266/// The word written before a number, in two forms: one for a single number
267/// and one for several.
268///
269/// The fields are named after the plural categories `one` and `other` of
270/// natural-language pluralization: `Eq.~` for one equation, `Eqs.~` for
271/// several. Both are FLM, so `~` and a text style mean in them what they mean
272/// in a document.
273#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
274#[derive(schemars::JsonSchema)]
275#[serde(default, deny_unknown_fields)]
276pub struct PluralWords {
277    /// The word written before a single number.
278    pub one: String,
279    /// The word written before several numbers.
280    pub other: String,
281}
282
283impl PluralWords {
284    /// Returns the words `one`, for a single number, and `other`, for
285    /// several.
286    pub fn new(one: impl Into<String>, other: impl Into<String>) -> PluralWords {
287        PluralWords { one: one.into(), other: other.into() }
288    }
289
290    /// Returns the same word for one number and for several.
291    pub fn same(word: impl Into<String>) -> PluralWords {
292        let word = word.into();
293        PluralWords { one: word.clone(), other: word }
294    }
295}
296
297/// The prefix words of a counter style: the words written before a number by
298/// default, and the named variants that a request may ask for instead.
299///
300/// A variant is a complete pair of words under a name of its own, such as
301/// `capital`, holding `Equation~` and `Equations~` where the default words are
302/// `Eq.~` and `Eqs.~`. A request for a variant the counter style does not
303/// declare ([`FormatOptions::variant`]) gets the default words; the refs
304/// feature reports such a request at the reference as an Error.
305#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
306#[derive(schemars::JsonSchema)]
307#[serde(default, deny_unknown_fields)]
308pub struct PrefixWords {
309    /// The words used when no variant is asked for, and when the variant asked
310    /// for is not declared.
311    pub base: PluralWords,
312    /// The variants, by name.
313    pub variants: BTreeMap<String, PluralWords>,
314}
315
316impl PrefixWords {
317    /// Returns the default words `one` and `other`, with no variant.
318    pub fn new(one: impl Into<String>, other: impl Into<String>) -> PrefixWords {
319        PrefixWords { base: PluralWords::new(one, other), variants: BTreeMap::new() }
320    }
321
322    /// Returns these prefix words with the variant `variant` added under
323    /// `name`.
324    pub fn with_variant(mut self, name: impl Into<String>, variant: PluralWords) -> PrefixWords {
325        self.variants.insert(name.into(), variant);
326        self
327    }
328}
329
330/// A sub-level of a counter style: how the sub-numbers at one level are
331/// written, and the separator written before each.
332///
333/// A counter style with one sub-level, declared as letters after a full stop,
334/// writes the value `(3, 2)` as `3.b`. The separator is FLM; it is left out
335/// when nothing has been written before the sub-number, so that the end of a
336/// range is written `b` and not `.b`.
337#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize, serde::Serialize)]
338#[derive(schemars::JsonSchema)]
339#[serde(deny_unknown_fields)]
340pub struct SubLevelDecl {
341    /// The text written before this level's number, when something is
342    /// written before it.
343    pub separator: String,
344    /// How this level's number is written.
345    pub number_format: NumberTemplate,
346}
347
348impl SubLevelDecl {
349    /// Returns a sub-level written with `number_format` after `separator`.
350    pub fn new(separator: impl Into<String>, number_format: NumberTemplate) -> SubLevelDecl {
351        SubLevelDecl { separator: separator.into(), number_format }
352    }
353}
354
355/// The join texts of a counter style: the texts that join several numbers
356/// into one text, such as `1–3, 7, and 9`.
357///
358/// Every field is a text written between or around the numbers, and each may
359/// be left unset, in which case the default text is used (the defaults are
360/// given per field below). The texts are FLM. A `${name}` in one of them is
361/// replaced by the text of the key `name`, in one pass (a replaced text is not
362/// scanned again); the keys meant for this use are the four variables `and`,
363/// `sep`, `endash` and `empty`, so that a caller changes the word `and` once
364/// instead of in every join text that uses it. A `${name}` whose name is not a key fails the
365/// compilation of the counter style ([`StyleError::UnknownVariable`]).
366///
367/// Which fields are used depends on how many *runs* the numbers form, a run
368/// being one number or a sequence of consecutive numbers:
369///
370/// - one run: `one_pre`, the run, `one_post`;
371/// - two runs: `pair_pre`, the first, `pair_mid`, the second, `pair_post`;
372/// - more: `list_pre`, the runs separated by `list_mid`, `list_midlast`
373///   before the last one, `list_post`.
374///
375/// A run of several numbers is written as `range_pre`, the first number, then
376/// `range_pairmid` for a run of exactly two or `range_mid` for a longer one,
377/// then the last number, then `range_post`.
378///
379/// The refs feature uses the same declaration for the texts that join the
380/// targets of a reference to several targets.
381///
382/// # Examples
383///
384/// ```
385/// use flm_core::stdlib::features::numbering::JoinDecl;
386///
387/// // The default: `1–3, 7, and 9`.
388/// let spelled_out = JoinDecl::default();
389/// // The compact preset: `1–3,7,9`.
390/// let compact = JoinDecl::compact();
391/// // The default with another conjunction.
392/// let mut german = JoinDecl::default();
393/// german.and = Some("und".to_string());
394/// # let _ = (spelled_out, compact, german);
395/// ```
396#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
397#[derive(schemars::JsonSchema)]
398#[serde(default, deny_unknown_fields)]
399pub struct JoinDecl {
400    /// Before a single run. Default: empty.
401    pub one_pre: Option<String>,
402    /// After a single run. Default: empty.
403    pub one_post: Option<String>,
404    /// Before two runs. Default: empty.
405    pub pair_pre: Option<String>,
406    /// Between two runs. Default: ` ${and} `; compact: `,`.
407    pub pair_mid: Option<String>,
408    /// After two runs. Default: empty.
409    pub pair_post: Option<String>,
410    /// Before a run of several numbers. Default: empty.
411    pub range_pre: Option<String>,
412    /// Between the ends of a run of three or more. Default: `${endash}`.
413    pub range_mid: Option<String>,
414    /// Between the ends of a run of exactly two. Default: `${sep}`; compact:
415    /// `,`.
416    pub range_pairmid: Option<String>,
417    /// After a run of several numbers. Default: empty.
418    pub range_post: Option<String>,
419    /// Before three runs or more. Default: empty.
420    pub list_pre: Option<String>,
421    /// Between the runs of a list, except before the last. Default: `${sep} `;
422    /// compact: `,`.
423    pub list_mid: Option<String>,
424    /// Before the last run of a list. Default: `${sep} ${and} `; compact: `,`.
425    pub list_midlast: Option<String>,
426    /// After three runs or more. Default: empty.
427    pub list_post: Option<String>,
428    /// The variable `and`. Default: `and`.
429    pub and: Option<String>,
430    /// The variable `sep`. Default: `,`.
431    pub sep: Option<String>,
432    /// The variable `endash`. Default: `–`.
433    pub endash: Option<String>,
434    /// The text written when there is no number at all, and the variable
435    /// `empty`. Default: `(empty)`.
436    pub empty: Option<String>,
437}
438
439impl JoinDecl {
440    /// Returns every text the declaration carries, in the order of the fields
441    /// above, each `None` where the default text is used.
442    ///
443    /// A caller that must write out a whole declaration reads it through this
444    /// method, for example for a registry digest, which must change when any
445    /// one of these texts changes.
446    pub fn texts(&self) -> [&Option<String>; 17] {
447        [
448            &self.one_pre,
449            &self.one_post,
450            &self.pair_pre,
451            &self.pair_mid,
452            &self.pair_post,
453            &self.range_pre,
454            &self.range_mid,
455            &self.range_pairmid,
456            &self.range_post,
457            &self.list_pre,
458            &self.list_mid,
459            &self.list_midlast,
460            &self.list_post,
461            &self.and,
462            &self.sep,
463            &self.endash,
464            &self.empty,
465        ]
466    }
467
468    /// Writes every text of the declaration into `out`, for a registry
469    /// digest: per key whether it is set, then the text preceded by its
470    /// length, so that two different declarations never write the same bytes.
471    pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
472        for text in self.texts() {
473            out.push(u8::from(text.is_some()));
474            super::decl::digest_text(out, text.as_deref().unwrap_or(""));
475        }
476    }
477
478    /// Returns the compact join texts: the numbers separated by commas, with
479    /// no word between the last two and no space after a comma, `1–3,7,9`.
480    pub fn compact() -> JoinDecl {
481        JoinDecl {
482            pair_mid: Some(",".to_string()),
483            range_pairmid: Some(",".to_string()),
484            list_mid: Some(",".to_string()),
485            list_midlast: Some(",".to_string()),
486            ..JoinDecl::default()
487        }
488    }
489}
490
491/// A counter style, as a feature declares it.
492///
493/// A counter style says how a counter value is shown: the number template, the
494/// sub-levels, the prefix words with their variants, the delimiters and the
495/// join texts, each text written in FLM and parsed once, when the counter
496/// style is compiled against the built language
497/// ([`compile`](CounterStyleDecl::compile)) into a [`CounterStyle`]. It also
498/// holds three choices about links and ranges, and may ask for a number writer
499/// other than the default one. The concepts overview presents counters and
500/// counter styles together ([counters and counter
501/// styles](crate::guide::concepts_overview#counters-and-counter-styles)).
502///
503/// A feature contributes the declaration to the service slot
504/// [`STYLES_SLOT`](super::STYLES_SLOT); a counter refers to its default counter
505/// style by name ([`CounterDecl::default_style`](super::CounterDecl::default_style)),
506/// and a reference point gives the counter style of its number in its number
507/// source. A host replaces a declared counter style by name through
508/// [`NumberingConfig`](super::NumberingConfig).
509///
510/// A counter style's name is a dotted name owned by the feature that declares
511/// it, such as `flm.math.style.equation`, so that two features may each
512/// declare a counter style for the same counter without a clash.
513///
514/// # Examples
515///
516/// ```
517/// use flm_core::stdlib::features::numbering::{
518///     CounterStyleDecl, Delimiters, JoinDecl, NumberTemplate, PrefixWords,
519/// };
520///
521/// let mut style = CounterStyleDecl::new("flm.math.style.equation");
522/// style.number_format = NumberTemplate::formats("#{arabic}");
523/// style.delimiters = Delimiters::new("(", ")");
524/// style.prefix_words = PrefixWords::new("Eq.~", "Eqs.~")
525///     .with_variant("capital", flm_core::stdlib::features::numbering::PluralWords::new(
526///         "Equation~", "Equations~",
527///     ));
528/// style.join = JoinDecl::compact();
529/// ```
530///
531/// In data, no field is required: each field the data gives replaces that
532/// field of a base counter style, and every other field keeps the base's
533/// value. The base of an entry of
534/// [`NumberingConfig::styles`](super::NumberingConfig::styles) is the counter
535/// style that [`CounterStyleDecl::new`] returns for the entry's key, which is
536/// its name, not the declared counter style it replaces; the counter style in
537/// the citations feature's configuration takes that feature's default counter
538/// style as its base. The name is never written as a field.
539#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize, serde::Serialize)]
540#[derive(schemars::JsonSchema)]
541#[serde(deny_unknown_fields)]
542#[schemars(transform = style_schema)]
543pub struct CounterStyleDecl {
544    /// The counter style's name: dotted, owned by the feature that declares
545    /// it.
546    #[schemars(skip)]
547    pub name: Name,
548    /// The number template: how the number itself is written.
549    pub number_format: NumberTemplate,
550    /// The sub-levels, outermost first. A value cannot be written with a
551    /// sub-number at a level the counter style does not declare.
552    pub sub_levels: Vec<SubLevelDecl>,
553    /// The prefix words: the word written before the number.
554    pub prefix_words: PrefixWords,
555    /// The delimiters: the texts around the number.
556    pub delimiters: Delimiters,
557    /// The join texts: the texts that join several numbers.
558    pub join: JoinDecl,
559    /// Whether the word before the numbers is part of the link to the first
560    /// number written. With one number written by [`format()`], the whole
561    /// text is one link regardless of this setting. On by default.
562    pub name_in_link: bool,
563    /// Whether the end of a range repeats the part of the number that comes
564    /// from the counters it is numbered within: `A.I–A.III` instead of
565    /// `A.I–III`. Off by default.
566    pub repeat_parents_in_range: bool,
567    /// Whether consecutive numbers collapse into a range: `1–3` when on,
568    /// `1,2,3` when off. Several numbers are sorted in both cases, and when
569    /// off every number is written separately, each with a link of its own.
570    /// On by default.
571    pub ranges: bool,
572    /// The name of the [number writer](super::NumberWriter) that writes this
573    /// counter style's numbers, registered under that name in
574    /// [`NUMBER_WRITERS_SLOT`](super::NUMBER_WRITERS_SLOT), or `None` for the
575    /// default writer. A name no feature registers fails the registry build.
576    pub number_writer: Option<Name>,
577}
578
579/// Adjusts the schema of a counter style in data: no field is required, as
580/// the counter style is read over a base counter style.
581fn style_schema(schema: &mut schemars::Schema) {
582    crate::core::settings::named::require_only(schema, &[]);
583}
584
585impl CounterStyleDecl {
586    /// Returns a counter style named `name` that writes the number in decimal
587    /// digits (`#{arabic}`), with no sub-level, no word, no delimiters, the
588    /// default join texts, the word inside the link, no repeated ancestors'
589    /// part in a range, consecutive numbers collapsed into ranges, and the
590    /// default number writer.
591    pub fn new(name: impl Into<Name>) -> CounterStyleDecl {
592        CounterStyleDecl {
593            name: name.into(),
594            number_format: NumberTemplate::formats("#{arabic}"),
595            sub_levels: Vec::new(),
596            prefix_words: PrefixWords::default(),
597            delimiters: Delimiters::default(),
598            join: JoinDecl::default(),
599            name_in_link: true,
600            repeat_parents_in_range: false,
601            ranges: true,
602            number_writer: None,
603        }
604    }
605
606    /// Builder: this counter style's numbers are written by the number writer
607    /// registered under `name`.
608    ///
609    /// A counter style that asks for no writer is written by the default
610    /// writer, which writes what the counter style's own data describes. A
611    /// name no feature registers fails the registry build.
612    pub fn with_number_writer(mut self, name: impl Into<Name>) -> CounterStyleDecl {
613        self.number_writer = Some(name.into());
614        self
615    }
616
617    /// Returns this declaration compiled against the built language: every
618    /// text parsed once, every number template compiled, every join variable
619    /// replaced.
620    ///
621    /// A caller that writes numbers of its own, outside the numbering feature,
622    /// compiles a counter style with this method; the numbering feature
623    /// compiles every declared counter style itself when the registry is
624    /// built. This method knows no registered number writer, so it refuses a
625    /// declaration that asks for one ([`compile_with`](CounterStyleDecl::compile_with)
626    /// accepts them).
627    ///
628    /// # Errors
629    ///
630    /// The [`StyleError`] of the first text that is not valid FLM or that
631    /// refers to something that does not exist, and
632    /// [`StyleError::UnknownWriter`] for a declaration that asks for a number
633    /// writer.
634    pub fn compile(&self, lang: &BuiltLang) -> Result<CounterStyle, StyleError> {
635        let language = TemplateLanguage::new(lang).map_err(|errors| StyleError::ParseFailed {
636            text: self.number_format.text().to_string(),
637            detail: errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "),
638        })?;
639        self.compile_with(lang, &language, &[])
640    }
641
642    /// Returns this declaration compiled as [`compile`](CounterStyleDecl::compile)
643    /// does, with an already built template language and with the number
644    /// writers that features registered.
645    ///
646    /// A caller that compiles many counter styles builds the template language
647    /// once and passes it to each call. A declaration that asks for a writer
648    /// that none of `writers` has is refused with
649    /// [`StyleError::UnknownWriter`].
650    ///
651    /// # Errors
652    ///
653    /// The same as [`compile`](CounterStyleDecl::compile), and
654    /// [`StyleError::UnknownWriter`].
655    pub fn compile_with(
656        &self,
657        lang: &BuiltLang,
658        language: &TemplateLanguage,
659        writers: &[Arc<dyn NumberWriter>],
660    ) -> Result<CounterStyle, StyleError> {
661        let mut warnings = Vec::new();
662        let blank = parse_text("", lang, &mut warnings)?;
663        let number =
664            CompiledNumber::compile(&self.number_format, &self.name, lang, language, &mut warnings)?;
665        let mut sub_levels = Vec::with_capacity(self.sub_levels.len());
666        for level in &self.sub_levels {
667            sub_levels.push(CompiledSubLevel {
668                separator: parse_text(&level.separator, lang, &mut warnings)?,
669                number: CompiledNumber::compile(
670                    &level.number_format,
671                    &self.name,
672                    lang,
673                    language,
674                    &mut warnings,
675                )?,
676            });
677        }
678        let writer = match &self.number_writer {
679            None => Arc::clone(default_writer()),
680            Some(name) => {
681                let Some(declared) = writers.iter().find(|writer| writer.name() == name) else {
682                    return Err(StyleError::UnknownWriter { name: name.clone() });
683                };
684                declared.compile(&WriterCx::new(lang, &self.name))?
685            }
686        };
687        let words = CompiledWords {
688            base: compile_words(&self.prefix_words.base, lang, &mut warnings)?,
689            variants: self
690                .prefix_words
691                .variants
692                .iter()
693                .map(|(name, words)| {
694                    compile_words(words, lang, &mut warnings).map(|words| (name.clone(), words))
695                })
696                .collect::<Result<BTreeMap<_, _>, _>>()?,
697        };
698        Ok(CounterStyle {
699            name: self.name.clone(),
700            number,
701            sub_levels: Arc::new(sub_levels),
702            words: Arc::new(words),
703            open: parse_text(&self.delimiters.open, lang, &mut warnings)?,
704            close: parse_text(&self.delimiters.close, lang, &mut warnings)?,
705            join: Arc::new(CompiledJoin::compile(
706                &self.join,
707                STYLE_TEXT_ORIGIN,
708                lang,
709                &mut warnings,
710            )?),
711            name_in_link: self.name_in_link,
712            repeat_parents_in_range: self.repeat_parents_in_range,
713            ranges: self.ranges,
714            writer,
715            state: Arc::clone(lang.initial_state()),
716            blank,
717            warnings,
718        })
719    }
720}
721
722// --- what a declaration compiles to ---------------------------------------------------------
723
724/// One sub-level, compiled.
725struct CompiledSubLevel {
726    separator: Arc<NodeTree<Flm>>,
727    number: CompiledNumber,
728}
729
730/// One pair of words, compiled.
731struct CompiledPlural {
732    one: Arc<NodeTree<Flm>>,
733    other: Arc<NodeTree<Flm>>,
734}
735
736/// The words of a counter style, compiled.
737struct CompiledWords {
738    base: CompiledPlural,
739    variants: BTreeMap<String, CompiledPlural>,
740}
741
742/// The join texts of a counter style, compiled: the variables replaced and
743/// every text parsed.
744///
745/// The refs feature compiles the texts that join the targets of a reference
746/// to several targets into this same form, through the same
747/// [`compile`](CompiledJoin::compile), so that one [`JoinDecl`] means the same
748/// in both places.
749pub(crate) struct CompiledJoin {
750    pub(super) one_pre: Arc<NodeTree<Flm>>,
751    pub(super) one_post: Arc<NodeTree<Flm>>,
752    pub(super) pair_pre: Arc<NodeTree<Flm>>,
753    pub(super) pair_mid: Arc<NodeTree<Flm>>,
754    pub(super) pair_post: Arc<NodeTree<Flm>>,
755    pub(super) range_pre: Arc<NodeTree<Flm>>,
756    pub(super) range_mid: Arc<NodeTree<Flm>>,
757    pub(super) range_pairmid: Arc<NodeTree<Flm>>,
758    pub(super) range_post: Arc<NodeTree<Flm>>,
759    pub(super) list_pre: Arc<NodeTree<Flm>>,
760    pub(super) list_mid: Arc<NodeTree<Flm>>,
761    pub(super) list_midlast: Arc<NodeTree<Flm>>,
762    pub(super) list_post: Arc<NodeTree<Flm>>,
763    pub(super) empty: Arc<NodeTree<Flm>>,
764}
765
766/// A counter style compiled against the built language: what a number is
767/// written with.
768///
769/// It is built from a [`CounterStyleDecl`] by
770/// [`compile`](CounterStyleDecl::compile) or
771/// [`compile_with`](CounterStyleDecl::compile_with), holds the parsed form of
772/// every text of the declaration and the compiled number writer, and is
773/// passed to [`format()`] and [`format_many`](super::format_many). The counter
774/// table holds the compiled counter styles of a registry
775/// ([`Counters::style`](super::Counters::style)).
776pub struct CounterStyle {
777    name: Name,
778    number: CompiledNumber,
779    // Every compiled part but the number is shared, so that a style derived
780    // with another number format costs one compiled template.
781    sub_levels: Arc<Vec<CompiledSubLevel>>,
782    words: Arc<CompiledWords>,
783    open: Arc<NodeTree<Flm>>,
784    close: Arc<NodeTree<Flm>>,
785    join: Arc<CompiledJoin>,
786    name_in_link: bool,
787    repeat_parents_in_range: bool,
788    ranges: bool,
789    /// The writer of this counter style's numbers: the default writer, or the
790    /// one the declaration asks for.
791    writer: Arc<dyn CompiledNumberWriter>,
792    /// The language's initial parsing state, with which the text nodes of a
793    /// number's characters are built.
794    state: Arc<ParsingState<Flm>>,
795    /// The parse of the empty text: the tree a result is assembled against,
796    /// and the source the characters of a number are attributed to.
797    blank: Arc<NodeTree<Flm>>,
798    warnings: Vec<FlmDiagnostic>,
799}
800
801impl fmt::Debug for CounterStyle {
802    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803        f.debug_struct("CounterStyle").field("name", &self.name.as_str()).finish_non_exhaustive()
804    }
805}
806
807impl CounterStyle {
808    /// Returns the counter style's name, as the declaration gave it.
809    pub fn name(&self) -> &Name {
810        &self.name
811    }
812
813    /// Returns the diagnostics that the counter style's texts raised when
814    /// they were parsed. None of them is an error, since a text that parses
815    /// with an error is refused instead. The numbering feature adds them to
816    /// the registry's build diagnostics.
817    pub fn warnings(&self) -> &[FlmDiagnostic] {
818        &self.warnings
819    }
820
821    /// Returns a derived counter style: this counter style with its number
822    /// format replaced by `template`, with the same name, sub-levels, words,
823    /// delimiters, join texts, choices and number writer.
824    ///
825    /// Only `template` is compiled; every other part is shared with this
826    /// counter style. The numbering stage uses it for a point that carries a
827    /// number template of its own
828    /// ([`NumberSource::number_format`](crate::model::aspects::NumberSource::number_format)):
829    /// the point's record holds the derived counter style, so that the point's
830    /// number and every reference to it are written in it. The lists feature
831    /// also writes an item's label through a derived counter style
832    /// ([`Counters::format_in_style`](super::Counters::format_in_style)). The
833    /// [`warnings`](CounterStyle::warnings) of the derived counter style are
834    /// this counter style's, followed by those `template` raised.
835    ///
836    /// # Errors
837    ///
838    /// The [`StyleError`] of a template that does not compile, as
839    /// [`CounterStyleDecl::compile_with`] reports it for a declaration's
840    /// number template.
841    pub fn with_number_format(
842        &self,
843        template: &NumberTemplate,
844        lang: &BuiltLang,
845        language: &TemplateLanguage,
846    ) -> Result<CounterStyle, StyleError> {
847        let mut warnings = self.warnings.clone();
848        let number = CompiledNumber::compile(template, &self.name, lang, language, &mut warnings)?;
849        Ok(CounterStyle {
850            name: self.name.clone(),
851            number,
852            sub_levels: Arc::clone(&self.sub_levels),
853            words: Arc::clone(&self.words),
854            open: Arc::clone(&self.open),
855            close: Arc::clone(&self.close),
856            join: Arc::clone(&self.join),
857            name_in_link: self.name_in_link,
858            repeat_parents_in_range: self.repeat_parents_in_range,
859            ranges: self.ranges,
860            writer: Arc::clone(&self.writer),
861            state: Arc::clone(&self.state),
862            blank: Arc::clone(&self.blank),
863            warnings,
864        })
865    }
866
867    /// Returns whether the counter style declares the variant `name` of the
868    /// prefix words ([`PrefixWords::variants`]).
869    ///
870    /// A number asked for in a variant the counter style does not declare is
871    /// written with the default words; a caller that reports such a request,
872    /// as the refs feature does, checks it with this method.
873    pub fn declares_variant(&self, name: &str) -> bool {
874        self.words.variants.contains_key(name)
875    }
876
877    /// Returns how many sub-levels the counter style declares: the depth of
878    /// the deepest sub-number it can write, counting the first sub-level as 1.
879    ///
880    /// A value that carries a non-zero sub-number deeper than that cannot be
881    /// written in this counter style; the numbering stage checks this when it
882    /// makes a record, not when the number is shown.
883    pub fn sub_level_count(&self) -> usize {
884        self.sub_levels.len()
885    }
886
887    /// Returns `text` as a small tree of content, built as the characters of
888    /// a number are: one text node attributed to the counter style's source.
889    ///
890    /// A caller that writes several numbers itself builds the text between two
891    /// of them with this method: everything a reader sees is content, not
892    /// characters, and this module provides the only way to build content from
893    /// computed characters. The call runs on a worker thread.
894    ///
895    /// # Errors
896    ///
897    /// [`FormatError::NestingTooDeep`] or [`FormatError::Failed`] when the
898    /// content could not be built.
899    pub fn literal(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, FormatError> {
900        let pieces = [Piece::Digits(text.to_string())];
901        on_worker(|| assemble_pieces(self, &pieces))
902    }
903
904    /// Returns the empty span to which a number's computed content is
905    /// attributed: the start of the counter style's own source, where a
906    /// diagnostic about a number points.
907    pub(super) fn site(&self) -> FlmSpan {
908        let at: &FlmSpan = self.blank.root().span();
909        SourceSpan::new(at.source(), at.start()..at.start())
910    }
911
912    /// Returns the word to write before `count` numbers, `variant` being the
913    /// variant asked for. A variant the counter style does not declare gets
914    /// the default words; the refs feature reports such a request at the
915    /// reference as an Error.
916    fn word(&self, count: usize, variant: Option<&str>) -> &Arc<NodeTree<Flm>> {
917        let words = variant
918            .and_then(|variant| self.words.variants.get(variant))
919            .unwrap_or(&self.words.base);
920        if count == 1 {
921            &words.one
922        } else {
923            &words.other
924        }
925    }
926}
927
928// --- what a caller passes in ------------------------------------------------------------------
929
930/// An ancestor: one counter within which a number is numbered, as the
931/// numbering feature records it: the counter's name, its value at the
932/// numbered point, the counter style in which that value is written, and the
933/// within-joiner that writes that counter's own ancestors before it.
934///
935/// Because each ancestor carries its own within-joiner, a chain of counters is
936/// written one step at a time: a within-joiner that refers to
937/// `flm.headings.subsection` writes the
938/// subsection's number preceded by what the subsection's own within-joiner
939/// writes, `2.3.`, so a within-joiner refers only to the counter immediately
940/// above.
941///
942/// An ancestor counted in a scoped instance also records which instance, for
943/// example the enclosing list of an item of a nested list
944/// ([`instance`](Ancestor::instance)).
945#[derive(Clone, Debug)]
946pub struct Ancestor {
947    /// The counter's name.
948    pub counter: Name,
949    /// Its value at the numbered point.
950    pub value: CounterValue,
951    /// The counter style in which its value is written.
952    pub style: Arc<CounterStyle>,
953    /// The within-joiner that writes this counter's own ancestors before its
954    /// number, or `None` for a counter numbered within nothing. Those
955    /// ancestors are the ones before it in the list a [`Parent`] carries.
956    pub joiner: Option<Arc<dyn CompiledWithinJoiner>>,
957    /// The scoped instance this value was counted in, as the address of the
958    /// node the instance is attached to, or `None` for a value of the
959    /// counter's single sequence through the document. See
960    /// [`NumberSource::instances`](crate::model::aspects::NumberSource::instances).
961    pub instance: Option<NodeAddr>,
962}
963
964impl Ancestor {
965    /// Returns an ancestor numbered within nothing and counted in no scoped
966    /// instance. Its own within-joiner, if it has one, is added with
967    /// [`within`](Ancestor::within).
968    pub fn new(counter: impl Into<Name>, value: CounterValue, style: Arc<CounterStyle>) -> Ancestor {
969        Ancestor { counter: counter.into(), value, style, joiner: None, instance: None }
970    }
971
972    /// Returns this ancestor as a value counted in the scoped instance
973    /// attached to the node `instance`.
974    pub fn in_instance(mut self, instance: NodeAddr) -> Ancestor {
975        self.instance = Some(instance);
976        self
977    }
978
979    /// Returns this ancestor with `joiner` as the within-joiner that writes
980    /// its own ancestors' numbers before its own.
981    pub fn within(mut self, joiner: Arc<dyn CompiledWithinJoiner>) -> Ancestor {
982        self.joiner = Some(joiner);
983        self
984    }
985}
986
987/// What a number is numbered within: the within-joiner that writes the
988/// ancestors' numbers, and the ancestors with their values.
989///
990/// The ancestors are the **whole chain**, outermost first:
991/// `flm.headings.section` before `flm.headings.subsection` before
992/// `flm.headings.subsubsection`. A caller must keep this order, because it
993/// says which counters each ancestor may itself be written within: the
994/// ancestors of `ancestors[i]` are `ancestors[..i]`. A within-joiner that
995/// refers to a counter which is not before it in the chain fails with
996/// [`FormatError::UnknownAncestor`]. Every step of the writing therefore has
997/// strictly fewer counters before it than the step before, so a chain of n
998/// ancestors takes at most n steps, regardless of what a caller passes.
999#[derive(Clone, Copy, Debug)]
1000pub struct Parent<'a> {
1001    /// The within-joiner that writes the ancestors' numbers before the
1002    /// point's own. It usually refers only to the counter immediately above,
1003    /// which is written with its own ancestors.
1004    pub joiner: &'a dyn CompiledWithinJoiner,
1005    /// The ancestors, as the numbering feature recorded them: the whole chain,
1006    /// outermost first.
1007    pub ancestors: &'a [Ancestor],
1008}
1009
1010impl<'a> Parent<'a> {
1011    /// Returns the within-joiner `joiner` with the chain `ancestors`,
1012    /// outermost first.
1013    pub fn new(
1014        joiner: &'a dyn CompiledWithinJoiner,
1015        ancestors: &'a [Ancestor],
1016    ) -> Parent<'a> {
1017        Parent { joiner, ancestors }
1018    }
1019}
1020
1021/// How a number is asked for: which variant of the prefix words, and whether
1022/// the word and the delimiters are written.
1023///
1024/// The default asks for the number as the counter style shows it: the
1025/// default words, with the word and the delimiters.
1026#[derive(Clone, PartialEq, Eq, Debug)]
1027pub struct FormatOptions {
1028    /// The variant of the prefix words to use. A variant the counter style
1029    /// does not declare gets the default words.
1030    pub variant: Option<String>,
1031    /// Whether the word before the number is written.
1032    pub with_word: bool,
1033    /// Whether the delimiters around the number are written.
1034    pub with_delimiters: bool,
1035}
1036
1037impl Default for FormatOptions {
1038    fn default() -> FormatOptions {
1039        FormatOptions { variant: None, with_word: true, with_delimiters: true }
1040    }
1041}
1042
1043impl FormatOptions {
1044    /// Returns the default options: the default words, with the word and the
1045    /// delimiters.
1046    pub fn new() -> FormatOptions {
1047        FormatOptions::default()
1048    }
1049
1050    /// Returns these options with the variant `variant` of the prefix words.
1051    pub fn variant(mut self, variant: impl Into<String>) -> FormatOptions {
1052        self.variant = Some(variant.into());
1053        self
1054    }
1055
1056    /// Returns these options without the word before the number.
1057    pub fn without_word(mut self) -> FormatOptions {
1058        self.with_word = false;
1059        self
1060    }
1061
1062    /// Returns these options without the delimiters around the number.
1063    pub fn without_delimiters(mut self) -> FormatOptions {
1064        self.with_delimiters = false;
1065        self
1066    }
1067}
1068
1069// --- what comes out ---------------------------------------------------------------------------
1070
1071/// A segment: a small tree of FLM content that is one stretch of a written
1072/// number, together with the link mark of the value it links to.
1073///
1074/// A segment's content is a synthesized value, content computed by the
1075/// library instead of parsed from a document ([synthesized
1076/// values](crate::guide::concepts_overview#synthesized-values)). It is made of
1077/// the counter style's texts, parsed when the counter style was compiled, and
1078/// the characters of the numbers. A lowering rule shows it with
1079/// [`Lowerer::splice`](crate::core::lowering::Lowerer::splice), which brings
1080/// it up to date first ([value
1081/// catch-up](crate::guide::concepts_overview#value-catch-up)), so the content
1082/// may hold a text style or a reference.
1083///
1084/// The **link mark** is the position, among the values the caller passed in,
1085/// of the value the segment links to: `0` for the only value of [`format()`],
1086/// and the position in the caller's list for
1087/// [`format_many`](super::format_many), regardless of how the values were
1088/// sorted and grouped. A segment with no link mark is shown without a link:
1089/// the texts between two numbers have none. These functions do not depend on
1090/// reference points; the caller turns a position into a link target (the
1091/// counter table does so in [`NumberSegment`](super::NumberSegment)).
1092pub struct Segment {
1093    content: Arc<NodeTree<Flm>>,
1094    link: Option<usize>,
1095}
1096
1097impl fmt::Debug for Segment {
1098    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099        f.debug_struct("Segment").field("link", &self.link).finish_non_exhaustive()
1100    }
1101}
1102
1103impl Segment {
1104    /// Returns the segment's content, a synthesized value whose root is a list
1105    /// node over the content's nodes.
1106    pub fn content(&self) -> &Arc<NodeTree<Flm>> {
1107        &self.content
1108    }
1109
1110    /// Returns the link mark: the position of the value this segment links
1111    /// to, or `None` when the segment is not part of a link.
1112    pub fn link(&self) -> Option<usize> {
1113        self.link
1114    }
1115}
1116
1117// --- writing one value --------------------------------------------------------------------------
1118
1119/// Writes one counter value in `style` and returns the segments of the
1120/// result: under the default writer, the word, the delimiters and the number,
1121/// as one segment that links to the value.
1122///
1123/// `parent` gives the within-joiner and the counters the value is numbered
1124/// within, and is `None` for a counter numbered within nothing. A
1125/// counter that the within-joiner refers to is written with its own ancestors
1126/// before it, so a within-joiner refers only to the counter immediately above
1127/// ([`Parent`]). `options` says which variant of the prefix words to use and
1128/// whether the word and the delimiters are written.
1129///
1130/// Under the default writer, the result is one segment with the link mark
1131/// `0`: one link covers the whole text, the word included. A counter style
1132/// written by another [number writer](super::NumberWriter) may return other
1133/// segments. The call runs on a worker thread ([`on_worker_thread`](guard::on_worker_thread)).
1134///
1135/// # Errors
1136///
1137/// [`FormatError::UndeclaredSubLevel`] when the value carries a sub-number at
1138/// a level for which `style` declares no format, [`FormatError::UnknownAncestor`]
1139/// when a within-joiner refers to a counter that is not among the ancestors,
1140/// and [`FormatError::NestingTooDeep`] or [`FormatError::Failed`] when the
1141/// content could not be built.
1142///
1143/// # Examples
1144///
1145/// ```
1146/// use flm_core::lang::{build_language, LangInputs};
1147/// use flm_core::stdlib::features::numbering::{
1148///     format, CounterStyleDecl, CounterValue, Delimiters, FormatOptions, PrefixWords,
1149/// };
1150///
1151/// let lang = build_language(LangInputs::new());
1152/// let mut decl = CounterStyleDecl::new("example.style.equation");
1153/// decl.delimiters = Delimiters::new("(", ")");
1154/// decl.prefix_words = PrefixWords::new("Eq.~", "Eqs.~");
1155/// let style = decl.compile(&lang).expect("the style compiles");
1156///
1157/// let segments = format(&CounterValue::new(3), &style, None, &FormatOptions::new())
1158///     .expect("the number is written");
1159/// assert_eq!(segments.len(), 1);
1160/// assert_eq!(segments[0].link(), Some(0));
1161/// ```
1162pub fn format(
1163    value: &CounterValue,
1164    style: &CounterStyle,
1165    parent: Option<Parent<'_>>,
1166    options: &FormatOptions,
1167) -> Result<Vec<Segment>, FormatError> {
1168    // Building the pieces walks the chain of ancestors and assembling a
1169    // segment copies content: both descend recursively, so the whole call runs
1170    // under the fixed stack budget, on the worker thread the recursion guard's
1171    // contract asks for, and input nested too deeply is refused rather than
1172    // overflowing the stack.
1173    on_worker(|| {
1174        let mut numbered = NumberedValue::new(value);
1175        if let Some(parent) = parent {
1176            numbered = numbered.within(parent);
1177        }
1178        let cx = WriteCx::new(style);
1179        let mut out = NumberOut::new();
1180        style.writer().write_one(&numbered, options, &cx, &mut out)?;
1181        segments(style, out.into_items())
1182    })
1183}
1184
1185/// Writes one value as the default writer does: the word, the opening
1186/// delimiter, the parts the value's within-joiner writes, the number with its
1187/// sub-numbers, and the closing delimiter, as one item that links to the
1188/// value.
1189///
1190/// [`WriteCx::default_one`] calls it, so a registered writer that hands one
1191/// value to the default writer gets this result.
1192///
1193/// # Errors
1194///
1195/// The same as [`format()`].
1196pub(super) fn default_one<'a>(
1197    value: &NumberedValue<'a>,
1198    options: &FormatOptions,
1199    cx: &WriteCx<'a>,
1200    out: &mut NumberOut<'a>,
1201) -> Result<(), FormatError> {
1202    let style = cx.style();
1203    let mut pieces = Vec::new();
1204    if options.with_word {
1205        pieces.push(Piece::Flm(style.word(1, options.variant.as_deref())));
1206    }
1207    if options.with_delimiters {
1208        pieces.push(Piece::Flm(&style.open));
1209    }
1210    let own = value.value();
1211    let sub_numbers: Vec<Option<i64>> = own.sub_numbers().iter().map(|n| Some(*n)).collect();
1212    number_pieces(style, Some(own.number()), &sub_numbers, Some((value, cx)), &mut pieces)?;
1213    if options.with_delimiters {
1214        pieces.push(Piece::Flm(&style.close));
1215    }
1216    out.item(Item { pieces, mark: Mark::Value(value.index()) });
1217    Ok(())
1218}
1219
1220/// Returns the parts written before a point's own number: what `parent`'s
1221/// within-joiner writes of its chain of ancestors.
1222///
1223/// The list is the one [`format()`] writes before a number, returned on its
1224/// own: a caller that writes several numbers itself reads the parts to find
1225/// which of them two numbers share. `style` is the counter style of the
1226/// point's own number, to which the within-joiner's own texts are
1227/// attributed. The call runs on a worker thread.
1228///
1229/// # Errors
1230///
1231/// [`FormatError::UnknownAncestor`] when the within-joiner refers to a
1232/// counter that is not in the chain, and [`FormatError::NestingTooDeep`] or
1233/// [`FormatError::Failed`] when the content could not be built.
1234pub fn parts(style: &CounterStyle, parent: Parent<'_>) -> Result<Vec<Part>, FormatError> {
1235    on_worker(|| {
1236        let cx = JoinCx::new(style);
1237        parent.joiner.parts(parent.ancestors, &cx)
1238    })
1239}
1240
1241// --- the pieces a number is made of ---------------------------------------------------------
1242
1243/// One piece of a segment's content before it is assembled: FLM parsed when
1244/// the counter style was compiled, content built while writing, or characters
1245/// the library computed.
1246pub(super) enum Piece<'a> {
1247    /// A tree of FLM content; its top-level nodes are copied into the segment.
1248    Flm(&'a Arc<NodeTree<Flm>>),
1249    /// A tree of content built while writing, which nothing else holds: an
1250    /// instantiated template for this number, or what a within-joiner wrote.
1251    Tree(Arc<NodeTree<Flm>>),
1252    /// Characters, which become one text node.
1253    Digits(String),
1254}
1255
1256/// How a piece of the result is linked.
1257#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1258pub(super) enum Mark {
1259    /// Never part of a link.
1260    Never,
1261    /// Part of the link of its neighbors, if they are part of one.
1262    Either,
1263    /// Part of the link to the value at this position among the caller's.
1264    Value(usize),
1265}
1266
1267/// One item of the result, before neighboring items with the same mark are
1268/// merged into a segment.
1269pub(super) struct Item<'a> {
1270    pub(super) pieces: Vec<Piece<'a>>,
1271    pub(super) mark: Mark,
1272}
1273
1274impl<'a> Item<'a> {
1275    /// Returns an item holding one tree of FLM content.
1276    pub(super) fn text(tree: &'a Arc<NodeTree<Flm>>, mark: Mark) -> Item<'a> {
1277        Item { pieces: vec![Piece::Flm(tree)], mark }
1278    }
1279}
1280
1281/// Appends the pieces of one number to `out`: the ancestors' parts, the
1282/// number written with the counter style's number template, and every
1283/// sub-number.
1284///
1285/// `number` is `None` for a number that is not written (the end of a range
1286/// whose start has the same number), and so is each entry of `sub_numbers`
1287/// that is not written; a sub-number of zero is written as nothing too. The
1288/// separator of a sub-level is written only when something is written before
1289/// it.
1290///
1291/// `within` is the value whose ancestors are written before the number,
1292/// with the writing context through which its parts are requested, and is
1293/// `None` where nothing of the ancestors is written. The parts are requested
1294/// only where they are written, so a counter style whose number template
1295/// writes no ancestors' part never runs the within-joiner.
1296///
1297/// # Errors
1298///
1299/// [`FormatError::UndeclaredSubLevel`] for a sub-number at a level for which
1300/// the counter style declares no format, and [`FormatError::UnknownAncestor`]
1301/// from the ancestors' parts.
1302pub(super) fn number_pieces<'a>(
1303    style: &'a CounterStyle,
1304    number: Option<i64>,
1305    sub_numbers: &[Option<i64>],
1306    within: Option<(&NumberedValue<'a>, &WriteCx<'a>)>,
1307    out: &mut Vec<Piece<'a>>,
1308) -> Result<(), FormatError> {
1309    let mut wrote_something = false;
1310    if let Some(number) = number {
1311        if style.number.with_parent() {
1312            if let Some((value, cx)) = within {
1313                for part in cx.parts(value)? {
1314                    out.push(Piece::Tree(part.content));
1315                }
1316            }
1317        }
1318        template_pieces(style, &style.number, number, out)?;
1319        wrote_something = true;
1320    }
1321    sub_level_pieces(style, sub_numbers, None, &mut wrote_something, out)
1322}
1323
1324/// Appends the pieces of the sub-numbers of one number: for each, the
1325/// separator its level declares, then the sub-number itself.
1326///
1327/// Every sub-number is written by this function. A sub-number that is `None`
1328/// or zero is written as nothing; the separator is written only when something
1329/// is written before it, which `wrote_something` says and which this function
1330/// sets as soon as it writes anything. `format`, when given, writes every
1331/// sub-number in that number format instead of with its level's own number
1332/// template.
1333///
1334/// # Errors
1335///
1336/// [`FormatError::UndeclaredSubLevel`] for a sub-number at a level for which
1337/// the counter style declares no format.
1338fn sub_level_pieces<'a>(
1339    style: &'a CounterStyle,
1340    sub_numbers: &[Option<i64>],
1341    format: Option<NumberFormat>,
1342    wrote_something: &mut bool,
1343    out: &mut Vec<Piece<'a>>,
1344) -> Result<(), FormatError> {
1345    for (level, sub_number) in sub_numbers.iter().enumerate() {
1346        let Some(sub_number) = *sub_number else { continue };
1347        if sub_number == 0 {
1348            continue;
1349        }
1350        let Some(declared) = style.sub_levels.get(level) else {
1351            return Err(FormatError::UndeclaredSubLevel {
1352                style: style.name.clone(),
1353                level,
1354                number: sub_number,
1355            });
1356        };
1357        if *wrote_something {
1358            out.push(Piece::Flm(&declared.separator));
1359        }
1360        match format {
1361            Some(format) => out.push(Piece::Digits(format.text(sub_number))),
1362            None => template_pieces(style, &declared.number, sub_number, out)?,
1363        }
1364        *wrote_something = true;
1365    }
1366    Ok(())
1367}
1368
1369/// Appends the pieces of a compiled number template written for `number`.
1370///
1371/// A template written in the template language is instantiated here: each
1372/// `#{…}` is replaced by the number written in the format it gives, and the
1373/// result is one tree of content. A single-letter number template contributes
1374/// its parsed literal parts with the number between them.
1375///
1376/// # Errors
1377///
1378/// [`FormatError`] when the content could not be built.
1379fn template_pieces<'a>(
1380    style: &CounterStyle,
1381    template: &'a CompiledNumber,
1382    number: i64,
1383    out: &mut Vec<Piece<'a>>,
1384) -> Result<(), FormatError> {
1385    match template {
1386        CompiledNumber::Initial { parts, .. } => {
1387            for part in parts {
1388                match part {
1389                    NumberPart::Literal(tree) => out.push(Piece::Flm(tree)),
1390                    NumberPart::Number(format) => out.push(Piece::Digits(format.text(number))),
1391                }
1392            }
1393            Ok(())
1394        }
1395        CompiledNumber::Written { template, formats } => {
1396            let mut entries = Vec::with_capacity(formats.len());
1397            for format in formats {
1398                entries.push(Binding {
1399                    name: format.written_name().to_string(),
1400                    keys: String::new(),
1401                    content: assemble_pieces(style, &[Piece::Digits(format.text(number))])?,
1402                });
1403            }
1404            let bindings = Bindings::new(entries);
1405            out.push(Piece::Tree(instantiate_template(&style.site(), template, &bindings)?));
1406            Ok(())
1407        }
1408    }
1409}
1410
1411/// Returns `value` written in `style` as a bare number: no word, no
1412/// delimiters, and nothing of any counter it is numbered within.
1413///
1414/// `format`, when given, writes the number and every sub-number in that format
1415/// instead of with the counter style's own number templates, as the key of
1416/// `#[Roman]{…}` asks; the counter style's sub-level separators are used in
1417/// both cases.
1418///
1419/// # Errors
1420///
1421/// [`FormatError::UndeclaredSubLevel`] for a sub-number at a level for which
1422/// the counter style declares no format, and a failure to build the content.
1423pub(super) fn number_tree(
1424    style: &CounterStyle,
1425    value: &CounterValue,
1426    format: Option<NumberFormat>,
1427) -> Result<Arc<NodeTree<Flm>>, FormatError> {
1428    let sub_numbers: Vec<Option<i64>> = value.sub_numbers().iter().map(|n| Some(*n)).collect();
1429    let mut pieces = Vec::new();
1430    match format {
1431        None => number_pieces(style, Some(value.number()), &sub_numbers, None, &mut pieces)?,
1432        Some(format) => {
1433            pieces.push(Piece::Digits(format.text(value.number())));
1434            let mut wrote_something = true;
1435            sub_level_pieces(style, &sub_numbers, Some(format), &mut wrote_something, &mut pieces)?;
1436        }
1437    }
1438    assemble_pieces(style, &pieces)
1439}
1440
1441// --- from items to segments --------------------------------------------------------------------
1442
1443/// Returns the segments that `items` become: neighboring items that belong
1444/// to one link (or to none) are merged, and each merged sequence is assembled
1445/// into one synthesized value.
1446///
1447/// A segment that holds no content and links to nothing is left out.
1448///
1449/// The function assembles content, which descends recursively, so it must be
1450/// called on a worker thread; the two entry points [`format()`] and
1451/// [`format_many`](super::format_many) run their whole work on one.
1452///
1453/// # Errors
1454///
1455/// [`FormatError::NestingTooDeep`] or [`FormatError::Failed`] from the
1456/// assembly of a value tree.
1457pub(super) fn segments(
1458    style: &CounterStyle,
1459    items: Vec<Item<'_>>,
1460) -> Result<Vec<Segment>, FormatError> {
1461    let mut merged: Vec<Item<'_>> = Vec::new();
1462    for item in items {
1463        match merged.last_mut() {
1464            Some(last) if last.mark == Mark::Never && item.mark == Mark::Never => {
1465                last.pieces.extend(item.pieces);
1466                continue;
1467            }
1468            Some(last)
1469                if last.mark != Mark::Never
1470                    && item.mark != Mark::Never
1471                    && (item.mark == Mark::Either
1472                        || last.mark == Mark::Either
1473                        || item.mark == last.mark) =>
1474            {
1475                if let (Mark::Value(_), Mark::Either) = (item.mark, last.mark) {
1476                    last.mark = item.mark;
1477                }
1478                last.pieces.extend(item.pieces);
1479                continue;
1480            }
1481            _ => {}
1482        }
1483        merged.push(item);
1484    }
1485
1486    let mut out = Vec::with_capacity(merged.len());
1487    for item in merged {
1488        let link = match item.mark {
1489            Mark::Value(position) => Some(position),
1490            Mark::Never | Mark::Either => None,
1491        };
1492        let content = assemble_pieces(style, &item.pieces)?;
1493        if link.is_none() && content.root().child_count() == 0 {
1494            continue;
1495        }
1496        out.push(Segment { content, link });
1497    }
1498    Ok(out)
1499}
1500
1501/// Runs `work` on a worker thread and returns its result; the operating
1502/// system's refusal to create the thread becomes [`FormatError::Failed`].
1503///
1504/// Every entry point that writes a number goes through this function: the
1505/// writing walks the chain of ancestors and copies content, both recursively,
1506/// and the recursion guard's fixed stack budget can be met only on a worker
1507/// thread ([`on_worker_thread`](guard::on_worker_thread)).
1508/// A call made from a thread that is already a worker thread, as every stage
1509/// of the pipeline is, runs `work` in place.
1510pub(super) fn on_worker<T: Send>(
1511    work: impl FnOnce() -> Result<T, FormatError> + Send,
1512) -> Result<T, FormatError> {
1513    match guard::on_worker_thread(work) {
1514        Ok(result) => result,
1515        Err(error) => Err(FormatError::Failed { detail: error.to_string() }),
1516    }
1517}
1518
1519// --- assembling a value tree ---------------------------------------------------------------
1520
1521/// The origin name under which a counter style's text is parsed: the name
1522/// that a diagnostic about that text gives as the text's origin.
1523pub(super) const STYLE_TEXT_ORIGIN: &str = "counter style text";
1524
1525/// Parses `text`, a counter style's text, as FLM against the built language
1526/// and returns its tree: [`parse_text_from`] with the origin name
1527/// [`STYLE_TEXT_ORIGIN`].
1528///
1529/// # Errors
1530///
1531/// As [`parse_text_from`].
1532pub(super) fn parse_text(
1533    text: &str,
1534    lang: &BuiltLang,
1535    warnings: &mut Vec<FlmDiagnostic>,
1536) -> Result<Arc<NodeTree<Flm>>, StyleError> {
1537    parse_text_from(text, STYLE_TEXT_ORIGIN, lang, warnings)
1538}
1539
1540/// Parses `text` as FLM against the built language and returns its tree;
1541/// `origin` is the origin name that the diagnostics of the parse give.
1542///
1543/// Warnings are added to `warnings`; an error refuses the text, since the text
1544/// is configuration and a mistake in it is reported when the registry is
1545/// built.
1546///
1547/// # Errors
1548///
1549/// [`StyleError::Parse`] when the parse reported errors, and
1550/// [`StyleError::ParseFailed`] when it could not run at all.
1551fn parse_text_from(
1552    text: &str,
1553    origin: &str,
1554    lang: &BuiltLang,
1555    warnings: &mut Vec<FlmDiagnostic>,
1556) -> Result<Arc<NodeTree<Flm>>, StyleError> {
1557    let origin = FlmOrigin::synthetic(origin);
1558    let source = Arc::new(FlmSource::new(text.to_string()).with_origin(origin));
1559    let fragment =
1560        parse_fragment(lang, source, FragmentLayout::default(), &ParseOptions::default())
1561            .map_err(|error| StyleError::ParseFailed {
1562                text: text.to_string(),
1563                detail: error.to_string(),
1564            })?;
1565    let errors: Vec<FlmDiagnostic> = fragment
1566        .diags()
1567        .iter()
1568        .filter(|diagnostic| diagnostic.severity() == Severity::Error)
1569        .cloned()
1570        .collect();
1571    if !errors.is_empty() {
1572        return Err(StyleError::Parse { text: text.to_string(), diagnostics: errors });
1573    }
1574    warnings.extend(
1575        fragment
1576            .diags()
1577            .iter()
1578            .filter(|diagnostic| diagnostic.severity() != Severity::Error)
1579            .cloned(),
1580    );
1581    Ok(Arc::clone(fragment.tree()))
1582}
1583
1584/// Compiles one pair of words.
1585fn compile_words(
1586    words: &PluralWords,
1587    lang: &BuiltLang,
1588    warnings: &mut Vec<FlmDiagnostic>,
1589) -> Result<CompiledPlural, StyleError> {
1590    Ok(CompiledPlural {
1591        one: parse_text(&words.one, lang, warnings)?,
1592        other: parse_text(&words.other, lang, warnings)?,
1593    })
1594}
1595
1596/// A visitor that carries every node over unchanged.
1597struct Verbatim;
1598
1599impl RestageVisitor<Flm, (), ()> for Verbatim {
1600    type Error = Infallible;
1601
1602    fn restage(
1603        &mut self,
1604        _node: NodeRef<'_, Flm>,
1605        _cx: &mut RestageContext<'_, Flm, (), ()>,
1606    ) -> Result<Restage<()>, Infallible> {
1607        Ok(Restage::Descend(()))
1608    }
1609}
1610
1611/// The visitor that assembles a segment: called once, at the root of the
1612/// counter style's empty tree, it emits a list node that holds a copy of every
1613/// piece.
1614struct Assemble<'a, 'p> {
1615    style: &'a CounterStyle,
1616    pieces: &'p [Piece<'a>],
1617}
1618
1619impl RestageVisitor<Flm, (), ()> for Assemble<'_, '_> {
1620    type Error = FormatError;
1621
1622    fn restage(
1623        &mut self,
1624        root: NodeRef<'_, Flm>,
1625        cx: &mut RestageContext<'_, Flm, (), ()>,
1626    ) -> Result<Restage<()>, FormatError> {
1627        let mut children: Vec<BuildId> = Vec::new();
1628        for piece in self.pieces {
1629            match piece {
1630                Piece::Flm(tree) => {
1631                    for node in tree.root().children().iter() {
1632                        let copied = cx
1633                            .restage_subtree(node, &mut Verbatim)
1634                            .map_err(|error| failed(&error))?;
1635                        children.extend(copied);
1636                    }
1637                }
1638                Piece::Tree(tree) => {
1639                    for node in tree.root().children().iter() {
1640                        let copied = cx
1641                            .restage_subtree(node, &mut Verbatim)
1642                            .map_err(|error| failed(&error))?;
1643                        children.extend(copied);
1644                    }
1645                }
1646                Piece::Digits(text) if !text.is_empty() => {
1647                    children.push(self.digits(cx, text)?);
1648                }
1649                Piece::Digits(_) => {}
1650            }
1651        }
1652        let span = SourceSpan::new(root.span().source(), root.span().start()..root.span().start());
1653        let state = Arc::clone(&self.style.state);
1654        let kind = NodeKind::list();
1655        let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&children))
1656            .map_err(|error| FormatError::Failed { detail: error.to_string() })?;
1657        let list = cx
1658            .builder()
1659            .add(kind, span, state, children, ext, ())
1660            .map_err(|error| FormatError::Failed { detail: error.to_string() })?;
1661        Ok(Restage::Emit(vec![list]))
1662    }
1663}
1664
1665impl Assemble<'_, '_> {
1666    /// Stages (builds into the tree being assembled) one text node that holds
1667    /// the characters of a number. The node is attributed to the counter
1668    /// style's own source, where a diagnostic about it points.
1669    fn digits(
1670        &self,
1671        cx: &mut RestageContext<'_, Flm, (), ()>,
1672        text: &str,
1673    ) -> Result<BuildId, FormatError> {
1674        let at: &FlmSpan = self.style.blank.root().span();
1675        let span = SourceSpan::new(at.source(), at.start()..at.start());
1676        let state = Arc::clone(&self.style.state);
1677        let kind = NodeKind::chars(TextContent::Owned(Box::from(text)));
1678        let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&[]))
1679            .map_err(|error| FormatError::Failed { detail: error.to_string() })?;
1680        cx.builder()
1681            .add(kind, span, state, Vec::new(), ext, ())
1682            .map_err(|error| FormatError::Failed { detail: error.to_string() })
1683    }
1684}
1685
1686/// Returns a restage failure as this module's [`FormatError`].
1687fn failed<E: fmt::Display>(error: &RestageError<E>) -> FormatError {
1688    match error {
1689        RestageError::DescentLimitExceeded { detail, .. } => {
1690            FormatError::NestingTooDeep { detail: detail.clone() }
1691        }
1692        other => FormatError::Failed { detail: other.to_string() },
1693    }
1694}
1695
1696/// Returns the synthesized value that the pieces make: a list node over a copy
1697/// of each piece's nodes, with one text node per piece of characters.
1698///
1699/// It descends recursively under the fixed stack budget, so it must be called
1700/// on a worker thread, which [`on_worker`] provides.
1701pub(super) fn assemble_pieces(
1702    style: &CounterStyle,
1703    pieces: &[Piece<'_>],
1704) -> Result<Arc<NodeTree<Flm>>, FormatError> {
1705    let mut visitor = Assemble { style, pieces };
1706    guard::restager(&mut visitor, GuardPolicy::StackBudget)
1707        .restage(&style.blank)
1708        .map_err(|error| failed(&error))
1709        .map(Arc::new)
1710}
1711
1712// --- the join texts, resolved ------------------------------------------------------------------
1713
1714/// The join keys, in the order of the fields of [`JoinDecl`], with the default
1715/// text of each.
1716const JOIN_DEFAULTS: [(&str, &str); 17] = [
1717    ("one_pre", ""),
1718    ("one_post", ""),
1719    ("pair_pre", ""),
1720    ("pair_mid", " ${and} "),
1721    ("pair_post", ""),
1722    ("range_pre", ""),
1723    ("range_mid", "${endash}"),
1724    ("range_pairmid", "${sep}"),
1725    ("range_post", ""),
1726    ("list_pre", ""),
1727    ("list_mid", "${sep} "),
1728    ("list_midlast", "${sep} ${and} "),
1729    ("list_post", ""),
1730    ("and", "and"),
1731    ("sep", ","),
1732    ("endash", "\u{2013}"),
1733    ("empty", "(empty)"),
1734];
1735
1736impl CompiledJoin {
1737    /// Returns the join text `which`.
1738    pub(crate) fn text(&self, which: JoinText) -> &Arc<NodeTree<Flm>> {
1739        match which {
1740            JoinText::OnePre => &self.one_pre,
1741            JoinText::OnePost => &self.one_post,
1742            JoinText::PairPre => &self.pair_pre,
1743            JoinText::PairMid => &self.pair_mid,
1744            JoinText::PairPost => &self.pair_post,
1745            JoinText::RangePre => &self.range_pre,
1746            JoinText::RangeMid => &self.range_mid,
1747            JoinText::RangePairMid => &self.range_pairmid,
1748            JoinText::RangePost => &self.range_post,
1749            JoinText::ListPre => &self.list_pre,
1750            JoinText::ListMid => &self.list_mid,
1751            JoinText::ListMidLast => &self.list_midlast,
1752            JoinText::ListPost => &self.list_post,
1753            JoinText::Empty => &self.empty,
1754        }
1755    }
1756
1757    /// Returns the declaration's texts compiled: the variables replaced and
1758    /// every text parsed; a key the declaration leaves `None` takes its
1759    /// default.
1760    ///
1761    /// `origin` is the origin name that the diagnostics of the parse give:
1762    /// [`STYLE_TEXT_ORIGIN`] for a counter style's texts, another name for the
1763    /// texts of another owner. Warnings are added to `warnings`.
1764    ///
1765    /// # Errors
1766    ///
1767    /// The [`StyleError`] of the first text that refers to a variable that is
1768    /// not a join key or that is not valid FLM.
1769    pub(crate) fn compile(
1770        decl: &JoinDecl,
1771        origin: &str,
1772        lang: &BuiltLang,
1773        warnings: &mut Vec<FlmDiagnostic>,
1774    ) -> Result<CompiledJoin, StyleError> {
1775        let declared: [(&str, &Option<String>); 17] = [
1776            ("one_pre", &decl.one_pre),
1777            ("one_post", &decl.one_post),
1778            ("pair_pre", &decl.pair_pre),
1779            ("pair_mid", &decl.pair_mid),
1780            ("pair_post", &decl.pair_post),
1781            ("range_pre", &decl.range_pre),
1782            ("range_mid", &decl.range_mid),
1783            ("range_pairmid", &decl.range_pairmid),
1784            ("range_post", &decl.range_post),
1785            ("list_pre", &decl.list_pre),
1786            ("list_mid", &decl.list_mid),
1787            ("list_midlast", &decl.list_midlast),
1788            ("list_post", &decl.list_post),
1789            ("and", &decl.and),
1790            ("sep", &decl.sep),
1791            ("endash", &decl.endash),
1792            ("empty", &decl.empty),
1793        ];
1794        let mut raw: BTreeMap<&str, &str> = JOIN_DEFAULTS.into_iter().collect();
1795        for (key, value) in declared {
1796            if let Some(value) = value {
1797                raw.insert(key, value);
1798            }
1799        }
1800        let mut parsed: BTreeMap<&str, Arc<NodeTree<Flm>>> = BTreeMap::new();
1801        for (key, _) in JOIN_DEFAULTS {
1802            let resolved = substitute_variables(raw[key], &raw)?;
1803            parsed.insert(key, parse_text_from(&resolved, origin, lang, warnings)?);
1804        }
1805        let mut take = |key: &str| parsed.remove(key).expect("every join key was parsed");
1806        Ok(CompiledJoin {
1807            one_pre: take("one_pre"),
1808            one_post: take("one_post"),
1809            pair_pre: take("pair_pre"),
1810            pair_mid: take("pair_mid"),
1811            pair_post: take("pair_post"),
1812            range_pre: take("range_pre"),
1813            range_mid: take("range_mid"),
1814            range_pairmid: take("range_pairmid"),
1815            range_post: take("range_post"),
1816            list_pre: take("list_pre"),
1817            list_mid: take("list_mid"),
1818            list_midlast: take("list_midlast"),
1819            list_post: take("list_post"),
1820            empty: take("empty"),
1821        })
1822    }
1823}
1824
1825/// One piece of a list joined by the join texts: a join text, or the item at
1826/// a position of the list.
1827#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1828pub(crate) enum ListPiece {
1829    /// The join text of this key.
1830    Text(JoinText),
1831    /// The item at this position, counted from zero.
1832    Item(usize),
1833}
1834
1835/// Returns the places of the join texts in a list of `count` items: one item
1836/// is `one_pre`, the item, `one_post`; two items are `pair_pre`, the first,
1837/// `pair_mid`, the second, `pair_post`; more are `list_pre`, the items with
1838/// `list_mid` between them and `list_midlast` before the last, `list_post`.
1839/// No item gives no piece.
1840///
1841/// The default number writer joins the runs of a counter style's numbers with
1842/// it, and the refs feature joins the items of a reference to several targets
1843/// with it, so that both follow the same rule.
1844pub(crate) fn list_shape(count: usize) -> Vec<ListPiece> {
1845    let mut pieces = Vec::new();
1846    match count {
1847        0 => {}
1848        1 => {
1849            pieces.push(ListPiece::Text(JoinText::OnePre));
1850            pieces.push(ListPiece::Item(0));
1851            pieces.push(ListPiece::Text(JoinText::OnePost));
1852        }
1853        2 => {
1854            pieces.push(ListPiece::Text(JoinText::PairPre));
1855            pieces.push(ListPiece::Item(0));
1856            pieces.push(ListPiece::Text(JoinText::PairMid));
1857            pieces.push(ListPiece::Item(1));
1858            pieces.push(ListPiece::Text(JoinText::PairPost));
1859        }
1860        _ => {
1861            pieces.push(ListPiece::Text(JoinText::ListPre));
1862            for index in 0..count - 1 {
1863                if index > 0 {
1864                    pieces.push(ListPiece::Text(JoinText::ListMid));
1865                }
1866                pieces.push(ListPiece::Item(index));
1867            }
1868            pieces.push(ListPiece::Text(JoinText::ListMidLast));
1869            pieces.push(ListPiece::Item(count - 1));
1870            pieces.push(ListPiece::Text(JoinText::ListPost));
1871        }
1872    }
1873    pieces
1874}
1875
1876/// Returns the name of the variable at the start of `text`, and how many bytes
1877/// it takes, or `None` when `text` does not start with one.
1878///
1879/// A variable is `${`, then one or more ASCII letters, digits, `_` and `.`,
1880/// then `}`. This syntax belongs to the join texts only: a number template and
1881/// a within template are written in the template language, where a
1882/// substitution is `#{…}`.
1883fn substitution_at(text: &str) -> Option<(&str, usize)> {
1884    let rest = text.strip_prefix("${")?;
1885    let end = rest.find('}')?;
1886    let name = &rest[..end];
1887    if name.is_empty()
1888        || !name.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '.')
1889    {
1890        return None;
1891    }
1892    Some((name, 2 + end + 1))
1893}
1894
1895/// Returns `text` with every `${name}` replaced by `values[name]`, in one
1896/// pass: a replaced text is not scanned again.
1897///
1898/// # Errors
1899///
1900/// [`StyleError::UnknownVariable`] for a name that `values` does not hold.
1901fn substitute_variables(
1902    text: &str,
1903    values: &BTreeMap<&str, &str>,
1904) -> Result<String, StyleError> {
1905    let mut out = String::new();
1906    let mut rest = text;
1907    while let Some(start) = rest.find("${") {
1908        match substitution_at(&rest[start..]) {
1909            Some((name, length)) => {
1910                let Some(value) = values.get(name) else {
1911                    return Err(StyleError::UnknownVariable {
1912                        text: text.to_string(),
1913                        name: name.to_string(),
1914                    });
1915                };
1916                out.push_str(&rest[..start]);
1917                out.push_str(value);
1918                rest = &rest[start + length..];
1919            }
1920            None => {
1921                out.push_str(&rest[..start + 2]);
1922                rest = &rest[start + 2..];
1923            }
1924        }
1925    }
1926    out.push_str(rest);
1927    Ok(out)
1928}
1929
1930// --- what `format_many` reads off a style -----------------------------------------------------
1931
1932impl CounterStyle {
1933    /// Returns the word for `count` numbers in the variant `variant`, or
1934    /// `None` when that word is the empty text and nothing is written.
1935    pub(crate) fn word_text(
1936        &self,
1937        count: usize,
1938        variant: Option<&str>,
1939    ) -> Option<&Arc<NodeTree<Flm>>> {
1940        let word = self.word(count, variant);
1941        (word.root().child_count() > 0).then_some(word)
1942    }
1943
1944    /// Returns the opening delimiter, the text before a number.
1945    pub(crate) fn open(&self) -> &Arc<NodeTree<Flm>> {
1946        &self.open
1947    }
1948
1949    /// Returns the closing delimiter, the text after a number.
1950    pub(crate) fn close(&self) -> &Arc<NodeTree<Flm>> {
1951        &self.close
1952    }
1953
1954    /// Returns whether the word before the numbers is part of the link to the
1955    /// first number written.
1956    pub(super) fn name_in_link(&self) -> bool {
1957        self.name_in_link
1958    }
1959
1960    /// Returns whether the end of a range repeats the ancestors' parts.
1961    pub(super) fn repeat_parents_in_range(&self) -> bool {
1962        self.repeat_parents_in_range
1963    }
1964
1965    /// Returns whether consecutive numbers collapse into a range.
1966    pub(super) fn ranges(&self) -> bool {
1967        self.ranges
1968    }
1969
1970    /// Returns the number writer of this counter style.
1971    pub(super) fn writer(&self) -> &Arc<dyn CompiledNumberWriter> {
1972        &self.writer
1973    }
1974
1975    /// Returns the counter style's compiled join texts.
1976    pub(crate) fn join(&self) -> &CompiledJoin {
1977        &self.join
1978    }
1979}