flm_core/stdlib/features/numbering/table.rs
1//! The counter table, `flm.counters` ([`COUNTERS`], a [`Counters`]): what the
2//! numbering stage recorded for every reference point it read, and the
3//! methods that write those records as the numbers a reader sees.
4//!
5//! A record ([`CounterRecord`]) holds a counter value and no text. A lowering
6//! rule writes the number from the record where it shows the number, with
7//! [`Counters::format`], [`Counters::format_in_style`] or
8//! [`Counters::format_many`], so that a number is counted once and stored in
9//! one form only, and the same record serves every backend and every
10//! reference to the point.
11
12use std::collections::BTreeMap;
13use std::sync::Arc;
14
15use techy::core::node::NodeTree;
16use techy::serialize::SerialValue;
17
18use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
19use crate::model::addr::NodeAddr;
20use crate::model::aspects::PointId;
21use crate::model::names::Name;
22use crate::lang::Flm;
23
24use super::many::format_many;
25use super::joiner::{written_with_keys, CompiledWithinJoiner, JoinCx};
26use super::style::{format, on_worker, Ancestor, CounterStyle, FormatError, FormatOptions, Parent};
27use super::template::AncestorKeys;
28use super::writer::NumberedValue;
29use super::value::CounterValue;
30
31/// The typed name of the counter table, `flm.counters`, whose value is a
32/// [`Counters`].
33///
34/// The numbering stage writes the table. The lowering rules that show numbers
35/// declare an optional read of it, so that they still run, without numbers,
36/// in a registry without the numbering feature.
37pub const COUNTERS: TableName<Counters> = TableName::new("flm.counters");
38
39/// What the numbering stage recorded for one numbered reference point: the
40/// counter the point counts in, that counter's value at the point, the
41/// counters it is numbered within with their own values, and the counter
42/// style in which its number is shown.
43///
44/// The record holds no text. Everything a reader sees is built from it when it
45/// is shown, so the same record serves every backend and every reference to
46/// the point.
47///
48/// The ancestors are the whole chain, outermost first, in the order
49/// [`Parent`] requires: the ancestors of `ancestors[i]` are `ancestors[..i]`.
50/// For a counter with several possible parents, the chain is the one that
51/// applied at the point: the parent advanced most recently, preceded by its
52/// own ancestors.
53///
54/// A point counted in a **scoped instance** of its counter (an independent
55/// sequence of the counter's values attached to an enclosing node, such as a
56/// list environment) records that instance
57/// ([`instance`](CounterRecord::instance)). Where the instance is nested in
58/// another instance of the same counter, the record's last ancestor is the
59/// enclosing instance's value at the point, which records its own instance,
60/// and the number is written with the counter's nesting joiner
61/// ([`CounterDecl::nesting`](super::CounterDecl::nesting)) instead of the
62/// counter's within-joiner; the ancestors before it are the enclosing
63/// instance's own, down to the counters within which the outermost instance
64/// is numbered. A record is *nested* exactly when its last ancestor is of its
65/// own counter, since no counter is otherwise numbered within itself.
66#[derive(Clone, Debug)]
67pub struct CounterRecord {
68 /// The counter the point counts in.
69 pub counter: Name,
70 /// The counter's value at the point.
71 pub value: CounterValue,
72 /// The counters this one is numbered within, outermost first, each with
73 /// its value at the point, the counter style it is written in and its own
74 /// within-joiner.
75 pub ancestors: Vec<Ancestor>,
76 /// The counter style in which the point's own number is shown: the
77 /// counter style its number source gives, or, for a point that carries a
78 /// number template of its own, that counter style with its number format
79 /// replaced by the template
80 /// ([`CounterStyle::with_number_format`](super::CounterStyle::with_number_format)).
81 pub style: Arc<CounterStyle>,
82 /// The scoped instance the point was counted in, as the address of the
83 /// node that instance is attached to (the last of the point's
84 /// [instances](crate::model::aspects::NumberSource::instances)), or `None`
85 /// for a point counted in the counter's single sequence through the
86 /// document.
87 pub instance: Option<NodeAddr>,
88}
89
90impl CounterRecord {
91 /// Returns whether the point was counted in a scoped instance nested in
92 /// another instance of the same counter: its last ancestor is then of its
93 /// own counter, and its number is written with the counter's nesting
94 /// joiner.
95 pub fn is_nested(&self) -> bool {
96 is_nested(&self.counter, &self.ancestors)
97 }
98}
99
100/// Returns whether a value of `counter` whose ancestors are `ancestors` was
101/// counted in a nested scoped instance: its last ancestor is of the same
102/// counter. The numbering stage, which chooses each ancestor's joiner, and the
103/// table, which chooses a record's joiner, both use this test.
104pub(super) fn is_nested(counter: &Name, ancestors: &[Ancestor]) -> bool {
105 ancestors.last().is_some_and(|last| &last.counter == counter)
106}
107
108/// One stretch of a number as the counter table writes it: a small tree of
109/// content, and the reference point it links to.
110///
111/// It is a [`Segment`](super::Segment) whose link mark has been replaced by
112/// the reference point at that position. A lowering rule splices the content
113/// with [`Lowerer::splice`](crate::core::lowering::Lowerer::splice) and builds
114/// the link from the point, for instance through the anchor the point was
115/// given ([`ANCHORS`](crate::stdlib::features::refs::ANCHORS)). A segment
116/// that links to no point is a text between two numbers, or a word or
117/// delimiter that the counter style keeps out of the link.
118#[derive(Clone, Debug)]
119pub struct NumberSegment {
120 content: Arc<NodeTree<Flm>>,
121 link: Option<PointId>,
122}
123
124impl NumberSegment {
125 /// A segment of the content `content` (a synthesized value whose root is a
126 /// list node over the content's nodes), linking to the reference point
127 /// `link`, or to none.
128 pub fn new(content: Arc<NodeTree<Flm>>, link: Option<PointId>) -> NumberSegment {
129 NumberSegment { content, link }
130 }
131
132 /// Returns the segment's content, a synthesized value whose root is a
133 /// list node over the content's nodes ([synthesized
134 /// values](crate::guide::concepts_overview#synthesized-values)).
135 pub fn content(&self) -> &Arc<NodeTree<Flm>> {
136 &self.content
137 }
138
139 /// Returns the reference point this segment links to, or `None` when the
140 /// segment is not part of a link.
141 pub fn link(&self) -> Option<PointId> {
142 self.link
143 }
144}
145
146/// The numbers of several reference points, written in one group per
147/// counter style ([`Counters::format_many`]), and the points that have no
148/// number.
149///
150/// A group is what the [number writer](super::NumberWriter) of one counter
151/// style wrote for the points shown in that counter style, such as
152/// `Eqs.~(1 and 2)`, and the groups are in the order in which their counter
153/// styles first occur among the points. The table does not join the groups:
154/// the caller writes them as the items of its own list, with texts of its own
155/// between them. The points without a number keep the caller's order; only
156/// the caller knows what an unnumbered point shows (its content, or the label
157/// it was given), so the table returns the points instead of writing them.
158#[derive(Clone, Debug, Default)]
159pub struct ManyNumbers {
160 /// Per counter style, in the order of first occurrence, the segments of
161 /// its numbers, each linking to its own point or to nothing.
162 pub groups: Vec<Vec<NumberSegment>>,
163 /// The points the table holds no number for, in the caller's order.
164 pub unnumbered: Vec<PointId>,
165}
166
167/// The counter table, `flm.counters`: every reference point the numbering
168/// stage read, each with its record ([`CounterRecord`]) or with nothing for a
169/// point that is not numbered.
170///
171/// A point that the table does not hold at all is a point the stage never
172/// read, such as a point inside a synthesized value, which is not part of the
173/// document; this differs from a point the stage read and did not number.
174/// [`Counters::lookup`] tells the two apart, as
175/// [`Anchors::lookup`](crate::stdlib::features::refs::Anchors::lookup) does
176/// for anchors.
177///
178/// The table also carries the compiled counter styles and within-joiners with
179/// which the numbers are written (the counter styles in the records, the
180/// within-joiners per counter), so that a lowering rule writes a number from
181/// the table alone, without the registry. It also carries every counter style
182/// the registry declares, compiled, with the host's replacements applied,
183/// whether or not a record of this document uses it: [`Counters::style`]
184/// returns one by name, so that a rule may show a point's number in a declared
185/// counter style other than its record's, through
186/// [`Counters::format_in_style`].
187///
188/// The numbering stage builds the table with [`Counters::insert`],
189/// [`Counters::number_within`] and [`Counters::number_nested`]; a caller that
190/// builds a table of its own, for instance in a test, uses the same methods.
191#[derive(Debug, Default)]
192pub struct Counters {
193 /// From a point to its record; `None` for a point the stage read and did
194 /// not number.
195 records: BTreeMap<PointId, Option<CounterRecord>>,
196 /// Per counter, the within-joiner that writes its ancestors' numbers
197 /// before its own, as the hierarchy of this run made it. A counter
198 /// numbered within nothing has no entry.
199 hierarchy: BTreeMap<Name, Arc<dyn CompiledWithinJoiner>>,
200 /// Per counter, the nesting joiner, which writes the enclosing instance's
201 /// number before the number of a point of a nested scoped instance.
202 nesting: BTreeMap<Name, Arc<dyn CompiledWithinJoiner>>,
203 /// Every declared counter style, compiled, by name, with the host's
204 /// replacements applied: a single map per registry, shared by the tables
205 /// of every run instead of being copied into each.
206 styles: Arc<BTreeMap<Name, Arc<CounterStyle>>>,
207}
208
209impl Counters {
210 /// Records `record` for `point`; `None` records that the point was read
211 /// and not numbered. A record already held for `point` is replaced.
212 pub fn insert(&mut self, point: PointId, record: Option<CounterRecord>) {
213 self.records.insert(point, record);
214 }
215
216 /// Records `joiner` as the within-joiner that writes `counter`'s ancestors'
217 /// numbers before its number.
218 pub fn number_within(
219 &mut self,
220 counter: impl Into<Name>,
221 joiner: Arc<dyn CompiledWithinJoiner>,
222 ) {
223 self.hierarchy.insert(counter.into(), joiner);
224 }
225
226 /// Records `joiner` as the nesting joiner of `counter`, which writes the
227 /// enclosing instance's number before the number of a point of a nested
228 /// scoped instance of `counter`.
229 pub fn number_nested(
230 &mut self,
231 counter: impl Into<Name>,
232 joiner: Arc<dyn CompiledWithinJoiner>,
233 ) {
234 self.nesting.insert(counter.into(), joiner);
235 }
236
237 /// Makes the table carry `styles`, every declared counter style compiled,
238 /// which [`Counters::style`] reads.
239 pub(super) fn carry_styles(&mut self, styles: Arc<BTreeMap<Name, Arc<CounterStyle>>>) {
240 self.styles = styles;
241 }
242
243 /// Returns the compiled counter style declared under `name`, or `None`
244 /// when no feature declares a counter style of that name.
245 ///
246 /// Every counter style a feature declares is returned, whether or not a
247 /// record of this document uses it, and where the host replaced the
248 /// declaration through [`NumberingConfig`](super::NumberingConfig), the
249 /// result is the replacement. A counter style derived for a point's own
250 /// number template is not declared and is not returned here; the point's
251 /// record holds it ([`CounterRecord::style`]).
252 ///
253 /// A lowering rule shows a point's number in a declared counter style
254 /// other than its record's (for instance a mark written in a counter style
255 /// of its own, beside the counter style that references use) by passing
256 /// the result to [`Counters::format_in_style`], without the registry. The
257 /// counter style must declare at least as many sub-levels as the point's
258 /// value carries, or the writing fails with
259 /// [`FormatError::UndeclaredSubLevel`](super::FormatError::UndeclaredSubLevel).
260 ///
261 /// A table that the numbering stage did not write (a default value)
262 /// carries no counter style and returns `None` for every name.
263 pub fn style(&self, name: &Name) -> Option<&Arc<CounterStyle>> {
264 self.styles.get(name)
265 }
266
267 /// Returns the record of `point`, or `None` both for a point the stage
268 /// never read and for one it did not number. A caller that must tell the
269 /// two apart calls [`Counters::lookup`].
270 pub fn record(&self, point: PointId) -> Option<&CounterRecord> {
271 self.records.get(&point).and_then(Option::as_ref)
272 }
273
274 /// Returns what the table holds for `point`: `None` when the stage never
275 /// read it, `Some(None)` when it read it and gave it no number, and
276 /// `Some(Some(record))` when it numbered it.
277 pub fn lookup(&self, point: PointId) -> Option<Option<&CounterRecord>> {
278 self.records.get(&point).map(Option::as_ref)
279 }
280
281 /// Returns how many points the table holds, numbered or not.
282 pub fn len(&self) -> usize {
283 self.records.len()
284 }
285
286 /// Returns whether the table holds no point at all.
287 pub fn is_empty(&self) -> bool {
288 self.records.is_empty()
289 }
290
291 /// Returns every point the table holds, in the order of point
292 /// identifiers, with its record or `None`.
293 pub fn points(&self) -> impl Iterator<Item = (PointId, Option<&CounterRecord>)> + '_ {
294 self.records.iter().map(|(point, record)| (*point, record.as_ref()))
295 }
296
297 /// Returns the part of `record`'s number that comes from the counters it
298 /// is numbered within, or `None` for a counter numbered within nothing.
299 // The joiner belongs to the counter and to the run's options, not to the
300 // point, so it is held once per counter here rather than in every record,
301 // where two copies could disagree.
302 fn parent_of<'a>(&'a self, record: &'a CounterRecord) -> Option<Parent<'a>> {
303 let joiner = self.joiner_of(record)?;
304 Some(Parent::new(joiner.as_ref(), &record.ancestors))
305 }
306
307 /// Returns the joiner that writes what comes before `record`'s own number:
308 /// the counter's nesting joiner for a point of a nested scoped instance,
309 /// else the counter's within-joiner, or `None` for a counter numbered
310 /// within nothing.
311 fn joiner_of(&self, record: &CounterRecord) -> Option<&Arc<dyn CompiledWithinJoiner>> {
312 if record.is_nested() {
313 self.nesting.get(&record.counter)
314 } else {
315 self.hierarchy.get(&record.counter)
316 }
317 }
318
319 /// Returns the number of `point`, written in the counter style its record
320 /// holds: `None` when the table holds no number for the point, and
321 /// otherwise the segments of the number, each linking to `point` or to
322 /// nothing.
323 ///
324 /// `options` says which variant of the prefix words to use, and whether
325 /// the word before the number and the delimiters around it are written.
326 ///
327 /// # Errors
328 ///
329 /// [`FormatError`] when the record and its counter style do not fit each
330 /// other, or when the content could not be built. The numbering stage
331 /// refuses a record that its counter style cannot write, so such an error
332 /// reveals a fault in the program, not in a document.
333 pub fn format(
334 &self,
335 point: PointId,
336 options: &FormatOptions,
337 ) -> Option<Result<Vec<NumberSegment>, FormatError>> {
338 let record = self.record(point)?;
339 let parent = self.parent_of(record);
340 Some(
341 format(&record.value, &record.style, parent, options)
342 .map(|segments| link_all(segments, &[point])),
343 )
344 }
345
346 /// Returns the number of `point` written in `style` instead of the
347 /// counter style its record holds: the recorded value, with `style`'s
348 /// number format, words and delimiters, preceded by the parts of the
349 /// counters it is numbered within, each written as the record holds it, in
350 /// its own counter style. Returns `None` when the table holds no number
351 /// for the point.
352 ///
353 /// A rule uses it to show a point's number in another form than the one a
354 /// reference to the point shows, without a second record. `style` is one
355 /// of two kinds:
356 ///
357 /// - a counter style derived from the record's own
358 /// ([`CounterStyle::with_number_format`](super::CounterStyle::with_number_format)),
359 /// which shares the sub-levels, words and number writer the record was
360 /// checked against. The lists feature writes the label beside a numbered
361 /// item in this way, through the list's label template, while the
362 /// record's counter style (from the list's reference template, its
363 /// `ref=`, see [`lists`](crate::stdlib::features::lists)) serves every
364 /// reference to the item;
365 /// - a declared counter style, looked up by its name with
366 /// [`Counters::style`], for instance for a mark written in a counter
367 /// style of its own.
368 ///
369 /// # Errors
370 ///
371 /// The same as [`Counters::format`]; a `style` that is not derived from
372 /// the record's own may also declare fewer sub-levels than the value
373 /// carries ([`FormatError::UndeclaredSubLevel`](super::FormatError::UndeclaredSubLevel)).
374 pub fn format_in_style(
375 &self,
376 point: PointId,
377 style: &CounterStyle,
378 options: &FormatOptions,
379 ) -> Option<Result<Vec<NumberSegment>, FormatError>> {
380 let record = self.record(point)?;
381 let parent = self.parent_of(record);
382 Some(format(&record.value, style, parent, options).map(|segments| link_all(segments, &[point])))
383 }
384
385 /// Returns the number of `point` as a placeholder carrying `keys` writes
386 /// it: with no key, what [`format`](Counters::format) writes with
387 /// `options`; with keys, the point's own number in the format the keys
388 /// give, preceded by the parts of the counters it is numbered within
389 /// unless the keys say `bare`, as a within template's `#[…]{counter}`
390 /// writes an ancestor (the word, the delimiters and the counter style's
391 /// number writer are then not used). Returns `None` when the table holds no
392 /// number for the point.
393 ///
394 /// # Errors
395 ///
396 /// The same as [`Counters::format`].
397 pub(crate) fn format_with_keys(
398 &self,
399 point: PointId,
400 keys: AncestorKeys,
401 options: &FormatOptions,
402 ) -> Option<Result<Vec<NumberSegment>, FormatError>> {
403 if keys == AncestorKeys::default() {
404 return self.format(point, options);
405 }
406 let record = self.record(point)?;
407 // The point is written as the last counter of its own chain, with its
408 // own joiner, so that the keys are read by the one function that
409 // reads them for a within template.
410 let mut own = Ancestor::new(
411 record.counter.clone(),
412 record.value.clone(),
413 Arc::clone(&record.style),
414 );
415 own.joiner = self.joiner_of(record).cloned();
416 own.instance = record.instance;
417 let mut chain = record.ancestors.clone();
418 chain.push(own);
419 let written = on_worker(|| {
420 let cx = JoinCx::new(&record.style);
421 written_with_keys(&chain, chain.len() - 1, keys, &cx)
422 });
423 Some(written.map(|part| vec![NumberSegment { content: part.content, link: Some(point) }]))
424 }
425
426 /// Returns the numbers of several points, written in one group per
427 /// counter style: `Eqs.~(1–3, 7, and 9)` for the points shown in one
428 /// counter style, `Thm. 1.1` for those of another.
429 ///
430 /// The points are grouped by the counter style they are shown in, each
431 /// group keeping the place of its first point, and each group is written
432 /// in one call of [`format_many`](super::format_many), with every point's
433 /// own ancestors. The counter style's [number writer](super::NumberWriter)
434 /// then decides which numbers of a group are written together and which
435 /// collapse into a range; the default writer groups the values by the
436 /// counters they are numbered within and never writes a range across two
437 /// such groups. The groups are returned separately, in
438 /// [`ManyNumbers::groups`], and the caller joins them. A point for which
439 /// the table holds no number is not written and is listed in
440 /// [`ManyNumbers::unnumbered`].
441 ///
442 /// Two points are in one group when their records hold the same compiled
443 /// counter style, compared by identity, not merely counter styles of the
444 /// same name. In a table
445 /// that the numbering stage wrote, a record holds either the compiled
446 /// counter style that the registry build made for its counter style's
447 /// name, or, for a point with a number template of its own
448 /// ([`NumberSource::number_format`](crate::model::aspects::NumberSource::number_format)),
449 /// the counter style derived from it with that template, which the stage
450 /// makes once per template text, counter style and run: the points of one
451 /// template are grouped together, and apart from the points written in the
452 /// declared counter style.
453 ///
454 /// With no numbered point at all, the result holds no group, and not the
455 /// counter style's text for an empty list: with no counter style there is
456 /// no such text to write.
457 ///
458 /// # Errors
459 ///
460 /// The same as [`Counters::format`].
461 pub fn format_many(
462 &self,
463 points: &[PointId],
464 options: &FormatOptions,
465 ) -> Result<ManyNumbers, FormatError> {
466 let mut unnumbered = Vec::new();
467 // The grouping keeps the place of the first point that fell into it,
468 // which is why it is a list searched through rather than a map: a
469 // style is told from another by identity.
470 let mut groups: Vec<StyleGroup<'_>> = Vec::new();
471 for point in points {
472 let Some(record) = self.record(*point) else {
473 unnumbered.push(*point);
474 continue;
475 };
476 let style = match groups
477 .iter()
478 .position(|group| Arc::ptr_eq(group.style, &record.style))
479 {
480 Some(index) => index,
481 None => {
482 groups.push(StyleGroup {
483 style: &record.style,
484 values: Vec::new(),
485 points: Vec::new(),
486 });
487 groups.len() - 1
488 }
489 };
490 let mut value = NumberedValue::new(&record.value);
491 if let Some(parent) = self.parent_of(record) {
492 value = value.within(parent);
493 }
494 if let Some(instance) = record.instance {
495 value = value.in_instance(instance);
496 }
497 groups[style].values.push(value);
498 groups[style].points.push(*point);
499 }
500
501 let mut written = Vec::with_capacity(groups.len());
502 for group in &groups {
503 let segments = format_many(group.style, &group.values, options)?;
504 written.push(link_all(segments, &group.points));
505 }
506 Ok(ManyNumbers { groups: written, unnumbered })
507 }
508}
509
510/// The points of one counter style, in the order of their first occurrence:
511/// the values that one call of the library's `format_many` writes, with the
512/// point of each value.
513struct StyleGroup<'a> {
514 style: &'a Arc<CounterStyle>,
515 values: Vec<NumberedValue<'a>>,
516 points: Vec<PointId>,
517}
518
519/// Returns the segments with their link marks replaced by points: a mark is a
520/// position among the values that were written, and `points` holds the point
521/// of each of those values, in the same order.
522fn link_all(segments: Vec<super::Segment>, points: &[PointId]) -> Vec<NumberSegment> {
523 segments
524 .into_iter()
525 .map(|segment| {
526 let link = segment.link().and_then(|position| points.get(position).copied());
527 NumberSegment { content: Arc::clone(segment.content()), link }
528 })
529 .collect()
530}
531
532impl Table for Counters {
533 fn absorb(&mut self, piece: Counters) {
534 self.records.extend(piece.records);
535 self.hierarchy.extend(piece.hierarchy);
536 self.nesting.extend(piece.nesting);
537 // The styles are the registry's, the same map for every piece the
538 // stage writes, so a piece carrying them is taken as it is. No merge
539 // is needed: the stage writes the table whole, as one piece.
540 if !piece.styles.is_empty() {
541 self.styles = piece.styles;
542 }
543 }
544
545 fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
546 SerialValue::Map(
547 self.records
548 .iter()
549 .map(|(point, record)| {
550 let value = match record {
551 Some(record) => {
552 let mut entries = vec![
553 (
554 "counter".to_string(),
555 SerialValue::Str(record.counter.to_string()),
556 ),
557 ("value".to_string(), components(&record.value)),
558 (
559 "style".to_string(),
560 SerialValue::Str(record.style.name().to_string()),
561 ),
562 ];
563 push_instance(cx, &mut entries, record.instance);
564 let within = record
565 .ancestors
566 .iter()
567 .map(|ancestor| {
568 let mut entries = vec![
569 (
570 "counter".to_string(),
571 SerialValue::Str(ancestor.counter.to_string()),
572 ),
573 ("value".to_string(), components(&ancestor.value)),
574 ];
575 push_instance(cx, &mut entries, ancestor.instance);
576 SerialValue::Map(entries)
577 })
578 .collect();
579 entries.push(("within".to_string(), SerialValue::List(within)));
580 SerialValue::Map(entries)
581 }
582 None => SerialValue::Null,
583 };
584 (point_key(cx, *point), value)
585 })
586 .collect(),
587 )
588 }
589
590 fn piece_class(&self) -> PieceClass {
591 // The styles are the registry's, not a fact about the document, and
592 // they are left out of the projection for the same reason: a table
593 // holding nothing else holds nothing of the document.
594 if self.records.is_empty() && self.hierarchy.is_empty() && self.nesting.is_empty() {
595 PieceClass::Empty
596 } else {
597 PieceClass::DocumentFact
598 }
599 }
600}
601
602impl SingletonTable for Counters {
603 const NAME: &'static str = "flm.counters";
604}
605
606/// Adds the key `instance`, the node the scoped instance is attached to, for a
607/// value counted in a scoped instance; a value of a counter's single sequence
608/// through the document has no such key in the projection.
609fn push_instance(
610 cx: &dyn ProjectCx,
611 entries: &mut Vec<(String, SerialValue)>,
612 instance: Option<NodeAddr>,
613) {
614 if let Some(instance) = instance {
615 entries.push(("instance".to_string(), cx.node_ref(instance)));
616 }
617}
618
619/// Returns a value's components as a list of integers, for a projection.
620fn components(value: &CounterValue) -> SerialValue {
621 SerialValue::List(value.components().iter().map(|part| SerialValue::Int(*part)).collect())
622}
623
624/// Returns a point written as `<node>#<index>`, the form in which every table
625/// about reference points writes a point in its projection.
626fn point_key(cx: &dyn ProjectCx, point: PointId) -> String {
627 format!("{}#{}", node_key(cx, point.addr), point.index)
628}
629
630/// Returns a node address as the projection context writes it.
631fn node_key(cx: &dyn ProjectCx, addr: NodeAddr) -> String {
632 match cx.node_ref(addr) {
633 SerialValue::Str(text) => text,
634 other => format!("{other:?}"),
635 }
636}