Skip to main content

flm_core/stdlib/features/refs/
safe_labels.rs

1//! Safe labels: the keys that the recomposed LaTeX writes in place of the
2//! document's own labels, numbered in document order by a stage of the
3//! [`refs`](super) feature and recorded in the table [`SAFE_LABELS`].
4//!
5//! The `latex-recomposed` backend writes the document back as LaTeX and
6//! leaves references to LaTeX to resolve. A safe label ([`SafeLabels`]) is the
7//! key the recomposed LaTeX writes for an FLM label: `ref1`, `ref2`, … in the
8//! order the document first mentions the labels, one count per document
9//! regardless of the label's type. An FLM label such as `sec:intro` or
10//! `eq:my equation` is not a safe LaTeX key (LaTeX itself accepts a colon or a
11//! space, but not every package that reads label keys does), so the
12//! recomposed LaTeX writes the safe label instead, and the table
13//! [`SAFE_LABELS`] holds the correspondence in both directions, for a tool
14//! that reads the recomposed LaTeX beside the document. The rendering guide
15//! shows the result under [References and safe
16//! labels](crate::guide::rendering#references-and-safe-labels).
17//!
18//! # The stage and what counts as a mention
19//!
20//! The stage [`STAGE`] (`flm.refs.safe-labels`) runs once for the document,
21//! reads the reference points ([`REFPOINTS`]) and writes [`SAFE_LABELS`]
22//! (`flm.labels.safe`). It walks every node of every frozen tree in the run's
23//! document order ([`StageCx::walk`]) and allocates the next safe label at the
24//! first mention of a label. A label is mentioned in two ways:
25//!
26//! - a node that declares reference points mentions the labels of those
27//!   points (the labels its construct read from its `\label` fields);
28//! - a node that declares reference sites ([`Referencing`], the sites the
29//!   resolve stage resolves) mentions the target of each site, whether or not
30//!   anything carries the target: `\ref`, `\hyperref`, the `math` feature's
31//!   `\eqref` and the `defterm` feature's term link alike.
32//!
33//! Every reference is therefore written with a safe label, even one that
34//! points at nothing, and no rule writes a target's own characters (which may
35//! hold markup, as a term's do) into a LaTeX label key. A target of `\ref` or
36//! `\hyperref` that is not spelled `type:label` declares no site; it is
37//! mentioned too, keyed by its text (below). A later mention of the same
38//! label finds its safe label already allocated, so a forward reference takes
39//! the lower number: `\ref{sec:b}` written before `\section{B}\label{sec:b}`
40//! makes `sec:b` `ref1`.
41//!
42//! The stage never looks at `\label` nodes. A label that no construct turned
43//! into a reference point is data that the construct absorbed and did not use
44//! (for example a user definition's own `\label` field, whose meaning is up to
45//! that definition), and it gets no safe label, because nothing in the
46//! recomposed LaTeX writes it.
47//!
48//! The stage allocates nothing for a label whose type the render option
49//! [`safe_label_types`](super::RefsRecomposeOptions::safe_label_types)
50//! marks as [`Raw`](super::SafeLabelMode::Raw). It checks nothing else: a
51//! label whose type its construct refuses (for example `\label{eq:x}` on a
52//! heading) is allocated a safe label and recomposed like any other, and the
53//! label check ([`CHECK_LABELS`](super::CHECK_LABELS)) reports it. The label
54//! check is a member of the [`flm.validated`](crate::stdlib::VALIDATED)
55//! collection of capabilities, which every standard workflow
56//! demands (asks the plan to provide; see
57//! [`PlanRequest`](crate::core::plan::PlanRequest)), so a recomposing render
58//! of one of those workflows reports it.
59//!
60//! **A label not spelled `type:label`** (`\label{intro}`, with no colon) is
61//! allocated a safe label too, keyed by its text and of no type. Such a text
62//! defines no label, so the reference point carries it among its
63//! [malformed](crate::model::aspects::RefPoint::malformed) texts; it is
64//! written like any other label, so that the recomposed LaTeX compiles and a
65//! reference to it resolves in LaTeX. The label scan reports the malformed
66//! text ([`BadLabel`](super::BadLabel)). Since it has no type,
67//! `safe_label_types` cannot select it.
68//!
69//! # The table
70//!
71//! The table is keyed by a *domain* and, inside it, by the label's key
72//! ([`label_key`]): its `type:label` spelling, or its text where it has no
73//! type. The only domain today is [`REF_DOMAIN`] (`ref`), the domain of
74//! `\label` and `\ref`. The count is shared across domains, so a feature that
75//! allocates keys of another sort (citation keys, for example) can join
76//! the same count under a domain of its own without collisions.
77//!
78//! The recomposition rules of this feature ([`super::latex`]) and every rule
79//! that writes a construct's labels with [`stage_label`](super::stage_label)
80//! (those of the headings, math, theorems, lists, defterm, floats and xnotes
81//! features) read the table. Nothing else reads a document's labels in a plan
82//! that recomposes it, since nothing is resolved there.
83//!
84//! # The references of a synthesized value
85//!
86//! Content spliced at lowering may write references of its own: a use site of
87//! a user definition expanded where the recomposed LaTeX is written, or a
88//! template lowered for the style file. Such content is a [synthesized
89//! value](crate::guide::concepts_overview#synthesized-values) (a small tree a
90//! stage builds during a run), not part of the document, so the stage above
91//! never saw it. [Value
92//! catch-up](crate::guide::concepts_overview#value-catch-up) brings it up to
93//! date by running the per-tree stages the lowering depends on over the value
94//! alone, and the per-tree stage [`VALUE_STAGE`]
95//! (`flm.refs.value-safe-labels`) is one of them. Over a synthesized value,
96//! it gives every target that the value's reference nodes mention (the same
97//! mentions as above: each site's target, and each target of `\ref` or
98//! `\hyperref` not spelled `type:label`, keyed by its text) and that has no
99//! safe label in the document's table a *value name*: `ref-v1`, `ref-v2`, …
100//! in the order the value first mentions the targets ([`value_name`]). It
101//! writes the value names, per reference node, into [`VALUE_SAFE_LABELS`]
102//! (`flm.labels.safe.value`), held in the
103//! catch-up store of that value; over a document tree it writes nothing. The
104//! rules read a target's safe label from the document's table first and from
105//! the value's table second ([`target_spelling`](super::target_spelling)), so
106//! no reference in a synthesized value is written with its own characters
107//! either.
108//!
109//! The value names are numbered per synthesized value, starting from one in
110//! each: one stage computes them over one value, regardless of the thread the
111//! value is lowered on, so they never depend on the order in which work is
112//! scheduled. They cannot equal a document's safe labels, which hold no
113//! hyphen because their domain, `ref`, holds none ([`value_name`]). No label
114//! is ever written under a value name: a synthesized value declares no label
115//! (a label is a fact about the document, which a value may not state), so a
116//! value name designates a target that nothing in the document carries (one
117//! the resolve stage reports as unresolved, or a text that is not a label),
118//! and LaTeX reports the reference as undefined, as it does for a document's
119//! reference to a label that nothing carries. The same value name in two
120//! synthesized values may designate two different targets; both are
121//! undefined. A target that the resolve stage finds in the external index but
122//! that the document never mentions also gets a value name, and is undefined
123//! in LaTeX, as a document's reference to it is.
124//!
125//! The value stage reads the resolutions of the synthesized value, so that
126//! the resolve stage ([`RESOLVE`](super::RESOLVE)) runs over the value in the
127//! same catch-up and reports its references.
128
129// One count serves every domain, so keys of different domains never meet and
130// need no type prefix; a key such as `ref1` holds only letters and digits,
131// which every package that reads label keys accepts.
132
133use std::collections::BTreeMap;
134
135use techy::error::Diagnostic;
136use techy::serialize::SerialValue;
137
138use crate::core::data::store::StageOut;
139use crate::core::data::table::{PieceClass, ProjectCx, Table, TableName};
140use crate::core::plan::PlanCx;
141use crate::core::run::StageCx;
142use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
143use crate::model::addr::NodeAddr;
144use crate::model::aspects::{Label, Referencing};
145use crate::model::element::element_of;
146use crate::lang::{nowhere, FlmOrigin};
147
148use super::elements::reference_targets;
149use super::latex::{RefsRecomposeOptions, SafeLabelMode};
150use super::stages::StageFailed;
151use super::tables::REF_RESOLUTIONS;
152use crate::stdlib::features::index::ELEMENT_INDEX;
153use crate::stdlib::features::refpoints::{REFPOINTS, RefPointRecord, node_key};
154
155/// The name of the safe-labels stage, `flm.refs.safe-labels`: it walks the
156/// document, reading the reference points and the render options
157/// [`RefsRecomposeOptions`], and writes
158/// [`SAFE_LABELS`]. See the module documentation.
159pub const STAGE: &str = "flm.refs.safe-labels";
160
161/// The typed name of the safe-labels table, `flm.labels.safe`, a
162/// [`SafeLabels`], which the stage [`STAGE`] writes.
163pub const SAFE_LABELS: TableName<SafeLabels> = TableName::new("flm.labels.safe");
164
165/// The domain of the labels that `\label` writes and `\ref` points at, `ref`:
166/// the first key of [`SafeLabels`], and the beginning of the safe labels
167/// allocated in it (`ref1`, `ref2`, …).
168pub const REF_DOMAIN: &str = "ref";
169
170/// The key under which a label is allocated a safe label: its `type:label`
171/// spelling as [`Label::parse`] reads it, each part with its whitespace runs
172/// made one space and its ends trimmed (the form in which [`Label`] is
173/// displayed), when `label` is a parsed label, and `text` as written when it
174/// is not (`intro`, with no colon). Two spellings of one label, `sec:intro`
175/// and `sec : intro`, therefore share one safe label.
176///
177/// The stages and the rules all build the key through this function, so that
178/// they agree.
179///
180/// # Examples
181///
182/// ```
183/// use flm_core::model::aspects::Label;
184/// use flm_core::stdlib::features::refs::label_key;
185///
186/// let label = Label::parse("sec : intro");
187/// assert_eq!(label_key("sec : intro", label.as_ref()), "sec:intro");
188/// assert_eq!(label_key("intro", None), "intro");
189/// ```
190pub fn label_key(text: &str, label: Option<&Label>) -> String {
191    match label {
192        Some(label) => label.to_string(),
193        None => String::from(text),
194    }
195}
196
197/// The safe-labels table, `flm.labels.safe` ([`SAFE_LABELS`]): per domain,
198/// from a label's key ([`label_key`]) to the safe label allocated for it, and
199/// back.
200///
201/// A safe label is the key the recomposed LaTeX writes for an FLM label
202/// (`ref1`, `ref2`, … in the order the document first mentions the labels),
203/// so that any label text an author wrote is carried through LaTeX's
204/// auxiliary file. The recomposed LaTeX writes it in each `\label` (inside
205/// the [LaTeX hook](crate::stdlib::backends::latex::preamble) `\flmLabels`
206/// when the backend's render option
207/// [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
208/// is on)
209/// and in each reference.
210/// A *value name* (`ref-v1`, `ref-v2`, …; [`value_name`]) is the key written
211/// for a target that a reference inside a synthesized value mentions and that
212/// has no safe label in the document; it is numbered apart from the
213/// document's safe labels so that the two sequences never collide. See the
214/// module documentation.
215///
216/// Read the safe label of a key with [`safe_name`](SafeLabels::safe_name),
217/// and the key of a safe label with [`label_of`](SafeLabels::label_of). A key
218/// the table does not hold is one the stage allocated nothing for (a label of
219/// a type written raw), which a rule writes as written.
220#[derive(Debug, Clone, Default)]
221pub struct SafeLabels {
222    /// Domain → the label's key → the safe label allocated for it.
223    pub by_label: BTreeMap<String, BTreeMap<String, String>>,
224    /// Domain → the safe label → the label's key, the reverse of
225    /// `by_label`.
226    pub by_name: BTreeMap<String, BTreeMap<String, String>>,
227    /// How many safe labels have been allocated across every domain: the
228    /// next one's number is one more.
229    pub allocated: u32,
230}
231
232impl SafeLabels {
233    /// The safe label allocated for the key `key` in `domain`, or `None` when
234    /// the stage allocated none for it. Build `key` with [`label_key`].
235    pub fn safe_name(&self, domain: &str, key: &str) -> Option<&str> {
236        self.by_label.get(domain)?.get(key).map(String::as_str)
237    }
238
239    /// The label key for which the safe label `name` was allocated in
240    /// `domain`, or `None` for a safe label the table does not hold.
241    pub fn label_of(&self, domain: &str, name: &str) -> Option<&str> {
242        self.by_name.get(domain)?.get(name).map(String::as_str)
243    }
244
245    /// The safe label of the key `key` in `domain`, allocating the next one
246    /// when the key has none yet: the domain followed by the number of safe
247    /// labels allocated so far across every domain, plus one.
248    pub fn allocate(&mut self, domain: &str, key: &str) -> &str {
249        let names = self.by_label.entry(String::from(domain)).or_default();
250        if !names.contains_key(key) {
251            self.allocated += 1;
252            let name = format!("{domain}{}", self.allocated);
253            self.by_name
254                .entry(String::from(domain))
255                .or_default()
256                .insert(name.clone(), String::from(key));
257            names.insert(String::from(key), name);
258        }
259        names.get(key).map(String::as_str).unwrap_or_default()
260    }
261}
262
263impl Table for SafeLabels {
264    /// The entries of a table piece are added to this table's; a key that
265    /// already has a safe label keeps it. The stage writes the whole table at
266    /// once, so two table pieces never hold the labels of one document.
267    fn absorb(&mut self, piece: SafeLabels) {
268        for (domain, names) in piece.by_label {
269            let mine = self.by_label.entry(domain).or_default();
270            for (key, name) in names {
271                mine.entry(key).or_insert(name);
272            }
273        }
274        for (domain, labels) in piece.by_name {
275            let mine = self.by_name.entry(domain).or_default();
276            for (name, label) in labels {
277                mine.entry(name).or_insert(label);
278            }
279        }
280        self.allocated = self.allocated.max(piece.allocated);
281    }
282
283    /// Projects the table as `{<domain>: {labels: {<key>: <safe label>},
284    /// names: {<safe label>: <key>}}}`.
285    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
286        SerialValue::Map(
287            self.by_label
288                .iter()
289                .map(|(domain, names)| {
290                    let labels = names
291                        .iter()
292                        .map(|(key, name)| (key.clone(), SerialValue::Str(name.clone())))
293                        .collect();
294                    let reverse = self
295                        .by_name
296                        .get(domain)
297                        .into_iter()
298                        .flatten()
299                        .map(|(name, key)| (name.clone(), SerialValue::Str(key.clone())))
300                        .collect();
301                    (
302                        domain.clone(),
303                        SerialValue::Map(vec![
304                            (String::from("labels"), SerialValue::Map(labels)),
305                            (String::from("names"), SerialValue::Map(reverse)),
306                        ]),
307                    )
308                })
309                .collect(),
310        )
311    }
312
313    fn piece_class(&self) -> PieceClass {
314        if self.by_label.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
315    }
316}
317
318/// The safe-labels stage [`STAGE`] (`flm.refs.safe-labels`). See the module
319/// documentation.
320#[derive(Debug, Default, Clone, Copy)]
321pub struct SafeLabelsStage;
322
323impl Stage for SafeLabelsStage {
324    fn decl(&self) -> StageDecl {
325        StageDecl::new(STAGE, Effect::Compute, Scope::Document).writes(SAFE_LABELS).docs(
326            "For the recomposed LaTeX: allocates the safe label (`ref1`, `ref2`, …) of every \
327             label a reference point carries and of every reference target, resolved or not, \
328             in the order the document first mentions it, into `flm.labels.safe`.",
329        )
330    }
331
332    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
333        Needs::new().reads(REFPOINTS).option::<RefsRecomposeOptions>()
334    }
335
336    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
337        let options = match cx.option::<RefsRecomposeOptions>() {
338            Ok(options) => options,
339            Err(error) => {
340                out.diags.push(Diagnostic::error(
341                    StageFailed { stage: String::from(STAGE), detail: error.to_string() },
342                    nowhere(FlmOrigin::none()),
343                ));
344                return;
345            }
346        };
347        let points = match cx.get(REFPOINTS) {
348            Ok(Some(points)) => points,
349            // The read is declared and the table is written by a scheduled
350            // stage, so this cannot happen; saying so is better than writing
351            // an empty table for a document full of labels.
352            Ok(None) => {
353                out.diags.push(Diagnostic::error(
354                    StageFailed {
355                        stage: String::from(STAGE),
356                        detail: format!("missing table ‘{}’", REFPOINTS.name()),
357                    },
358                    nowhere(FlmOrigin::none()),
359                ));
360                return;
361            }
362            Err(error) => {
363                out.diags.push(Diagnostic::error(
364                    StageFailed { stage: String::from(STAGE), detail: error.to_string() },
365                    nowhere(FlmOrigin::none()),
366                ));
367                return;
368            }
369        };
370        // The points of one node, in the order the node declares them: the
371        // table holds one node's points in that order, so appending keeps it.
372        let mut by_node: BTreeMap<NodeAddr, Vec<&RefPointRecord>> = BTreeMap::new();
373        for record in points.records() {
374            by_node.entry(record.id.addr).or_default().push(record);
375        }
376        let mut table = SafeLabels::default();
377        // A label with no type is allocated a name like any other, keyed by
378        // its text; `safe_label_types` names types, so it cannot name it.
379        let raw = |label: Option<&Label>| {
380            label.is_some_and(|label| {
381                options.safe_label_types.get(&label.ref_type) == Some(&SafeLabelMode::Raw)
382            })
383        };
384        for (addr, node) in cx.walk() {
385            // What this node mentions: everything written as a label for every
386            // point it declares, in the order the document wrote it — a text
387            // that is no label among them, keyed by its text and written like
388            // any other, so that the recomposed LaTeX still pairs it with the
389            // references that name it.
390            let mentions = by_node
391                .get(&addr)
392                .into_iter()
393                .flatten()
394                .flat_map(|record| record.mentions());
395            for (text, label) in mentions {
396                if !raw(label) {
397                    table.allocate(REF_DOMAIN, &label_key(&text, label));
398                }
399            }
400            // A reference mentions the target of every site it declares — the
401            // sites the resolver resolves, read through the same aspect, so
402            // that every referencing element of every feature (`\ref`,
403            // `\hyperref`, `\eqref`, a term link) gets a key for its target
404            // alike, resolved or not, and no rule has to write a target the
405            // table does not hold. A `\ref` may name several targets at once,
406            // each of which is written by a key of its own.
407            let sites = element_of(&node)
408                .aspect::<dyn Referencing>()
409                .map(|referencing| referencing.sites(&node))
410                .unwrap_or_default();
411            for site in sites {
412                if !raw(Some(&site.target)) {
413                    table.allocate(REF_DOMAIN, &label_key("", Some(&site.target)));
414                }
415            }
416            // A target of `\ref` or `\hyperref` that is not spelled
417            // `type:label` declares no site, and is named like a label with no
418            // type, keyed by its text, so that it is written as a key and never
419            // as the characters the document wrote.
420            let unspelled = reference_targets(&node).into_iter().flatten();
421            for target in unspelled.filter(|target| target.label.is_none()) {
422                table.allocate(REF_DOMAIN, &label_key(&target.text, None));
423            }
424        }
425        match out.table(SAFE_LABELS) {
426            Ok(written) => *written = table,
427            Err(error) => out.diags.push(Diagnostic::error(
428                StageFailed { stage: String::from(STAGE), detail: error.to_string() },
429                nowhere(FlmOrigin::none()),
430            )),
431        }
432    }
433}
434
435// --- the references a value writes ------------------------------------------------------
436
437/// The name of the value stage, `flm.refs.value-safe-labels`: over a
438/// synthesized value spliced at lowering, it reads [`SAFE_LABELS`], the
439/// value's element index and resolutions and the render options, and writes
440/// [`VALUE_SAFE_LABELS`]. See the module documentation, *The references of a
441/// synthesized value*.
442pub const VALUE_STAGE: &str = "flm.refs.value-safe-labels";
443
444/// The typed name of the value names table, `flm.labels.safe.value`, a
445/// [`ValueSafeLabels`], which the stage [`VALUE_STAGE`] writes.
446pub const VALUE_SAFE_LABELS: TableName<ValueSafeLabels> = TableName::new("flm.labels.safe.value");
447
448/// The value name numbered `number` in `domain`: the domain, a hyphen, `v`
449/// and the number, as in `ref-v1`. A document's safe labels
450/// ([`SafeLabels::allocate`]) are the domain followed by the number alone, so
451/// for a domain without a hyphen (such as [`REF_DOMAIN`], the only domain the
452/// library allocates in) a document's safe label holds no hyphen, and the two
453/// never coincide. See the module documentation, *The references of a
454/// synthesized value*.
455///
456/// # Examples
457///
458/// ```
459/// use flm_core::stdlib::features::refs::{REF_DOMAIN, value_name};
460///
461/// assert_eq!(value_name(REF_DOMAIN, 1), "ref-v1");
462/// ```
463pub fn value_name(domain: &str, number: u32) -> String {
464    format!("{domain}-v{number}")
465}
466
467/// The value names table, `flm.labels.safe.value` ([`VALUE_SAFE_LABELS`]):
468/// for each reference node of a synthesized value, from the key of a target
469/// it mentions ([`label_key`]) to the value name that target is written
470/// under, for the targets that have no safe label in the document's table
471/// ([`SafeLabels`]). Empty for every document tree; see the module
472/// documentation, *The references of a synthesized value*.
473///
474/// It is held in the catch-up store of one synthesized value and read only
475/// at the addresses of that value's nodes, so its node addresses never reach
476/// the run's own store.
477#[derive(Debug, Clone, Default)]
478pub struct ValueSafeLabels {
479    /// Reference node → the target's key → the value name written for it, in
480    /// the domain [`REF_DOMAIN`].
481    pub by_node: BTreeMap<NodeAddr, BTreeMap<String, String>>,
482}
483
484impl ValueSafeLabels {
485    /// The value name written for the target of key `key` that the node at
486    /// `at` mentions, or `None` where the table holds none. Build `key` with
487    /// [`label_key`].
488    pub fn safe_name(&self, at: NodeAddr, key: &str) -> Option<&str> {
489        self.by_node.get(&at)?.get(key).map(String::as_str)
490    }
491}
492
493impl Table for ValueSafeLabels {
494    fn absorb(&mut self, piece: ValueSafeLabels) {
495        for (addr, names) in piece.by_node {
496            self.by_node.entry(addr).or_default().extend(names);
497        }
498    }
499
500    /// Projects the table as `{<node>: {<key>: <value name>}}`.
501    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
502        SerialValue::Map(
503            self.by_node
504                .iter()
505                .map(|(addr, names)| {
506                    let names = names
507                        .iter()
508                        .map(|(key, name)| (key.clone(), SerialValue::Str(name.clone())))
509                        .collect();
510                    (node_key(cx, *addr), SerialValue::Map(names))
511                })
512                .collect(),
513        )
514    }
515
516    /// Keyed by node address: the names under which one synthesized value's
517    /// references are written are not a fact about the document.
518    fn piece_class(&self) -> PieceClass {
519        if self.by_node.is_empty() { PieceClass::Empty } else { PieceClass::NodeKeyed }
520    }
521}
522
523/// The value stage [`VALUE_STAGE`] (`flm.refs.value-safe-labels`). See the
524/// module documentation, *The references of a synthesized value*.
525#[derive(Debug, Default, Clone, Copy)]
526pub struct ValueSafeLabelsStage;
527
528impl Stage for ValueSafeLabelsStage {
529    fn decl(&self) -> StageDecl {
530        StageDecl::new(VALUE_STAGE, Effect::Compute, Scope::PerTree)
531            .writes(VALUE_SAFE_LABELS)
532            .docs(
533                "For the recomposed LaTeX, over a synthesized value spliced at lowering: gives \
534                 every target its references mention that has no safe label in \
535                 `flm.labels.safe` a value name, `ref-v1`, `ref-v2`, … in the order the value \
536                 first mentions it, into `flm.labels.safe.value`; writes nothing over a \
537                 document tree.",
538            )
539    }
540
541    /// Reads the document's safe labels, the element index of the tree, the
542    /// render options for the label types written raw, and the resolutions:
543    /// the last so that the resolve stage runs over the synthesized value
544    /// before this stage, in the same catch-up, and reports the value's
545    /// references.
546    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
547        Needs::new()
548            .reads(SAFE_LABELS)
549            .reads(ELEMENT_INDEX)
550            .reads(REF_RESOLUTIONS)
551            .option::<RefsRecomposeOptions>()
552    }
553
554    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
555        let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
556        if !id.is_value() {
557            return;
558        }
559        // A failure here is the plan's, and reported over the document by
560        // the document-scope stage reading the same tables.
561        let (Ok(Some(document)), Ok(Some(index)), Ok(options)) =
562            (cx.get(SAFE_LABELS), cx.get(ELEMENT_INDEX), cx.option::<RefsRecomposeOptions>())
563        else {
564            return;
565        };
566        let raw = |label: &Label| {
567            options.safe_label_types.get(&label.ref_type) == Some(&SafeLabelMode::Raw)
568        };
569        let mut named: BTreeMap<String, String> = BTreeMap::new();
570        let mut table = ValueSafeLabels::default();
571        for (addr, node, referencing) in
572            index.nodes_with::<dyn Referencing>(cx.registry(), id, &tree)
573        {
574            // The same mentions as the document's stage reads: each site's
575            // target, then each target not spelled `type:label`, by its text.
576            let sites = referencing.sites(&node).into_iter().map(|site| site.target);
577            let keys = sites
578                .filter(|target| !raw(target))
579                .map(|target| label_key("", Some(&target)))
580                .chain(
581                    reference_targets(&node)
582                        .into_iter()
583                        .flatten()
584                        .filter(|target| target.label.is_none())
585                        .map(|target| label_key(&target.text, None)),
586                );
587            for key in keys {
588                if document.safe_name(REF_DOMAIN, &key).is_some() {
589                    continue;
590                }
591                let next = named.len() + 1;
592                let name = named
593                    .entry(key.clone())
594                    .or_insert_with(|| value_name(REF_DOMAIN, u32::try_from(next).unwrap_or(u32::MAX)))
595                    .clone();
596                table.by_node.entry(addr).or_default().insert(key, name);
597            }
598        }
599        if let Ok(written) = out.table(VALUE_SAFE_LABELS) {
600            *written = table;
601        }
602    }
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608
609    #[test]
610    fn names_are_allocated_once_per_label_across_domains() {
611        let mut table = SafeLabels::default();
612        let a = Label::new("sec", "a").to_string();
613        let b = Label::new("eq", "b").to_string();
614        assert_eq!(table.allocate(REF_DOMAIN, &a), "ref1");
615        assert_eq!(table.allocate("cite", &b), "cite2");
616        assert_eq!(table.allocate(REF_DOMAIN, &a), "ref1");
617        assert_eq!(table.allocate(REF_DOMAIN, &b), "ref3");
618        assert_eq!(table.safe_name(REF_DOMAIN, &b), Some("ref3"));
619        assert_eq!(table.safe_name("cite", &a), None);
620        assert_eq!(table.label_of("cite", "cite2"), Some("eq:b"));
621        assert_eq!(table.allocated, 3);
622        assert_eq!(table.piece_class(), PieceClass::DocumentFact);
623        assert_eq!(SafeLabels::default().piece_class(), PieceClass::Empty);
624    }
625
626    #[test]
627    fn a_label_with_no_type_is_keyed_by_its_text_and_named_like_any_other() {
628        assert_eq!(label_key("sec : intro", Label::parse("sec : intro").as_ref()), "sec:intro");
629        assert_eq!(label_key("intro", None), "intro");
630        let mut table = SafeLabels::default();
631        assert_eq!(table.allocate(REF_DOMAIN, &label_key("sec:a", Label::parse("sec:a").as_ref())), "ref1");
632        assert_eq!(table.allocate(REF_DOMAIN, &label_key("a_b", None)), "ref2");
633        assert_eq!(table.safe_name(REF_DOMAIN, "a_b"), Some("ref2"));
634        assert_eq!(table.label_of(REF_DOMAIN, "ref2"), Some("a_b"));
635    }
636
637    #[test]
638    fn a_value_name_holds_a_hyphen_no_document_name_holds() {
639        assert_eq!(value_name(REF_DOMAIN, 3), "ref-v3");
640        let mut table = SafeLabels::default();
641        assert!(!table.allocate(REF_DOMAIN, "sec:a").contains('-'));
642        assert_eq!(ValueSafeLabels::default().piece_class(), PieceClass::Empty);
643    }
644
645    #[test]
646    fn the_value_stage_is_per_tree_and_writes_its_table() {
647        let decl = ValueSafeLabelsStage.decl();
648        assert_eq!(decl.name, VALUE_STAGE);
649        assert_eq!(decl.scope, Scope::PerTree);
650        assert_eq!(decl.writes.len(), 1);
651    }
652
653    #[test]
654    fn the_stage_is_of_document_scope_and_writes_the_table() {
655        let decl = SafeLabelsStage.decl();
656        assert_eq!(decl.name, STAGE);
657        assert_eq!(decl.scope, Scope::Document);
658        assert_eq!(decl.effect, Effect::Compute);
659        assert_eq!(decl.writes.len(), 1);
660    }
661}