flm_core/stdlib/features/numbering/joiner.rs
1//! The within-joiner, which writes a counter's ancestors' numbers before the
2//! counter's own number, and the parts ([`Part`]) in which it writes them.
3//!
4//! A counter numbered within another shows something of that other counter
5//! before its own number: a subsection in section 1 is written `1.2`. The
6//! **within-joiner** decides what is shown. Four forms are built in
7//! ([`WithinJoinerSpec`](super::WithinJoinerSpec)): a joining text, a within
8//! template, nothing at all, and a within-joiner that a feature registered by
9//! name. The code that writes a number treats
10//! all four alike: given a chain of ancestors, a within-joiner returns a list
11//! of [`Part`]s.
12//!
13//! A within-joiner exists in two forms, as a declaration and as a compiled
14//! value. [`WithinJoiner`] is the declaration of a registered within-joiner: a
15//! name, and a method that compiles it against the built language.
16//! [`CompiledWithinJoiner`] is the compiled form of any of the four: it
17//! returns the parts, and it says which counters of a chain it writes, with
18//! which the registry build and the start of every run check the hierarchy.
19//!
20//! **The parts always come first**: they are written in order before the
21//! point's own number, which is never inside a part. Each part lists the
22//! ancestors it shows, so that a caller writing several numbers at once can
23//! find which parts two numbers share. A joining text gives one part per
24//! ancestor (`1.`, then `2.`, then the counter's own number `3`); a within
25//! template gives one part per `#{…}`, holding the text after it; the form
26//! that writes nothing of the ancestors gives no part; a registered
27//! within-joiner gives the parts its code gives, possibly a single part for
28//! everything.
29
30use std::collections::BTreeMap;
31use std::fmt;
32use std::sync::Arc;
33
34use techy::core::node::NodeTree;
35
36use crate::lang::rewrites::userdefs::template::{CompiledTemplate, TemplateLanguage};
37use crate::lang::{BuiltLang, Flm};
38use crate::model::names::Name;
39
40use super::decl::{Parents, Within, WithinJoinerSpec, PARENT_PLACEHOLDER};
41use super::formats::NumberFormat;
42use super::style::{
43 assemble_pieces, number_tree, parse_text, Ancestor, CounterStyle, FormatError, Piece, StyleError,
44};
45use super::template::{
46 compile_text, instantiate_template, occurrences_of, parse_keys, placeholder_starts,
47 within_vocabulary, AncestorKeys, Binding, Bindings,
48};
49use super::value::CounterValue;
50
51// --- what a joiner writes ---------------------------------------------------------------------
52
53/// A part: one unit of the text that a within-joiner writes before a point's
54/// own number, with the ancestors it shows and its content.
55///
56/// The parts of one number are written in order, and no part holds anything
57/// of the point's own number. A part that shows no ancestor is text only; a
58/// part that shows several ancestors is one in which the ancestors cannot be
59/// separated, such as a within template's `#{flm.headings.subsection}`, which
60/// writes the section's number and the subsection's together.
61#[derive(Clone, Debug)]
62pub struct Part {
63 /// The ancestors this part shows, outermost first, each with its value at
64 /// the point.
65 pub stands_for: Vec<(Name, CounterValue)>,
66 /// The part's content.
67 pub content: Arc<NodeTree<Flm>>,
68}
69
70impl Part {
71 /// Returns a part that shows the ancestors `stands_for`, with the content
72 /// `content`.
73 pub fn new(
74 stands_for: Vec<(Name, CounterValue)>,
75 content: Arc<NodeTree<Flm>>,
76 ) -> Part {
77 Part { stands_for, content }
78 }
79}
80
81// --- the two traits ---------------------------------------------------------------------------
82
83/// A within-joiner registered by name, as a feature declares it: its name,
84/// and how it compiles itself once the language is built.
85///
86/// A feature contributes one, wrapped in a [`WithinJoinerDecl`], to the
87/// service slot [`WITHIN_JOINERS_SLOT`](super::WITHIN_JOINERS_SLOT), and a
88/// counter asks for it by name with
89/// [`Within::joiner_named`](super::Within::joiner_named). Two within-joiners of
90/// one name fail the registry build.
91pub trait WithinJoiner: Send + Sync {
92 /// Returns the name by which counters ask for this within-joiner. It is
93 /// dotted and owned by the feature that declares it, such as
94 /// `example.numbering.compact`, as a counter style's name is.
95 fn name(&self) -> &Name;
96
97 /// Returns this within-joiner compiled with `cx`, which holds the built
98 /// language; every text it holds is parsed here.
99 ///
100 /// # Errors
101 ///
102 /// The [`StyleError`] of a text of its own that is not valid FLM, or of a
103 /// template it could not compile.
104 fn compile(&self, cx: &WithinCx<'_>) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError>;
105}
106
107/// A within-joiner as it is contributed to the service slot
108/// [`WITHIN_JOINERS_SLOT`](super::WITHIN_JOINERS_SLOT): a value that holds the
109/// within-joiner.
110///
111/// A service slot hands out its values as borrowed references, and the
112/// numbering feature uses a within-joiner long after the registry build has
113/// released them, so the service slot holds this value, of which the
114/// numbering feature keeps a copy.
115#[derive(Clone)]
116pub struct WithinJoinerDecl {
117 joiner: Arc<dyn WithinJoiner>,
118}
119
120impl WithinJoinerDecl {
121 /// Returns the declaration of `joiner`.
122 pub fn new(joiner: Arc<dyn WithinJoiner>) -> WithinJoinerDecl {
123 WithinJoinerDecl { joiner }
124 }
125
126 /// Returns the within-joiner it holds.
127 pub fn joiner(&self) -> &Arc<dyn WithinJoiner> {
128 &self.joiner
129 }
130}
131
132impl fmt::Debug for WithinJoinerDecl {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.debug_struct("WithinJoinerDecl")
135 .field("name", &self.joiner.name().as_str())
136 .finish()
137 }
138}
139
140/// A compiled within-joiner: what writes the ancestors' numbers.
141///
142/// Its two methods are called at different times.
143/// [`counters_written`](CompiledWithinJoiner::counters_written) is called when
144/// the registry is built and at the start of every run, once per chain of
145/// counters the counter may be numbered within, to check that every counter a
146/// number would show is in the chain it is shown with.
147/// [`parts`](CompiledWithinJoiner::parts) is called wherever a number is
148/// shown.
149pub trait CompiledWithinJoiner: Send + Sync + fmt::Debug {
150 /// Returns the counters this within-joiner writes, given `chain`: the
151 /// counters the point is numbered within, outermost first, the last of
152 /// them being the parent that applies.
153 ///
154 /// The method is called once per chain the counter may be numbered within,
155 /// before anything is counted, and every counter it returns must be in the
156 /// chain it was given. A declared within-joiner that fails this check
157 /// fails the registry build. At the start of a run, a within-joiner given
158 /// by the document's numbering options that fails it is refused, and the
159 /// counter keeps its declared place in the hierarchy; a declared
160 /// within-joiner that fails it because the options moved the counter's
161 /// ancestors makes the counter unnumbered for that run. `#{_parent}` and
162 /// the joining text return the last counter of the chain, so they pass for
163 /// every chain; a within template that refers to a counter by name passes
164 /// where that counter is an ancestor under every chain.
165 ///
166 /// Only the counters this within-joiner writes *itself* are returned, not
167 /// the ones an ancestor's own within-joiner writes: each counter of the
168 /// chain is checked with its own within-joiner in turn.
169 fn counters_written(&self, chain: &[Name]) -> Vec<Name>;
170
171 /// Returns the parts written before the point's own number.
172 ///
173 /// `ancestors` is the whole chain, outermost first, so the ancestors of
174 /// `ancestors[i]` are `ancestors[..i]`; `cx` builds the content.
175 ///
176 /// # Errors
177 ///
178 /// [`FormatError::UnknownAncestor`] when the within-joiner refers to a
179 /// counter that is not in the chain, and [`FormatError::NestingTooDeep`]
180 /// or [`FormatError::Failed`] when the content could not be built.
181 fn parts(&self, ancestors: &[Ancestor], cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError>;
182}
183
184// --- compiling ---------------------------------------------------------------------------------
185
186/// The context against which a within-joiner is compiled: the built language,
187/// the template language shared by every template of the numbering feature,
188/// the counters a within template may refer to, and the within-joiners
189/// registered by name.
190pub struct WithinCx<'a> {
191 lang: &'a BuiltLang,
192 language: &'a TemplateLanguage,
193 counters: &'a [Name],
194 joiners: &'a BTreeMap<Name, Arc<dyn WithinJoiner>>,
195}
196
197impl<'a> WithinCx<'a> {
198 /// Returns the context over `lang`, the shared template language, the
199 /// counters a within template may refer to and the registered
200 /// within-joiners.
201 pub(super) fn new(
202 lang: &'a BuiltLang,
203 language: &'a TemplateLanguage,
204 counters: &'a [Name],
205 joiners: &'a BTreeMap<Name, Arc<dyn WithinJoiner>>,
206 ) -> WithinCx<'a> {
207 WithinCx { lang, language, counters, joiners }
208 }
209
210 /// Returns the built language.
211 pub fn lang(&self) -> &BuiltLang {
212 self.lang
213 }
214
215 /// Returns `text` parsed as FLM, as every text of a counter style is
216 /// parsed. Warnings of the parse are dropped.
217 ///
218 /// # Errors
219 ///
220 /// The [`StyleError`] of a text that is not valid FLM.
221 pub fn parse(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, StyleError> {
222 let mut warnings = Vec::new();
223 parse_text(text, self.lang, &mut warnings)
224 }
225
226 /// Returns `text` compiled as a within template: `#{counter}` writes that
227 /// counter's number and `#{_parent}` the parent that applies, with the
228 /// keys that [`Within::template`](super::Within::template) describes.
229 /// `what` describes the owner of the text in a diagnostic.
230 ///
231 /// # Errors
232 ///
233 /// The [`StyleError`] of a text that is not valid FLM, of a `#{…}` that is
234 /// not a declared counter, and of an unknown key in brackets.
235 pub fn compile_template(
236 &self,
237 text: &str,
238 what: &str,
239 ) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError> {
240 let vocabulary = within_vocabulary(self.counters.iter());
241 let whole = compile_text(text, what, &vocabulary, self.lang, self.language)?;
242 let mut occurrences = Vec::new();
243 for (name, keys) in occurrences_of(&whole) {
244 let parsed = parse_keys(&keys).map_err(|key| StyleError::UnknownKey {
245 text: text.to_string(),
246 key,
247 })?;
248 occurrences.push(Occurrence {
249 counter: Name::new(name.as_str()),
250 keys: parsed,
251 written: keys,
252 });
253 }
254 let shape = self.split(text, &whole, &vocabulary, what, &occurrences);
255 Ok(Arc::new(Templated { text: text.to_string(), whole, occurrences, shape }))
256 }
257
258 /// Returns the template cut into one part per `#{…}`, or `None` when it
259 /// cannot be cut: when a piece of it between two substitutions is not
260 /// valid FLM on its own, as happens when markup surrounds a substitution.
261 /// The whole template is then one part.
262 fn split(
263 &self,
264 text: &str,
265 whole: &CompiledTemplate,
266 vocabulary: &crate::lang::rewrites::userdefs::template::PlaceholderVocabulary,
267 what: &str,
268 occurrences: &[Occurrence],
269 ) -> Option<Vec<CompiledTemplate>> {
270 let starts = placeholder_starts(whole);
271 if starts.len() != occurrences.len() || starts.is_empty() {
272 return None;
273 }
274 let mut cuts: Vec<usize> = Vec::with_capacity(starts.len() + 1);
275 cuts.push(0);
276 cuts.extend(starts.iter().skip(1).copied());
277 cuts.push(text.len());
278 let mut parts = Vec::with_capacity(starts.len());
279 for window in cuts.windows(2) {
280 let piece = text.get(window[0]..window[1])?;
281 let compiled = compile_text(piece, what, vocabulary, self.lang, self.language).ok()?;
282 if occurrences_of(&compiled).len() != 1 {
283 return None;
284 }
285 parts.push(compiled);
286 }
287 Some(parts)
288 }
289}
290
291impl Within {
292 /// Returns this declaration's within-joiner compiled against the built
293 /// language, ready to write parts.
294 ///
295 /// `counters` are the counters a within template may refer to, and
296 /// `joiners` the within-joiners registered by name. The numbering feature
297 /// compiles every declaration itself when the registry is built; a caller
298 /// that writes numbers of its own, outside the feature, compiles one with
299 /// this method. Each call builds a template language of its own when the
300 /// form needs one, whereas the feature builds one for all the
301 /// declarations it compiles.
302 ///
303 /// # Errors
304 ///
305 /// The [`StyleError`] of a text that is not valid FLM, of a template that
306 /// does not compile, and [`StyleError::UnknownJoiner`] for a name that no
307 /// within-joiner in `joiners` has.
308 pub fn compile(
309 &self,
310 lang: &BuiltLang,
311 counters: &[Name],
312 joiners: &[Arc<dyn WithinJoiner>],
313 ) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError> {
314 // The forms that hold no template are compiled without building a
315 // template language for them.
316 match &self.joiner {
317 WithinJoinerSpec::Joined(text) => {
318 let mut warnings = Vec::new();
319 return Ok(Arc::new(Joined {
320 described: described(&self.parents, text),
321 joiner: parse_text(text, lang, &mut warnings)?,
322 }));
323 }
324 WithinJoinerSpec::Bare => return Ok(Arc::new(Bare)),
325 _ => {}
326 }
327 let language = TemplateLanguage::new(lang).map_err(|errors| StyleError::ParseFailed {
328 text: joiner_text(self),
329 detail: errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "),
330 })?;
331 let registered: BTreeMap<Name, Arc<dyn WithinJoiner>> =
332 joiners.iter().map(|joiner| (joiner.name().clone(), Arc::clone(joiner))).collect();
333 let cx = WithinCx::new(lang, &language, counters, ®istered);
334 compile_within(self, &format!("the counter written within {}", self.parents.describe()), &cx)
335 }
336}
337
338/// Returns the within-joiner of `within`, compiled with `cx` and ready to
339/// write parts.
340///
341/// `what` describes the counter in a diagnostic.
342///
343/// # Errors
344///
345/// The [`StyleError`] of a text that is not valid FLM, of a template that does
346/// not compile, and [`StyleError::UnknownJoiner`] for a name that no feature
347/// registered.
348pub(super) fn compile_within(
349 within: &Within,
350 what: &str,
351 cx: &WithinCx<'_>,
352) -> Result<Arc<dyn CompiledWithinJoiner>, StyleError> {
353 match &within.joiner {
354 WithinJoinerSpec::Joined(text) => Ok(Arc::new(Joined {
355 described: described(&within.parents, text),
356 joiner: cx.parse(text)?,
357 })),
358 WithinJoinerSpec::Bare => Ok(Arc::new(Bare)),
359 WithinJoinerSpec::Template(text) => cx.compile_template(text, what),
360 WithinJoinerSpec::Named(name) => {
361 let Some(joiner) = cx.joiners.get(name) else {
362 return Err(StyleError::UnknownJoiner { name: name.clone() });
363 };
364 joiner.compile(cx)
365 }
366 }
367}
368
369// --- what content is made with -----------------------------------------------------------------
370
371/// The context with which a within-joiner builds content: an ancestor's
372/// number, the parts written before an ancestor, and text of its own.
373///
374/// Everything a reader sees is content, not characters, and a within-joiner
375/// builds content only through this context.
376pub struct JoinCx<'a> {
377 style: &'a CounterStyle,
378}
379
380impl<'a> JoinCx<'a> {
381 /// Returns the context over `style`, the counter style in which the whole
382 /// number is written. A within-joiner's own texts are attributed to this
383 /// counter style; an ancestor's number is written in the ancestor's own
384 /// counter style regardless.
385 pub(super) fn new(style: &'a CounterStyle) -> JoinCx<'a> {
386 JoinCx { style }
387 }
388
389 /// Returns `ancestor`'s own number, written in its own counter style: the
390 /// number alone, with no word, no delimiters and nothing of its own
391 /// ancestors.
392 ///
393 /// # Errors
394 ///
395 /// [`FormatError`] when the content could not be built, and
396 /// [`FormatError::UndeclaredSubLevel`] when the value carries a sub-number
397 /// for which the counter style declares no format.
398 pub fn number_of(&self, ancestor: &Ancestor) -> Result<Arc<NodeTree<Flm>>, FormatError> {
399 number_tree(&ancestor.style, &ancestor.value, None)
400 }
401
402 /// Returns `ancestor`'s own number written in `format` instead of the
403 /// format of its own counter style, its sub-numbers in that format too.
404 ///
405 /// # Errors
406 ///
407 /// The same as [`number_of`](JoinCx::number_of).
408 pub fn number_of_in(
409 &self,
410 ancestor: &Ancestor,
411 format: NumberFormat,
412 ) -> Result<Arc<NodeTree<Flm>>, FormatError> {
413 number_tree(&ancestor.style, &ancestor.value, Some(format))
414 }
415
416 /// Returns the parts written before `ancestors[index]`: what that
417 /// ancestor's own within-joiner writes of the ancestors before it. An
418 /// ancestor numbered within nothing has no part.
419 ///
420 /// Through this recursion, a within-joiner that refers to the counter
421 /// immediately above writes the whole chain: each step has strictly fewer
422 /// ancestors before it than the step before, so the writing always ends.
423 ///
424 /// # Errors
425 ///
426 /// The error the ancestor's own within-joiner returns.
427 pub fn parts_before(
428 &self,
429 ancestors: &[Ancestor],
430 index: usize,
431 ) -> Result<Vec<Part>, FormatError> {
432 let Some(ancestor) = ancestors.get(index) else { return Ok(Vec::new()) };
433 let Some(joiner) = &ancestor.joiner else { return Ok(Vec::new()) };
434 joiner.parts(&ancestors[..index], self)
435 }
436
437 /// Returns `text` as a small tree of content, built as the characters of
438 /// a number are: one text node attributed to the counter style's source.
439 ///
440 /// # Errors
441 ///
442 /// [`FormatError`] when the content could not be built.
443 pub fn literal(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, FormatError> {
444 assemble_pieces(self.style, &[Piece::Digits(text.to_string())])
445 }
446
447 /// Returns one tree of content that holds the nodes of `contents`, in
448 /// order.
449 ///
450 /// # Errors
451 ///
452 /// [`FormatError`] when the content could not be built.
453 pub fn joined(
454 &self,
455 contents: &[Arc<NodeTree<Flm>>],
456 ) -> Result<Arc<NodeTree<Flm>>, FormatError> {
457 let pieces: Vec<Piece<'_>> = contents.iter().map(Piece::Flm).collect();
458 assemble_pieces(self.style, &pieces)
459 }
460
461 /// Returns the counter style to which a within-joiner's content is
462 /// attributed.
463 pub(super) fn style(&self) -> &CounterStyle {
464 self.style
465 }
466}
467
468/// Returns the index of `counter` among `ancestors`, or the error that gives
469/// it. [`PARENT_PLACEHOLDER`] is the last ancestor, the parent that applies.
470///
471/// A counter appears more than once in a chain only as scoped instances of
472/// one counter nested in each other, and its name then refers to the
473/// innermost of them, the one immediately above: the enclosing instance of a
474/// nested point, whose own joiner writes the instances around it.
475fn place_of(
476 ancestors: &[Ancestor],
477 counter: &Name,
478 joiner: &str,
479) -> Result<usize, FormatError> {
480 let place = if counter.as_str() == PARENT_PLACEHOLDER {
481 ancestors.len().checked_sub(1)
482 } else {
483 ancestors.iter().rposition(|ancestor| &ancestor.counter == counter)
484 };
485 place.ok_or_else(|| FormatError::UnknownAncestor {
486 joiner: joiner.to_string(),
487 counter: counter.clone(),
488 })
489}
490
491/// Returns the parent that applies in `chain`, its last counter, as a list
492/// that holds it, or an empty list for an empty chain.
493fn parent_in(chain: &[Name]) -> Vec<Name> {
494 chain.last().cloned().into_iter().collect()
495}
496
497// --- the joining-text form ----------------------------------------------------------------------
498
499/// Returns how a [`Within`] writes the ancestors' numbers, as a text a
500/// diagnostic can give: the joining text, the within template, the
501/// within-joiner's name, or the empty text for the form that writes nothing of
502/// the ancestors.
503pub(super) fn joiner_text(within: &Within) -> String {
504 match &within.joiner {
505 WithinJoinerSpec::Joined(text) | WithinJoinerSpec::Template(text) => text.clone(),
506 WithinJoinerSpec::Named(name) => name.to_string(),
507 WithinJoinerSpec::Bare => String::new(),
508 }
509}
510
511/// Returns how a diagnostic describes a joining-text form: the parents it
512/// writes and the text after them, since the text alone does not identify
513/// the form.
514fn described(parents: &Parents, text: &str) -> String {
515 format!("{} joined by {text}", parents.describe())
516}
517
518/// The joining-text form: the number of the parent that applies (the only
519/// parent, or among several the one advanced most recently, which is the last
520/// counter of the chain in both cases), then a text.
521#[derive(Debug)]
522struct Joined {
523 described: String,
524 joiner: Arc<NodeTree<Flm>>,
525}
526
527impl CompiledWithinJoiner for Joined {
528 fn counters_written(&self, chain: &[Name]) -> Vec<Name> {
529 parent_in(chain)
530 }
531
532 fn parts(&self, ancestors: &[Ancestor], cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError> {
533 let place = place_of(ancestors, &Name::new(PARENT_PLACEHOLDER), &self.described)?;
534 let ancestor = &ancestors[place];
535 let mut parts = cx.parts_before(ancestors, place)?;
536 let content = cx.joined(&[cx.number_of(ancestor)?, Arc::clone(&self.joiner)])?;
537 parts.push(Part::new(
538 vec![(ancestor.counter.clone(), ancestor.value.clone())],
539 content,
540 ));
541 Ok(parts)
542 }
543}
544
545// --- the form that writes nothing of the ancestors ---------------------------------------------
546
547/// The bare form: the counter restarts under its parent, and nothing of the
548/// parent, or of any counter above it, is written before its own number.
549#[derive(Debug)]
550struct Bare;
551
552impl CompiledWithinJoiner for Bare {
553 fn counters_written(&self, _chain: &[Name]) -> Vec<Name> {
554 Vec::new()
555 }
556
557 fn parts(&self, _ancestors: &[Ancestor], _cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError> {
558 Ok(Vec::new())
559 }
560}
561
562// --- the template form -----------------------------------------------------------------------
563
564/// One `#{…}` of a within template: the counter it refers to, the keys it
565/// carries, and the text of those keys as written in the template.
566struct Occurrence {
567 counter: Name,
568 keys: AncestorKeys,
569 written: String,
570}
571
572impl fmt::Debug for Occurrence {
573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574 f.debug_struct("Occurrence")
575 .field("counter", &self.counter.as_str())
576 .field("keys", &self.keys)
577 .finish()
578 }
579}
580
581/// The within-template form.
582struct Templated {
583 text: String,
584 /// The whole template, which writes all parts as one where the template
585 /// cannot be cut.
586 whole: CompiledTemplate,
587 /// Every `#{…}` of the template, in order.
588 occurrences: Vec<Occurrence>,
589 /// The template cut into one piece per `#{…}`, or `None` when it cannot
590 /// be cut.
591 shape: Option<Vec<CompiledTemplate>>,
592}
593
594impl fmt::Debug for Templated {
595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
596 f.debug_struct("Templated").field("text", &self.text).finish_non_exhaustive()
597 }
598}
599
600impl Templated {
601 /// Returns what one `#{…}` is replaced by: the content, and the ancestors
602 /// that content shows. The result is a [`Part`] because a part has exactly
603 /// these two fields; the content is then substituted into the template,
604 /// and the result is the part the within-joiner returns.
605 fn written(
606 &self,
607 occurrence: &Occurrence,
608 ancestors: &[Ancestor],
609 cx: &JoinCx<'_>,
610 ) -> Result<Part, FormatError> {
611 let place = place_of(ancestors, &occurrence.counter, &self.text)?;
612 written_with_keys(ancestors, place, occurrence.keys, cx)
613 }
614}
615
616/// Returns what a placeholder carrying `keys` writes for `ancestors[place]`:
617/// that counter's number, in the format the keys give or else in its own
618/// counter style, preceded by the parts its own within-joiner writes of the
619/// ancestors before it unless the keys say `bare`; together with the
620/// counters that content shows.
621///
622/// This is the only function that applies the keys of `#[…]{counter}`: a
623/// within template writes each of its placeholders through it, and
624/// [`Counters::format_with_keys`](super::Counters::format_with_keys) writes a
625/// point's own number through it by placing the point at the end of its own
626/// chain.
627///
628/// # Errors
629///
630/// The error the ancestor's own within-joiner returns, and [`FormatError`]
631/// when the content could not be built.
632pub(super) fn written_with_keys(
633 ancestors: &[Ancestor],
634 place: usize,
635 keys: AncestorKeys,
636 cx: &JoinCx<'_>,
637) -> Result<Part, FormatError> {
638 let ancestor = &ancestors[place];
639 let mut stands_for = Vec::new();
640 let mut contents = Vec::new();
641 if !keys.bare {
642 for part in cx.parts_before(ancestors, place)? {
643 stands_for.extend(part.stands_for);
644 contents.push(part.content);
645 }
646 }
647 contents.push(match keys.format {
648 Some(format) => cx.number_of_in(ancestor, format)?,
649 None => cx.number_of(ancestor)?,
650 });
651 stands_for.push((ancestor.counter.clone(), ancestor.value.clone()));
652 Ok(Part::new(stands_for, cx.joined(&contents)?))
653}
654
655impl CompiledWithinJoiner for Templated {
656 fn counters_written(&self, chain: &[Name]) -> Vec<Name> {
657 let mut named: Vec<Name> = Vec::new();
658 for occurrence in &self.occurrences {
659 let written = if occurrence.counter.as_str() == PARENT_PLACEHOLDER {
660 parent_in(chain)
661 } else {
662 vec![occurrence.counter.clone()]
663 };
664 for counter in written {
665 if !named.contains(&counter) {
666 named.push(counter);
667 }
668 }
669 }
670 named
671 }
672
673 fn parts(&self, ancestors: &[Ancestor], cx: &JoinCx<'_>) -> Result<Vec<Part>, FormatError> {
674 let site = cx.style().site();
675 match &self.shape {
676 Some(pieces) => {
677 let mut parts = Vec::with_capacity(pieces.len());
678 for (piece, occurrence) in pieces.iter().zip(&self.occurrences) {
679 let written = self.written(occurrence, ancestors, cx)?;
680 let bindings = Bindings::new(vec![Binding {
681 name: occurrence.counter.as_str().to_string(),
682 keys: occurrence.written.clone(),
683 content: written.content,
684 }]);
685 parts.push(Part::new(
686 written.stands_for,
687 instantiate_template(&site, piece, &bindings)?,
688 ));
689 }
690 Ok(parts)
691 }
692 // A template with no `#{…}` at all writes one part standing for
693 // no ancestor, and an empty template writes no part.
694 None if self.text.is_empty() => Ok(Vec::new()),
695 None => {
696 let mut entries = Vec::with_capacity(self.occurrences.len());
697 let mut stands_for = Vec::new();
698 for occurrence in &self.occurrences {
699 let written = self.written(occurrence, ancestors, cx)?;
700 stands_for.extend(written.stands_for);
701 entries.push(Binding {
702 name: occurrence.counter.as_str().to_string(),
703 keys: occurrence.written.clone(),
704 content: written.content,
705 });
706 }
707 let bindings = Bindings::new(entries);
708 let content = instantiate_template(&site, &self.whole, &bindings)?;
709 Ok(vec![Part::new(stands_for, content)])
710 }
711 }
712 }
713}