flm_core/stdlib/features/numbering/decl.rs
1//! What another feature declares to the numbering feature: a counter
2//! ([`CounterDecl`]), the counter it is numbered within and how that counter's
3//! number is written before its own ([`Within`]), and a parent set
4//! ([`ParentSetDecl`]).
5//!
6//! A feature declares each of these by contributing a value to one of the
7//! numbering feature's five service slots, whose names this module defines.
8//! A service slot is the declaration, by the feature that owns an
9//! interaction, of a dotted name, the type of the values the slot takes and
10//! its arity ([`services`](crate::core::services)). The five service slots,
11//! and the type of the values each takes, are:
12//!
13//! - [`COUNTERS_SLOT`] takes [`CounterDecl`];
14//! - [`STYLES_SLOT`] takes [`CounterStyleDecl`](super::CounterStyleDecl);
15//! - [`WITHIN_JOINERS_SLOT`] takes [`WithinJoinerDecl`](super::WithinJoinerDecl);
16//! - [`NUMBER_WRITERS_SLOT`] takes [`NumberWriterDecl`](super::NumberWriterDecl);
17//! - [`PARENT_SETS_SLOT`] takes [`ParentSetDecl`].
18//!
19//! The module also defines the reserved name prefix ([`RESERVED_PREFIX`]) and
20//! the placeholder of the parent that applies ([`PARENT_PLACEHOLDER`]). The
21//! [module documentation of the numbering feature](super) describes what the
22//! feature does with these declarations.
23
24use crate::model::names::Name;
25
26/// The name of the service slot into which a feature declares its counters,
27/// `flm.numbering.counters`.
28///
29/// The service slot takes [`CounterDecl`] values, any number of them, in
30/// contribution order. A feature adds one counter per call of
31/// [`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot).
32/// The call is a peer declaration
33/// ([`PeerName`](crate::core::registry::PeerName)) of the service slot, so the
34/// feature still registers in a registry that holds no numbering feature: the
35/// value is then dropped and the registry build records one Note ([services and
36/// service slots](crate::guide::concepts_overview#services-and-service-slots)).
37pub const COUNTERS_SLOT: &str = "flm.numbering.counters";
38
39/// The name of the service slot into which a feature declares its counter
40/// styles, `flm.numbering.styles`.
41///
42/// The service slot takes [`CounterStyleDecl`](super::CounterStyleDecl)
43/// values, contributed the same way as the counters of [`COUNTERS_SLOT`].
44pub const STYLES_SLOT: &str = "flm.numbering.styles";
45
46/// The name of the service slot into which a feature contributes a
47/// within-joiner registered by name, `flm.numbering.within-joiners`.
48///
49/// The service slot takes [`WithinJoinerDecl`](super::WithinJoinerDecl)
50/// values, contributed the same way as the counters of [`COUNTERS_SLOT`]. A
51/// counter asks for a registered within-joiner by its name with
52/// [`Within::joiner_named`]. Two within-joiners of one name fail the registry
53/// build.
54pub const WITHIN_JOINERS_SLOT: &str = "flm.numbering.within-joiners";
55
56/// The name of the service slot into which a feature contributes a number
57/// writer, `flm.numbering.number-writers`.
58///
59/// The service slot takes [`NumberWriterDecl`](super::NumberWriterDecl)
60/// values, contributed the same way as the counters of [`COUNTERS_SLOT`]. A
61/// counter style asks for a number writer by its name with
62/// [`CounterStyleDecl::with_number_writer`](super::CounterStyleDecl::with_number_writer).
63/// Two number writers of one name fail the registry build.
64pub const NUMBER_WRITERS_SLOT: &str = "flm.numbering.number-writers";
65
66/// The name of the service slot into which a feature contributes a parent
67/// set, `flm.numbering.parent-sets`.
68///
69/// The service slot takes [`ParentSetDecl`] values, contributed the same way
70/// as the counters of [`COUNTERS_SLOT`]. A counter is numbered within a parent
71/// set with [`Within::parent_set`]. Two parent sets of one name fail the
72/// registry build.
73pub const PARENT_SETS_SLOT: &str = "flm.numbering.parent-sets";
74
75/// The prefix, `_`, that begins every name the numbering feature reserves for
76/// itself.
77///
78/// A within template writes `#{_parent}` for the parent that applies
79/// ([`PARENT_PLACEHOLDER`]), so no counter may have a name that begins with
80/// this prefix: a counter or a parent set whose name begins with it fails the
81/// registry build.
82pub const RESERVED_PREFIX: &str = "_";
83
84/// The name, `_parent`, under which a within template writes the parent that
85/// applies.
86///
87/// In a within template, `#{_parent}` is the number of the parent that
88/// applies at the point (the only parent, or among several the one advanced
89/// most recently), with that parent's own ancestors written before it, as
90/// `#{flm.headings.section}` is the section's number. See
91/// [`Within::template`].
92pub const PARENT_PLACEHOLDER: &str = "_parent";
93
94/// A parent set: a named list of counters, any one of which may be the parent
95/// of a counter numbered within the set with [`Within::parent_set`].
96///
97/// A feature that owns a family of counters contributes a parent set to the
98/// service slot [`PARENT_SETS_SLOT`], so that another feature, or a document's
99/// numbering options, can number a counter within whichever of these counters
100/// was advanced most recently without listing them. The headings feature
101/// contributes `flm.headings.levels`, the counters of its heading kinds from
102/// the outermost level in.
103///
104/// The set's name is dotted and owned by the feature that contributes the
105/// set, as a counter style's name is. A name beginning with
106/// [`RESERVED_PREFIX`] fails the registry build, and so does a set that holds
107/// a counter no feature declares.
108///
109/// # Examples
110///
111/// ```
112/// use flm_core::stdlib::features::numbering::ParentSetDecl;
113///
114/// let levels = ParentSetDecl::new("example.levels", ["example.chapter", "example.section"]);
115/// assert_eq!(levels.counters.len(), 2);
116/// ```
117#[derive(Clone, PartialEq, Eq, Hash, Debug)]
118pub struct ParentSetDecl {
119 /// The set's dotted name, such as `flm.headings.levels`.
120 pub name: Name,
121 /// The counters of the set, in the order the contributing feature gives
122 /// them.
123 pub counters: Vec<Name>,
124}
125
126impl ParentSetDecl {
127 /// Returns the parent set `name`, which holds `counters`.
128 pub fn new(
129 name: impl Into<Name>,
130 counters: impl IntoIterator<Item = impl Into<Name>>,
131 ) -> ParentSetDecl {
132 ParentSetDecl { name: name.into(), counters: counters.into_iter().map(Into::into).collect() }
133 }
134}
135
136/// Which counters a counter may be numbered within: one counter, any counter
137/// of a list, or any counter of a registered parent set.
138///
139/// This is the `parents` field of [`Within`], which the constructors
140/// [`Within::parent`], [`Within::parents`] and [`Within::parent_set`] set.
141///
142/// Where there are several possible parents, the **parent that applies** at a
143/// reference point is the one among them that was advanced most recently in
144/// document order. For example, an equation numbered within any of the
145/// sectioning counters is written `4.1` after a chapter and before the
146/// chapter's first section, and `4.1.2` once a section has begun in that
147/// chapter.
148#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize, serde::Serialize)]
149#[derive(schemars::JsonSchema)]
150#[serde(rename_all = "kebab-case")]
151pub enum Parents {
152 /// Numbered within this one counter.
153 One(Name),
154 /// Numbered within whichever of these counters was advanced most
155 /// recently.
156 Any(Vec<Name>),
157 /// Numbered within whichever counter of the parent set of this name was
158 /// advanced most recently. A name no feature registers fails the registry
159 /// build when a feature declares it, and is the Error
160 /// `flm.numbering.unknown-parent-set` when a document's numbering options
161 /// give it.
162 Set(Name),
163}
164
165impl Parents {
166 /// Returns the parents as a message writes them: `` `section` ``,
167 /// `` any of `section`, `subsection` `` or
168 /// `` the parent set `flm.headings.levels` ``.
169 pub(super) fn describe(&self) -> String {
170 match self {
171 Parents::One(name) => format!("`{name}`"),
172 Parents::Any(names) => format!("any of {}", quoted_list(names)),
173 Parents::Set(name) => format!("the parent set `{name}`"),
174 }
175 }
176}
177
178/// Returns `names` in backquotes, separated by commas: `` `a`, `b` ``.
179pub(super) fn quoted_list(names: &[Name]) -> String {
180 names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", ")
181}
182
183/// The form of a within-joiner, which writes a counter's ancestors' numbers
184/// before the counter's own number: one of the four forms a [`Within`] may
185/// carry.
186///
187/// A form is data, not behavior: it can be compared, hashed, and carried in a
188/// document's numbering options. What a form writes is decided when it is
189/// compiled, against the built language and against the within-joiners the
190/// registry holds ([`Within::compile`]).
191#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize, serde::Serialize)]
192#[derive(schemars::JsonSchema)]
193#[serde(rename_all = "kebab-case")]
194pub enum WithinJoinerSpec {
195 /// The parent's number, then this joining text, which is FLM: what
196 /// [`Within::parent`] and [`Within::joined_by`] make. A subsection joined
197 /// by `.` is written `1.2`.
198 ///
199 /// The parent is written with its own ancestors before it, each as a part
200 /// of its own, so a chain three counters deep is written `1.2.3` with
201 /// every counter declaring only its joining text.
202 Joined(String),
203 /// A within template, in the language that [`Within::template`]
204 /// describes.
205 Template(String),
206 /// Nothing of the ancestors is written: the counter restarts under its
207 /// parent, and its number is shown **bare**, that is, without its
208 /// parents' numbers. What [`Within::displayed_bare`] makes.
209 Bare,
210 /// The within-joiner registered under this name in
211 /// [`WITHIN_JOINERS_SLOT`], which writes what its code writes. A name no
212 /// feature registers is refused: in a feature's declaration it fails the
213 /// registry build, and in a document's numbering options it is the Error
214 /// `flm.numbering.unknown-within-joiner`, and the counter keeps the
215 /// hierarchy it was declared with.
216 Named(Name),
217}
218
219/// The counter within which a counter is numbered, and how that counter's
220/// number is written before the counter's own: the counter's place in the
221/// hierarchy of counters.
222///
223/// A subsection numbered within a section is written `2.3`: the parent is the
224/// counter `flm.headings.section`, and the within-joiner is the joining text
225/// `.`. The two are declared together because the parent decides what
226/// restarts the counter and the within-joiner decides what is shown of the
227/// parent, and neither is of any use without the other. The [module
228/// documentation](super#numbering-within-another-counter) describes the
229/// mechanism.
230///
231/// Three constructors say which counter is the parent:
232///
233/// - [`Within::parent`]: numbered within that one counter.
234/// - [`Within::parents`]: numbered within whichever of several counters was
235/// advanced most recently in document order.
236/// - [`Within::parent_set`]: the same over the counters of a parent set that
237/// a feature registered ([`ParentSetDecl`]).
238///
239/// Each writes the parent's number and a full stop before the counter's own
240/// number, `1.2`. Four builders change what is written:
241///
242/// - [`joined_by`](Within::joined_by): another joining text.
243/// - [`template`](Within::template): a within template, which may write
244/// markup around an ancestor's number and may refer to more than one
245/// ancestor.
246/// - [`displayed_bare`](Within::displayed_bare): nothing of the parent is
247/// written; the counter restarts under the parent and its number is shown
248/// bare.
249/// - [`joiner_named`](Within::joiner_named): a within-joiner that a feature
250/// registered by name, which writes what its code writes.
251///
252/// The builder [`no_restart`](Within::no_restart) keeps the parent's number
253/// written before the counter's own but stops the parent from restarting the
254/// count: `1.1`, `1.2`, `2.3`.
255///
256/// # Examples
257///
258/// ```
259/// use flm_core::stdlib::features::numbering::Within;
260///
261/// // `1.2`, the usual shape.
262/// let plain = Within::parent("flm.headings.section");
263/// // `1-2`.
264/// let dashed = Within::parent("flm.headings.section").joined_by("-");
265/// // The section's number in bold, then a full stop.
266/// let bold = Within::parent("flm.headings.section").template(r"\textbf{#{flm.headings.section}}.");
267/// // The same, referring to the parent that applies rather than to the counter.
268/// let short = Within::parent("flm.headings.section").template(r"\textbf{#{_parent}}.");
269/// // Restarted by the section, and shown without the section's number.
270/// let bare = Within::parent("flm.headings.section").displayed_bare();
271/// // What the within-joiner registered under this name writes.
272/// let custom = Within::parent("flm.headings.section").joiner_named("example.compact");
273/// // Within whichever of the three was advanced last: `4.1`, `4.1.2`.
274/// let any = Within::parents([
275/// "example.chapter",
276/// "flm.headings.section",
277/// "flm.headings.subsection",
278/// ]);
279/// // The same over the heading counters a registry declares.
280/// let levels = Within::parent_set("flm.headings.levels");
281/// // `1.1`, `1.2`, then `2.3`: the section is written and does not restart.
282/// let continued = Within::parent("flm.headings.section").no_restart();
283/// # let _ = (plain, dashed, bold, short, bare, custom, any, levels, continued);
284/// ```
285#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize, serde::Serialize)]
286#[derive(schemars::JsonSchema)]
287#[serde(deny_unknown_fields)]
288pub struct Within {
289 /// The counter within which this counter is numbered, or the counters any
290 /// one of which may be its parent. The parent that applies restarts this
291 /// counter: the counter's count is kept separately for each list of
292 /// ancestors it is advanced under, each ancestor identified by its name
293 /// and its value.
294 pub parents: Parents,
295 /// The within-joiner: how the ancestors' numbers are written before this
296 /// counter's own.
297 pub joiner: WithinJoinerSpec,
298 /// Whether the parent is left out of what restarts the count. `true`
299 /// continues the count across the parent's advances, and the parent's
300 /// number is still written before the counter's own (`1.1`, `1.2`,
301 /// `2.3`). `false` by default.
302 pub no_restart: bool,
303}
304
305impl Within {
306 /// Returns the place of a counter numbered within `parent`, whose number
307 /// is written before the counter's own with a full stop after it: `1.2`.
308 pub fn parent(parent: impl Into<Name>) -> Within {
309 Within::with_parents(Parents::One(parent.into()))
310 }
311
312 /// Returns the place of a counter numbered within whichever of `parents`
313 /// was advanced most recently in document order; that counter's number is
314 /// written before the counter's own with a full stop after it.
315 ///
316 /// A reference point that the document reaches before any of `parents`
317 /// was advanced takes no number and is reported as the Error
318 /// `flm.numbering.parent-uninitialized`, as is a point under a single
319 /// parent that has no value yet.
320 pub fn parents(parents: impl IntoIterator<Item = impl Into<Name>>) -> Within {
321 Within::with_parents(Parents::Any(parents.into_iter().map(Into::into).collect()))
322 }
323
324 /// Returns the place of a counter numbered within whichever counter of the
325 /// parent set `name` was advanced most recently, as [`Within::parents`]
326 /// does over the counters of the set. The parent set is one that a feature
327 /// registered as a [`ParentSetDecl`].
328 pub fn parent_set(name: impl Into<Name>) -> Within {
329 Within::with_parents(Parents::Set(name.into()))
330 }
331
332 /// Returns the place of a counter numbered within `parents`, joined by a
333 /// full stop and restarted by them.
334 fn with_parents(parents: Parents) -> Within {
335 Within { parents, joiner: WithinJoinerSpec::Joined(".".to_string()), no_restart: false }
336 }
337
338 /// Builder: the parent no longer restarts the count, which goes on across
339 /// the parent's advances; the parent's number is still written before the
340 /// counter's own: `1.1`, `1.2`, then `2.3` after the second section.
341 ///
342 /// Only the parent is left out of what the count is kept under; the
343 /// parent's own ancestors still restart the count.
344 pub fn no_restart(mut self) -> Within {
345 self.no_restart = true;
346 self
347 }
348
349 /// Builder: the parent's number is followed by `text` instead of a full
350 /// stop. The text is FLM.
351 pub fn joined_by(mut self, text: impl Into<String>) -> Within {
352 self.joiner = WithinJoinerSpec::Joined(text.into());
353 self
354 }
355
356 /// Builder: the ancestors' numbers are written by the within template
357 /// `text`.
358 ///
359 /// A within template is FLM in which `#{name}` writes the counter `name`:
360 /// that counter's value in that counter's own counter style, the number
361 /// alone with no word and no delimiters, preceded by its own ancestors'
362 /// numbers. `#{_parent}` ([`PARENT_PLACEHOLDER`]) writes the parent that
363 /// applies in the same way: the only parent, or among several the one
364 /// advanced most recently. Every other character is written as given, and
365 /// markup may surround a substitution: `\textbf{#{flm.headings.section}}.`
366 /// writes the section's number in bold. A counter's name is the whole text
367 /// between the braces, dots included.
368 ///
369 /// A substitution may carry keys between brackets, separated by commas:
370 /// `#[Roman]{flm.headings.section}` writes the section in that [number
371 /// format](super::NumberFormat) instead of in its own counter style's, and
372 /// `#[bare]{flm.headings.section}` writes the section's own number without
373 /// its ancestors' numbers. A key that is neither `bare` nor the name of a
374 /// number format is refused when the template is compiled.
375 ///
376 /// The template writes one [part](super::Part) per substitution, holding
377 /// the text after it (the text before the first substitution belongs to
378 /// the first part); a template that markup prevents from being cut at its
379 /// substitutions writes one part for all of them. A template that holds
380 /// text and no substitution writes one part that shows no ancestor, and
381 /// the empty template writes no part. To write nothing of the parent,
382 /// [`displayed_bare`](Within::displayed_bare) says so directly.
383 pub fn template(mut self, text: impl Into<String>) -> Within {
384 self.joiner = WithinJoinerSpec::Template(text.into());
385 self
386 }
387
388 /// Builder: nothing of the ancestors is written. The counter still
389 /// restarts under its parent (it is counted separately for each value of
390 /// the parent), and its number is shown **bare**, that is, without its
391 /// parents' numbers, as `#[bare]{counter}` writes an ancestor in a
392 /// [within template](Within::template).
393 pub fn displayed_bare(mut self) -> Within {
394 self.joiner = WithinJoinerSpec::Bare;
395 self
396 }
397
398 /// Builder: the ancestors' numbers are written by the within-joiner
399 /// registered under `name` in [`WITHIN_JOINERS_SLOT`].
400 pub fn joiner_named(mut self, name: impl Into<Name>) -> Within {
401 self.joiner = WithinJoinerSpec::Named(name.into());
402 self
403 }
404}
405
406/// A counter, as the feature that declares it contributes it to the service
407/// slot [`COUNTERS_SLOT`].
408///
409/// A counter is a dotted name under which things are counted in document
410/// order, declared by a feature together with the counter it is numbered
411/// within; its value at a reference point is a number with optional
412/// sub-numbers ([`CounterValue`](super::CounterValue)). The declaration gives
413/// the counter's name, the counter style its numbers are shown in by default,
414/// the counter it is numbered within ([`Within`]), and the counter's nesting
415/// joiner ([`nesting`](CounterDecl::nesting)). The concepts overview presents
416/// counters and counter styles together ([counters and counter
417/// styles](crate::guide::concepts_overview#counters-and-counter-styles)).
418///
419/// The numbering feature numbers every reference point whose number source
420/// ([`NumberSource`](crate::model::aspects::NumberSource)) gives a declared
421/// counter. The feature that owns the point decides whether the point
422/// gives a number source (the numbering depth of the headings feature, the
423/// switch for numbered equations of the mathematics feature); the numbering
424/// feature has no switch of its own.
425///
426/// A counter's name is dotted and owned by the feature that declares it, like
427/// every name the library registers: `flm.headings.section`,
428/// `flm.math.equation`, and a name under a prefix of its own for a counter
429/// that a third party declares. One feature declares a counter, and a name is
430/// declared once per registry; the points of any feature may count in it, and
431/// points of several kinds that count in one counter form one sequence. A
432/// counter style's name is dotted and owned in the same way
433/// (`flm.math.style.equation`) and is separate from the counter's name,
434/// because two features may each declare a counter style for the same
435/// counter.
436///
437/// # Examples
438///
439/// ```
440/// use flm_core::stdlib::features::numbering::{CounterDecl, Within};
441///
442/// // Theorems count from one in every section, and are shown `2.13`.
443/// let decl = CounterDecl::new("example.theorem", "example.style.theorem")
444/// .docs("The theorems of the document.")
445/// .within(Within::parent("flm.headings.section"));
446/// assert!(decl.within.is_some());
447/// ```
448#[derive(Clone, PartialEq, Eq, Hash, Debug)]
449pub struct CounterDecl {
450 /// The counter's name, dotted and owned by the declaring feature, such as
451 /// `flm.headings.section` or `flm.math.equation`. Two declarations of one
452 /// name fail the registry build, and so does a name beginning with
453 /// [`RESERVED_PREFIX`].
454 pub name: Name,
455 /// One sentence saying what the counter counts. The numbering feature
456 /// keeps it with the declaration and does not display it.
457 pub docs: String,
458 /// The name of the counter style in which a point's number is shown when
459 /// the point's number source gives no other. It is also the counter style
460 /// in which this counter's number is written as an ancestor until a point
461 /// advances the counter. A counter style no feature declares fails the
462 /// registry build.
463 pub default_style: Name,
464 /// The counter within which this counter is numbered, or `None` for a
465 /// counter numbered within nothing, which is never restarted.
466 pub within: Option<Within>,
467 /// The counter's **nesting joiner**: what a point that counts in a
468 /// *nested* scoped instance of this counter writes of the enclosing
469 /// instance's number before its own, or `None` for
470 /// [`WithinJoinerSpec::Bare`], which writes nothing of it.
471 ///
472 /// A scoped instance is an independent sequence of the counter's values
473 /// attached to an enclosing node
474 /// ([`NumberSource::instances`](crate::model::aspects::NumberSource::instances)).
475 /// An instance inside another is numbered within the enclosing instance's
476 /// current value, which the records of its points carry as their last
477 /// ancestor. The nesting joiner writes that ancestor, in any of the four
478 /// forms a [`Within`] may take: `Joined(".")` and
479 /// `Template("#{_parent}.")` both write `2.(b)` for the second item of a
480 /// list nested in the second item of another list whose items are written
481 /// `1`, `2`, and the default writes `(b)`. The ancestor is written in its
482 /// own counter style, so where the enclosing items are written `1.`, `2.`,
483 /// `Template("#{_parent}")` writes `2.(b)`. In a within template,
484 /// `#{_parent}` and the counter's own name both refer to the enclosing
485 /// instance.
486 ///
487 /// The nesting joiner is compiled when the registry is built, as the
488 /// counter's [`within`](CounterDecl::within) is. It may write only
489 /// counters that are ancestors of a nested point under every chain of
490 /// counters the counter may be numbered within, that is, the counter
491 /// itself and the counters it is numbered within; any other counter fails
492 /// the registry build.
493 pub nesting: Option<WithinJoinerSpec>,
494}
495
496impl CounterDecl {
497 /// Returns a counter named `name`, shown in the counter style
498 /// `default_style`, numbered within nothing, with no nesting joiner and an
499 /// empty description.
500 pub fn new(name: impl Into<Name>, default_style: impl Into<Name>) -> CounterDecl {
501 CounterDecl {
502 name: name.into(),
503 docs: String::new(),
504 default_style: default_style.into(),
505 within: None,
506 nesting: None,
507 }
508 }
509
510 /// Builder: sets the sentence that says what the counter counts
511 /// ([`docs`](CounterDecl::docs)). Without the cargo feature `docs`, the
512 /// text is dropped and the field stays empty.
513 pub fn docs(mut self, docs: impl Into<String>) -> CounterDecl {
514 self.docs = crate::kept_docs(docs);
515 self
516 }
517
518 /// Builder: sets the counter within which this counter is numbered
519 /// ([`within`](CounterDecl::within)).
520 pub fn within(mut self, within: Within) -> CounterDecl {
521 self.within = Some(within);
522 self
523 }
524
525 /// Builder: sets the nesting joiner, what a point of a nested scoped
526 /// instance writes of the enclosing instance's number
527 /// ([`nesting`](CounterDecl::nesting)).
528 pub fn nesting(mut self, joiner: WithinJoinerSpec) -> CounterDecl {
529 self.nesting = Some(joiner);
530 self
531 }
532}
533
534impl Within {
535 /// Writes this value into `out` for a registry digest, every field of it:
536 /// the parents, the within-joiner and `no_restart`, each text preceded by
537 /// its length so that two different values never write the same bytes.
538 ///
539 /// The fields are destructured by name, so a field added to `Within` and
540 /// not written here fails to compile.
541 pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
542 let Within { parents, joiner, no_restart } = self;
543 match parents {
544 Parents::One(name) => {
545 out.push(0);
546 digest_text(out, name.as_str());
547 }
548 Parents::Any(names) => {
549 out.push(1);
550 out.extend_from_slice(&(names.len() as u64).to_le_bytes());
551 for name in names {
552 digest_text(out, name.as_str());
553 }
554 }
555 Parents::Set(name) => {
556 out.push(2);
557 digest_text(out, name.as_str());
558 }
559 }
560 joiner.digest_into(out);
561 out.push(u8::from(*no_restart));
562 }
563}
564
565impl WithinJoinerSpec {
566 /// Writes this value into `out` for a registry digest: which form it is,
567 /// and its text or name preceded by its length, so that two different
568 /// values never write the same bytes. A feature whose configuration holds
569 /// a nesting joiner adds it to its digest through this function.
570 pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
571 match self {
572 WithinJoinerSpec::Joined(text) => {
573 out.push(0);
574 digest_text(out, text);
575 }
576 WithinJoinerSpec::Template(text) => {
577 out.push(1);
578 digest_text(out, text);
579 }
580 WithinJoinerSpec::Bare => out.push(2),
581 WithinJoinerSpec::Named(name) => {
582 out.push(3);
583 digest_text(out, name.as_str());
584 }
585 }
586 }
587}
588
589/// Why the parents of a [`Within`] give no counter to be numbered within.
590#[derive(Clone, PartialEq, Eq, Debug)]
591pub(super) enum ParentsError {
592 /// A parent set that no feature registers.
593 UnknownSet(Name),
594 /// An empty list of parents, or a parent set that holds no counter.
595 Empty,
596}
597
598impl Parents {
599 /// Returns the counters these parents may be, in their order: the one
600 /// parent, the list, or the counters of the parent set, looked up in
601 /// `sets`.
602 ///
603 /// # Errors
604 ///
605 /// [`ParentsError::UnknownSet`] for a parent set that `sets` does not
606 /// hold, and [`ParentsError::Empty`] when the result would hold no
607 /// counter.
608 pub(super) fn resolve(
609 &self,
610 sets: &std::collections::BTreeMap<Name, Vec<Name>>,
611 ) -> Result<Vec<Name>, ParentsError> {
612 let resolved = match self {
613 Parents::One(name) => vec![name.clone()],
614 Parents::Any(names) => names.clone(),
615 Parents::Set(name) => {
616 sets.get(name).cloned().ok_or_else(|| ParentsError::UnknownSet(name.clone()))?
617 }
618 };
619 if resolved.is_empty() {
620 return Err(ParentsError::Empty);
621 }
622 Ok(resolved)
623 }
624}
625
626/// Returns every chain of counters that `counter` may be numbered within,
627/// each chain outermost first, by walking the hierarchy with `parents_of`.
628///
629/// A counter with one parent has one chain: the parent's chain followed by the
630/// parent. A counter with several possible parents ([`Within::parents`],
631/// [`Within::parent_set`]) has one chain per parent, and a parent with several
632/// possible parents of its own multiplies the chains; which chain applies at a
633/// reference point is known only when the document is read. A counter
634/// numbered within nothing has one chain, the empty one.
635///
636/// The function serves two views of the hierarchy: the one the declarations
637/// make, which the registry build checks, and the one a document's numbering
638/// options leave, which the numbering stage counts by. `parents_of` returns
639/// the counters a counter may be numbered within in its own view, and an
640/// empty list both for a counter numbered within nothing and for a counter
641/// the view does not hold; the walk stops in both cases.
642///
643/// # Errors
644///
645/// The counters of a cycle, when the hierarchy leads back, through any of the
646/// parents, to a counter already on the path: the counter that the walk
647/// reached a second time, then each counter walked through after it.
648pub(super) fn chains_of(
649 counter: &Name,
650 parents_of: &impl Fn(&Name) -> Vec<Name>,
651) -> Result<Vec<Vec<Name>>, Vec<Name>> {
652 let mut path = vec![counter.clone()];
653 walk_chains(&mut path, parents_of)
654}
655
656/// [`chains_of`] for the last counter of `path`, where `path` holds the
657/// counters walked through to reach it.
658fn walk_chains(
659 path: &mut Vec<Name>,
660 parents_of: &impl Fn(&Name) -> Vec<Name>,
661) -> Result<Vec<Vec<Name>>, Vec<Name>> {
662 let current = path.last().expect("the path holds the counter walked from").clone();
663 let parents = parents_of(¤t);
664 if parents.is_empty() {
665 return Ok(vec![Vec::new()]);
666 }
667 let mut chains = Vec::new();
668 for parent in parents {
669 if let Some(start) = path.iter().position(|seen| *seen == parent) {
670 return Err(path[start..].to_vec());
671 }
672 path.push(parent.clone());
673 let above = walk_chains(path, parents_of);
674 path.pop();
675 for mut chain in above? {
676 chain.push(parent.clone());
677 chains.push(chain);
678 }
679 }
680 Ok(chains)
681}
682
683/// Writes `text` into `out` as its length followed by its bytes, so that two
684/// different lists of texts never write the same bytes.
685pub(super) fn digest_text(out: &mut Vec<u8>, text: &str) {
686 out.extend_from_slice(&(text.len() as u64).to_le_bytes());
687 out.extend_from_slice(text.as_bytes());
688}
689
690#[cfg(test)]
691mod tests {
692 use std::collections::BTreeMap;
693
694 use super::*;
695
696 /// The counters of a declared hierarchy, as a map from a counter's name
697 /// to the counters it may be numbered within.
698 fn hierarchy(entries: &[(&str, &[&str])]) -> BTreeMap<Name, Vec<Name>> {
699 entries
700 .iter()
701 .map(|(name, parents)| {
702 (Name::new(*name), parents.iter().map(|parent| Name::new(*parent)).collect())
703 })
704 .collect()
705 }
706
707 /// [`chains_of`] over such a map, each chain written with dots.
708 fn chains(counters: &BTreeMap<Name, Vec<Name>>, counter: &str) -> Result<Vec<String>, Vec<Name>> {
709 let walked =
710 chains_of(&Name::new(counter), &|name| counters.get(name).cloned().unwrap_or_default())?;
711 Ok(walked
712 .iter()
713 .map(|chain| chain.iter().map(Name::as_str).collect::<Vec<_>>().join("."))
714 .collect())
715 }
716
717 #[test]
718 fn a_chain_runs_outermost_first() {
719 let counters = hierarchy(&[
720 ("section", &[]),
721 ("subsection", &["section"]),
722 ("equation", &["subsection"]),
723 ]);
724 assert_eq!(chains(&counters, "equation"), Ok(vec!["section.subsection".to_string()]));
725 assert_eq!(chains(&counters, "section"), Ok(vec![String::new()]));
726 }
727
728 #[test]
729 fn a_counter_with_several_parents_has_one_chain_per_parent() {
730 let counters = hierarchy(&[
731 ("chapter", &[]),
732 ("section", &["chapter"]),
733 ("equation", &["chapter", "section"]),
734 ]);
735 let walked = chains(&counters, "equation").expect("acyclic");
736 assert_eq!(walked, ["chapter", "chapter.section"]);
737 }
738
739 #[test]
740 fn a_hierarchy_that_leads_back_to_itself_is_a_cycle() {
741 let counters = hierarchy(&[("a", &["b"]), ("b", &["c"]), ("c", &["a"])]);
742 let cycle = chains(&counters, "a").expect_err("a cycle");
743 let names: Vec<&str> = cycle.iter().map(Name::as_str).collect();
744 assert_eq!(names, ["a", "b", "c"]);
745 }
746
747 #[test]
748 fn a_cycle_through_any_one_parent_is_a_cycle() {
749 let counters = hierarchy(&[("a", &["x", "b"]), ("b", &["a"]), ("x", &[])]);
750 let cycle = chains(&counters, "a").expect_err("a cycle");
751 let names: Vec<&str> = cycle.iter().map(Name::as_str).collect();
752 assert_eq!(names, ["a", "b"]);
753 }
754
755 #[test]
756 fn a_walk_stops_at_a_counter_the_view_does_not_know() {
757 let counters = hierarchy(&[("equation", &["section"])]);
758 assert_eq!(chains(&counters, "equation"), Ok(vec!["section".to_string()]));
759 }
760
761 #[test]
762 fn a_counter_is_declared_within_nothing() {
763 let decl = CounterDecl::new("equation", "flm.math.style.equation");
764 assert!(decl.within.is_none());
765 assert_eq!(decl.name.as_str(), "equation");
766 }
767
768 #[test]
769 fn the_builders_set_what_they_name() {
770 let decl = CounterDecl::new("subsection", "flm.heading.style.subsection")
771 .docs("Subsections.")
772 .within(Within::parent("section"));
773 assert_eq!(decl.docs, if cfg!(feature = "docs") { "Subsections." } else { "" });
774 let within = decl.within.expect("declared");
775 assert_eq!(within.parents, Parents::One(Name::new("section")));
776 assert_eq!(within.joiner, WithinJoinerSpec::Joined(".".to_string()));
777 assert!(!within.no_restart);
778
779 let any = Within::parents(["chapter", "section"]).no_restart();
780 assert_eq!(any.parents, Parents::Any(vec![Name::new("chapter"), Name::new("section")]));
781 assert!(any.no_restart);
782 let set = Within::parent_set("flm.headings.levels").displayed_bare();
783 assert_eq!(set.parents, Parents::Set(Name::new("flm.headings.levels")));
784 assert_eq!(set.joiner, WithinJoinerSpec::Bare);
785 }
786
787 #[test]
788 fn a_counter_has_no_nesting_joiner_until_it_declares_one() {
789 let decl = CounterDecl::new("t.list", "t.style.list");
790 assert!(decl.nesting.is_none());
791 let nested = decl.nesting(WithinJoinerSpec::Template("#{_parent}.".to_string()));
792 assert_eq!(nested.nesting, Some(WithinJoinerSpec::Template("#{_parent}.".to_string())));
793 }
794
795 #[test]
796 fn every_form_of_a_joiner_digests_differently() {
797 let digest = |spec: &WithinJoinerSpec| {
798 let mut out = Vec::new();
799 spec.digest_into(&mut out);
800 out
801 };
802 let forms = [
803 WithinJoinerSpec::Joined(".".to_string()),
804 WithinJoinerSpec::Template(".".to_string()),
805 WithinJoinerSpec::Bare,
806 WithinJoinerSpec::Named(Name::new(".")),
807 ];
808 for (index, one) in forms.iter().enumerate() {
809 for other in &forms[index + 1..] {
810 assert_ne!(digest(one), digest(other), "{one:?} and {other:?}");
811 }
812 }
813 }
814
815 #[test]
816 fn every_field_of_a_within_changes_its_digest() {
817 let digest = |within: &Within| {
818 let mut out = Vec::new();
819 within.digest_into(&mut out);
820 out
821 };
822 let base = Within::parent("section");
823 let variants = [
824 Within::parent("chapter"),
825 Within::parents(["section"]),
826 Within::parent_set("section"),
827 Within::parent("section").joined_by("-"),
828 Within::parent("section").template("#{section}."),
829 Within::parent("section").displayed_bare(),
830 Within::parent("section").joiner_named("section"),
831 Within::parent("section").no_restart(),
832 ];
833 for variant in &variants {
834 assert_ne!(digest(&base), digest(variant), "{variant:?}");
835 }
836 assert_eq!(digest(&base), digest(&Within::parent("section")));
837 }
838}