Skip to main content

flm_core/stdlib/features/refs/
rules.rs

1//! The two lowering rules that the [`refs`](super) feature registers as the
2//! default on every backend: [`REF_RULE`] lowers a `\ref` to links around
3//! what its targets show, and [`HYPERREF_RULE`] lowers a `\hyperref` to a
4//! link around the author's own text. A lowering rule
5//! ([`LoweringRule`]) is written for one element and stages (builds into the
6//! lowered tree; see [`Lowerer`]) the element's presentation for a backend.
7//! On the `latex-recomposed` backend, the rules of [`super::latex`] are the
8//! default instead.
9//!
10//! The module also holds [`lower_reference`], through which a command of
11//! another feature shows a reference exactly as a `\ref` does, and
12//! [`designation`], which gives what a reference to a label shows, decided by
13//! the same code, for a host that names the label's target (an outline of the
14//! document, for instance).
15//!
16//! # What a `\ref` shows
17//!
18//! A `\ref` may point at several targets, so the rule reads every target the
19//! node wrote ([`ref_targets`](super::ref_targets)) and lowers them through
20//! [`lower_reference`].
21//!
22//! For each target, the rule shows the first of three things that exists:
23//!
24//! - the **number** the document gave the target, where the numbering stage
25//!   recorded one for it, written from the counter table `flm.counters`; the
26//!   rule reads that table optionally, through a peer declaration
27//!   ([`PeerName`](crate::core::registry::PeerName)), so that the same rule
28//!   works in a registry without the numbering feature;
29//! - else the target's **content**: the synthesized value that the anchors
30//!   stage copied out of the document (a heading's title, for instance), or
31//!   the one that the target's element built (such as the bullet beside a
32//!   list's item);
33//! - else the **label** the reference was written with, as written: the
34//!   target has nothing to show, which is reported as the Error
35//!   `flm.refs.nothing-to-show` ([`NothingToShow`](super::NothingToShow)).
36//!
37//! Each of the three is placed inside a
38//! [`flm.pres.link`](crate::stdlib::backends::pres::LINK) to the target,
39//! whose kind is [`LINK_KIND`]. A target that nothing resolves, and a target
40//! that is not spelled `type:label` at all, gets no link: its own text is
41//! placed inside a [`flm.pres.span`](crate::stdlib::backends::pres::SPAN)
42//! styled as an unresolved reference. The resolve stage ([`RESOLVE`](super::RESOLVE)) or the
43//! label scan ([`SCAN`](super::SCAN)) has already reported it.
44//!
45//! # Several targets
46//!
47//! A reference is written as one list of items, joined by the texts of the
48//! feature's configuration ([`RefsConfig`](super::RefsConfig)): by default,
49//! two items read `Eq. (1) and Thm. 1.1`, and three or more read `Eq. (1),
50//! Thm. 1.1, and A note`.
51//!
52//! The first items are the numbers of the targets the document numbered, one
53//! item per [counter style](crate::stdlib::features::numbering::CounterStyleDecl)
54//! (how the numbering feature shows a counter's value; see [counters and
55//! counter styles](crate::guide::concepts_overview#counters-and-counter-styles)),
56//! in the order the styles are first reached:
57//! [`Counters::format_many`] groups the targets by the counter style they are
58//! shown in and passes each style's numbers to that style's number writer,
59//! which writes them as one text with the style's own joining texts
60//! (`Eqs. (1–3), (7) and (9)`). The default number writer also groups a
61//! style's numbers by the counters they are numbered within, and collapses
62//! consecutive numbers of a group into a range. Each number links to its own
63//! target, and the word before the numbers links to the first target where
64//! the counter style asks for it. With exactly one target,
65//! [`Counters::format`] writes the number, and the whole text is one link.
66//!
67//! Then come the other targets (one the document did not number, one that
68//! nothing resolves, one that is not a label), one item each, in the order
69//! the document wrote them, each shown as a single target is shown. The
70//! texts that join the items link to nothing.
71//!
72//! # The display options
73//!
74//! The options a `\ref` carries ([`RefDisplayOptions`]) choose the wording of
75//! the word a counter style places before a number: `noprefix` leaves the
76//! word out, the key `S` asks for the capitalized wording (the variant
77//! [`CAPITAL_VARIANT`](super::CAPITAL_VARIANT)), and any other key asks for
78//! the variant of its own name. The options apply to every target of the
79//! reference alike.
80//!
81//! `S` is a preference: a counter style that declares the variant `capital`
82//! writes it, and a style that does not writes its usual wording, with
83//! nothing reported. A variant written as the key itself (`capital` or
84//! `abbreviated`) is a requirement: where the counter style of a numbered
85//! target does not declare it, the reference is reported as the Error
86//! `flm.refs.undeclared-variant` ([`UndeclaredVariant`](super::UndeclaredVariant)),
87//! once per style that lacks it, and that style writes its usual wording. A
88//! target shown by its content or its label has no counter style, and nothing
89//! is checked for it.
90//!
91//! # `\hyperref`
92//!
93//! The `\hyperref` rule stages a link or an unresolved span in the same way,
94//! with one difference: their content is the text the author wrote in the
95//! braces, lowered as ordinary inline content. What the target has to show
96//! takes no part, so the rule reads no synthesized value, no number and
97//! nothing of the counter table. A `\hyperref` whose target is not spelled
98//! `type:label` (an absent or unreadable target included) still shows the
99//! author's text, without a link and styled as unresolved.
100//!
101//! # A reference site missing from the resolutions table
102//!
103//! A reference site that the table `flm.refs.resolutions` does not hold at
104//! all differs from a target that nothing resolves: it means that the rule is
105//! lowering content that the resolve stage ([`RESOLVE`](super::RESOLVE)) never saw, such as
106//! a synthesized value that the code lowering it did not bring up to date
107//! through value catch-up. The rule reports it at
108//! the node as `flm.run.missing-entry` ([`MissingEntry`]) and then fails.
109
110use std::collections::BTreeMap;
111use std::sync::Arc;
112
113use techy::core::node::{BuildId, NodeRef, NodeTree};
114use techy::error::Diagnostic;
115
116use crate::core::lowering::{
117    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
118};
119use crate::model::aspects::{Label, PointId, RefDisplayOptions};
120use crate::model::element::element_of;
121use crate::model::names::{CapName, ElementName};
122use crate::core::run::MissingEntry;
123use crate::lang::Flm;
124use crate::lang::text::text_of;
125use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
126use crate::stdlib::backends::pres::{self, LinkPayload, SpanPayload, SpanStyle};
127use crate::stdlib::features::numbering::{
128    COUNTERS, Counters, FormatError, FormatOptions, NumberSegment,
129};
130
131use super::elements::{
132    CAPITAL_KEY, CAPITAL_VARIANT, HYPERREF, REF, RefTargetText, TEXT_ARG, hyperref_target,
133    ref_display_options, ref_targets,
134};
135use super::list::{ListTexts, join_items};
136use super::stages::{NothingToShow, UndeclaredVariant};
137use super::tables::{REF_RESOLUTIONS, RefTarget, Resolution, SiteId};
138
139/// The name of the `\ref` lowering rule, `flm.ref.lower.default`, whose
140/// implementation is [`RefRule`]: the default for `flm.ref` on every backend
141/// except `latex-recomposed`.
142pub const REF_RULE: &str = "flm.ref.lower.default";
143
144/// The name of the `\hyperref` lowering rule, `flm.hyperref.lower.default`,
145/// whose implementation is [`HyperrefRule`]: the default for `flm.hyperref`
146/// on every backend except `latex-recomposed`.
147pub const HYPERREF_RULE: &str = "flm.hyperref.lower.default";
148
149/// The kind token written on the link that a `\ref` or a `\hyperref`
150/// produces, `ref`: it tells a backend, or a stylesheet, that the link comes
151/// from a reference (see the [payload
152/// conventions](crate::stdlib::backends::pres::payload)). The HTML backend
153/// writes it as `data-flm-kind="ref"`.
154pub const LINK_KIND: &str = "ref";
155
156/// Stages `body` inside a
157/// [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) styled as an
158/// unresolved reference: what both rules produce where nothing resolved the
159/// target.
160///
161/// # Errors
162///
163/// Returns [`LowerError`] when the node could not be built, or when the
164/// calling rule did not declare that it produces `flm.pres.span`.
165fn unresolved_node(
166    cx: &mut LowerCx<'_>,
167    lw: &mut dyn Lowerer,
168    body: Vec<BuildId>,
169) -> Result<BuildId, LowerError> {
170    let payload =
171        SpanPayload { style: Some(SpanStyle::UnresolvedReference), ..SpanPayload::default() };
172    lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)
173}
174
175/// Stages `body` inside a
176/// [`flm.pres.link`](crate::stdlib::backends::pres::LINK) to `href` of the
177/// kind [`LINK_KIND`]: what both rules produce for a resolved target.
178///
179/// # Errors
180///
181/// Returns [`LowerError`] when the node could not be built, or when the
182/// calling rule did not declare that it produces `flm.pres.link`.
183fn link_node(
184    cx: &mut LowerCx<'_>,
185    lw: &mut dyn Lowerer,
186    href: String,
187    body: Vec<BuildId>,
188) -> Result<BuildId, LowerError> {
189    let payload = LinkPayload {
190        href,
191        kind: LINK_KIND.into(),
192        doc_role: None,
193        label: None,
194        shows_target: false,
195    };
196    lw.pres_with(cx, &ElementName::from(pres::LINK), payload, body)
197}
198
199/// How the reference site `index` of `node` resolved, read from
200/// `flm.refs.resolutions` at the node's own address.
201///
202/// `None` is not a site that nothing resolved (that is
203/// [`Resolution::Unresolved`]) but a site the table does not hold at all,
204/// which means that the rule is lowering content the resolve stage
205/// ([`RESOLVE`](super::RESOLVE)) never saw: a synthesized value that the code lowering it
206/// did not bring up to date through value catch-up. It is
207/// reported at the node as `flm.run.missing-entry`, giving `element`, and the
208/// caller fails.
209fn resolution_of(
210    node: &NodeRef<'_, Flm>,
211    lw: &mut dyn Lowerer,
212    element: &str,
213    index: u32,
214) -> Result<Option<Resolution>, LowerError> {
215    let site = SiteId { addr: lw.addr(), index };
216    // The resolution is cloned out of the table (a value tree is one shared
217    // pointer): splicing needs the `Lowerer` mutably.
218    let resolution = lw.get(REF_RESOLUTIONS)?.and_then(|table| table.site(site)).cloned();
219    if resolution.is_none() {
220        let table = CapName::from(REF_RESOLUTIONS.name());
221        let producer = lw
222            .producer_of(&table)
223            .map(|stage| stage.to_string())
224            .unwrap_or_else(|| "nobody".to_string());
225        lw.diagnose(Diagnostic::error(
226            MissingEntry { table: table.to_string(), producer, element: element.to_string() },
227            node.span().clone(),
228        ));
229    }
230    Ok(resolution)
231}
232
233/// What one target of a reference has to show, once it has been resolved.
234enum Shown {
235    /// The target was found: the link target, the reference point it
236    /// designates in this document (absent for a target of another document),
237    /// the content it shows where it has no number, and the text the
238    /// reference wrote for it.
239    Resolved {
240        href: String,
241        point: Option<PointId>,
242        content: Option<Arc<NodeTree<Flm>>>,
243        text: String,
244    },
245    /// Nothing resolved the target, or its text is not a label: this text is
246    /// shown, without a link and marked unresolved.
247    Unresolved { text: String },
248}
249
250/// The wording variant that `display` asks for, if any: its name, and whether
251/// the request is a requirement. The key `S` asks for the variant `capital`
252/// as a preference, and a counter style that lacks it writes its usual
253/// wording; any other key asks for the variant of its own name as a
254/// requirement, and a counter style that lacks it is reported at the
255/// reference.
256fn requested_variant(display: &RefDisplayOptions) -> Option<(&str, bool)> {
257    display.variant.as_deref().map(|variant| match variant {
258        CAPITAL_KEY => (CAPITAL_VARIANT, false),
259        other => (other, true),
260    })
261}
262
263/// The formatting options with which a counter style writes a number at a
264/// reference site: the display options translated into the options of the
265/// numbering feature.
266///
267/// `noprefix` leaves out the word before the number, and the variant asked
268/// for is [`requested_variant`]. The delimiters around a number are always
269/// written: no option of a reference asks for a number without them.
270fn format_options(display: &RefDisplayOptions) -> FormatOptions {
271    let mut options = FormatOptions::new();
272    if !display.with_prefix {
273        options = options.without_word();
274    }
275    if let Some((variant, _)) = requested_variant(display) {
276        options = options.variant(variant);
277    }
278    options
279}
280
281/// The names of the counter styles of the points `numbered` that do not
282/// declare the wording variant `variant`: each once, in the order of the
283/// first point that uses it.
284fn styles_lacking(counters: &Counters, numbered: &[PointId], variant: &str) -> Vec<String> {
285    let mut lacking: Vec<String> = Vec::new();
286    for point in numbered {
287        let Some(record) = counters.record(*point) else { continue };
288        if record.style.declares_variant(variant) {
289            continue;
290        }
291        let name = record.style.name().as_str();
292        if !lacking.iter().any(|seen| seen == name) {
293            lacking.push(name.to_string());
294        }
295    }
296    lacking
297}
298
299/// Lowers a reference to `targets`, with the display options `display`, into
300/// the items it shows: a command of another feature calls this function to
301/// show a reference exactly as a `\ref` does, instead of writing that
302/// behavior again.
303///
304/// Returns the list of items, in order, each a sequence of staged nodes
305/// linked to its own target: first one item per counter style for the
306/// targets the document numbered, then one item per other target. The module
307/// documentation says what each item shows. The `\ref` rule joins the items
308/// with the texts of [`RefsConfig`](super::RefsConfig), even a single item,
309/// which receives `one_pre` and `one_post`. A command of another feature
310/// writes the items as it needs. Two do so: the mathematics feature's
311/// `\eqref`, whose one target shows what `\ref[noprefix]` would show, writes
312/// its one item without `one_pre` and `one_post` (both empty by default),
313/// because that feature cannot read this feature's joining texts; and the
314/// theorems feature's back-reference from a proof to its theorem.
315///
316/// `node` is the node being lowered, whose address identifies the reference
317/// sites the resolve stage ([`RESOLVE`](super::RESOLVE)) wrote for it;
318/// `targets` are the targets of that
319/// node, in the order they were written, as [`ref_targets`](super::ref_targets)
320/// reads them; `display` holds the display options. A wording variant written
321/// as a key that the counter style of a numbered target does not declare is
322/// reported at `node` ([`UndeclaredVariant`](super::UndeclaredVariant)); the
323/// key `S` is a preference and is never reported.
324///
325/// The calling rule must declare that it produces
326/// [`flm.pres.link`](crate::stdlib::backends::pres::LINK) and
327/// [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) and that it reads
328/// `flm.refs.resolutions` ([`REF_RESOLUTIONS`]). It should also declare an
329/// optional read of [`COUNTERS`], with a peer declaration of that table
330/// ([`FeatureBuilder::peer_table`](crate::core::registry::FeatureBuilder::peer_table)),
331/// so that a target the document numbered shows its number.
332///
333/// The calling *element* must declare, through
334/// [`Referencing`](crate::model::aspects::Referencing), one reference site
335/// per target of `targets` that has a label, in the order those targets are
336/// written: the resolution of a target is read by its place among the
337/// labeled targets. A target without a label uses no site and is shown
338/// unresolved, as the text it was written with. If the element declares its
339/// sites in any other way, the rule reports `flm.run.missing-entry` at the
340/// node and fails, which looks like a fault of the pipeline although the
341/// mistake is in the calling feature.
342///
343/// # Errors
344///
345/// Returns [`LowerError`] when a node could not be built, when the calling
346/// rule did not declare what this function stages or reads, when a table
347/// could not be read, or when the reference site of a target is missing from
348/// `flm.refs.resolutions` (a fault of an earlier step, reported at the node
349/// before the error is returned).
350pub fn lower_reference(
351    cx: &mut LowerCx<'_>,
352    lw: &mut dyn Lowerer,
353    node: &NodeRef<'_, Flm>,
354    targets: &[RefTargetText],
355    display: &RefDisplayOptions,
356) -> Result<Vec<Vec<BuildId>>, LowerError> {
357    let element = element_of(node).name.to_string();
358    // A target that is no label declares no reference site, so the site of a
359    // target is its place among the labeled targets — the same count the
360    // `Referencing` implementation makes when it declares them.
361    let mut site = 0u32;
362    let mut shown: Vec<Shown> = Vec::with_capacity(targets.len());
363    for target in targets {
364        if target.label.is_none() {
365            shown.push(Shown::Unresolved { text: target.text.clone() });
366            continue;
367        }
368        let index = site;
369        site += 1;
370        match resolution_of(node, lw, &element, index)? {
371            Some(Resolution::Resolved { point, href, display }) => shown.push(Shown::Resolved {
372                href,
373                point,
374                content: display.content,
375                text: target.text.clone(),
376            }),
377            Some(Resolution::Unresolved { target }) => {
378                shown.push(Shown::Unresolved { text: target.to_string() })
379            }
380            None => return Err(LowerError::structure("the reference has no resolution entry")),
381        }
382    }
383
384    // What each resolved target shows, decided by `showing` as `designation`
385    // decides it, and the numbers written for the targets the document
386    // numbered. Both are read in one borrow of the counter table, and what
387    // comes out of it is owned, because staging content needs the `Lowerer`
388    // mutably.
389    // A variant named outright that the style of a numbered target does not
390    // declare is reported here, once per style; the style writes its usual
391    // wording all the same. The key `S` is a preference, and is not checked.
392    let variant = requested_variant(display)
393        .and_then(|(variant, demanded)| demanded.then_some(variant));
394    let counters = lw.get(COUNTERS)?;
395    let showings: Vec<Option<Showing>> = shown
396        .iter()
397        .map(|target| match target {
398            Shown::Resolved { point, content, .. } => Some(showing(counters, *point, content.as_ref())),
399            Shown::Unresolved { .. } => None,
400        })
401        .collect();
402    let numbered: Vec<PointId> = showings
403        .iter()
404        .filter_map(|showing| match showing {
405            Some(Showing::Number(point)) => Some(*point),
406            _ => None,
407        })
408        .collect();
409    let (groups, lacking) = match counters {
410        None => (Vec::new(), Vec::new()),
411        Some(counters) => {
412            let groups = written_numbers(counters, &numbered, targets.len(), &format_options(display))?;
413            let lacking = match variant {
414                Some(variant) => styles_lacking(counters, &numbered, variant),
415                None => Vec::new(),
416            };
417            (groups, lacking)
418        }
419    };
420    if let Some(variant) = variant {
421        for style in lacking {
422            lw.error(UndeclaredVariant { variant: variant.to_string(), style }, node.span().clone());
423        }
424    }
425
426    let hrefs: BTreeMap<PointId, String> = shown
427        .iter()
428        .filter_map(|target| match target {
429            Shown::Resolved { point: Some(point), href, .. } => Some((*point, href.clone())),
430            _ => None,
431        })
432        .collect();
433    let mut items: Vec<Vec<BuildId>> = Vec::with_capacity(groups.len() + shown.len());
434    for group in &groups {
435        let mut item = Vec::new();
436        for segment in group {
437            let body = lw.splice(cx, segment.content())?;
438            match segment.link().and_then(|point| hrefs.get(&point)) {
439                Some(href) => item.push(link_node(cx, lw, href.clone(), body)?),
440                None => item.extend(body),
441            }
442        }
443        items.push(item);
444    }
445    for (target, showing) in shown.iter().zip(showings) {
446        let node = match (target, showing) {
447            (_, Some(Showing::Number(_))) => continue,
448            (Shown::Resolved { href, .. }, Some(Showing::Content(value))) => {
449                let body = lw.splice(cx, &value)?;
450                link_node(cx, lw, href.clone(), body)?
451            }
452            (Shown::Resolved { href, text, .. }, _) => {
453                let span = node.span().clone();
454                lw.error(NothingToShow { label: text.clone() }, span);
455                let body = vec![lw.text(cx, text)?];
456                link_node(cx, lw, href.clone(), body)?
457            }
458            (Shown::Unresolved { text }, _) => {
459                let body = vec![lw.text(cx, text)?];
460                unresolved_node(cx, lw, body)?
461            }
462        };
463        items.push(vec![node]);
464    }
465    Ok(items)
466}
467
468/// What one resolved target of a reference shows: the first of its number,
469/// its content and its label that exists (the module documentation, "What a
470/// `\ref` shows"). [`lower_reference`] and [`designation`] both decide it
471/// through [`showing`], so that what a reference shows and the designation of
472/// a label cannot differ.
473enum Showing {
474    /// The number the document gave the target's reference point.
475    Number(PointId),
476    /// The target's content, where it has no number.
477    Content(Arc<NodeTree<Flm>>),
478    /// Nothing of its own: the label as written.
479    Label,
480}
481
482/// What a target whose reference point is `point` (absent for a target of
483/// another document) and whose content is `content` shows, under the counter
484/// table `counters` (absent where the numbering feature is not registered).
485fn showing(
486    counters: Option<&Counters>,
487    point: Option<PointId>,
488    content: Option<&Arc<NodeTree<Flm>>>,
489) -> Showing {
490    let numbered = point.filter(|point| counters.is_some_and(|counters| counters.record(*point).is_some()));
491    match (numbered, content) {
492        (Some(point), _) => Showing::Number(point),
493        (None, Some(content)) => Showing::Content(Arc::clone(content)),
494        (None, None) => Showing::Label,
495    }
496}
497
498/// The number of the one target of a reference, written by `counters` with
499/// `options`: no segment where the table holds no number for `point`.
500fn one_number(
501    counters: &Counters,
502    point: PointId,
503    options: &FormatOptions,
504) -> Result<Vec<NumberSegment>, FormatError> {
505    counters.format(point, options).unwrap_or(Ok(Vec::new()))
506}
507
508/// The numbers of the points `numbered`, which the document numbered: one
509/// group of segments per counter style.
510///
511/// `count` is the number of targets of the reference: with exactly one,
512/// [`one_number`] writes the number as one group whose whole text is one
513/// link; with more, [`Counters::format_many`] groups the points by counter
514/// style and lets each style's number writer write them.
515///
516/// # Errors
517///
518/// Returns [`LowerError`] when a number could not be written, which means
519/// that the counter record and its counter style do not fit each other: a
520/// fault of an earlier step, since the numbering stage refuses a record its
521/// counter style cannot write.
522fn written_numbers(
523    counters: &Counters,
524    numbered: &[PointId],
525    count: usize,
526    options: &FormatOptions,
527) -> Result<Vec<Vec<NumberSegment>>, LowerError> {
528    if numbered.is_empty() {
529        return Ok(Vec::new());
530    }
531    let written = if count == 1 {
532        one_number(counters, numbered[0], options).map(|one| vec![one])
533    } else {
534        counters.format_many(numbered, options).map(|many| many.groups)
535    };
536    written.map_err(|error| LowerError::structure(error.to_string()))
537}
538
539/// What a reference to a label shows, as [`designation`] gives it: the
540/// number, the content or the label of the module documentation's "What a
541/// `\ref` shows".
542#[derive(Debug, Clone)]
543pub enum Designation {
544    /// The number the document gave the label's reference point, as the
545    /// segments its counter style writes, the word before it included
546    /// (`Thm. 1`).
547    Number(Vec<NumberSegment>),
548    /// The content the label's reference point shows where it has no number
549    /// (a heading's title), as a synthesized value.
550    Content(Arc<NodeTree<Flm>>),
551    /// The label itself, as written: its reference point has nothing to show.
552    Label(String),
553}
554
555impl Designation {
556    /// Returns the text of the designation: of each segment of a number in
557    /// turn, of the content, or the label.
558    ///
559    /// The text of a number's segment or of the content is the characters of
560    /// its text nodes, with each whitespace node (`~`, `\ `) written as one
561    /// space, so `Thm. 1`; any other command contributes nothing, as in the
562    /// plain text of content. Nothing is trimmed or collapsed.
563    pub fn plain_text(&self) -> String {
564        match self {
565            Designation::Number(segments) => {
566                segments.iter().map(|segment| text_with_spaces(segment.content())).collect()
567            }
568            Designation::Content(content) => text_with_spaces(content),
569            Designation::Label(label) => label.clone(),
570        }
571    }
572}
573
574/// Returns the text of a synthesized value as [`Designation::plain_text`]
575/// reads it: each whitespace node written as one space.
576fn text_with_spaces(tree: &NodeTree<Flm>) -> String {
577    text_of(std::iter::once(tree.root()), " ")
578}
579
580/// Returns what a reference to the label `label`, whose target in this
581/// document is `target`, shows: what a `\ref{label}` written with no display
582/// option shows, decided by the code that [`lower_reference`] decides it with.
583/// `counters` is the run's counter table ([`COUNTERS`]), absent where the
584/// numbering feature is not registered or did not run; a target is then shown
585/// by its content or its label.
586///
587/// The designation is what the reference shows inside its link. The texts
588/// that the `\ref` rule writes around a single item (`one_pre` and
589/// `one_post` of [`RefsConfig`](super::RefsConfig), empty by default) are not
590/// part of it, nor is the problem `flm.refs.nothing-to-show` that a reference
591/// to a label with nothing to show reports.
592///
593/// # Errors
594///
595/// Returns [`FormatError`] when the number could not be written: the counter
596/// record and its counter style do not fit each other, a fault of the
597/// program, since the numbering stage refuses such a record.
598pub fn designation(
599    target: &RefTarget,
600    label: &Label,
601    counters: Option<&Counters>,
602) -> Result<Designation, FormatError> {
603    let options = format_options(&RefDisplayOptions::default());
604    match (showing(counters, Some(target.point), target.display.content.as_ref()), counters) {
605        (Showing::Number(point), Some(counters)) => {
606            one_number(counters, point, &options).map(Designation::Number)
607        }
608        (Showing::Content(content), _) => Ok(Designation::Content(content)),
609        (Showing::Number(_) | Showing::Label, _) => Ok(Designation::Label(label.to_string())),
610    }
611}
612
613/// The implementation of [`REF_RULE`]: it stages what each target of the
614/// reference shows (its number, its content or its label), linked to that
615/// target, as one list joined by the texts of
616/// [`RefsConfig`](super::RefsConfig). See the module documentation.
617///
618/// The feature registers it with the joining texts of its configuration,
619/// compiled when the registry is built.
620#[derive(Debug)]
621pub struct RefRule {
622    list: Arc<ListTexts>,
623}
624
625impl Lower for RefRule {
626    fn lower(
627        &self,
628        node: NodeRef<'_, Flm>,
629        cx: &mut LowerCx<'_>,
630        lw: &mut dyn Lowerer,
631    ) -> Result<Lowering, LowerError> {
632        let targets = ref_targets(&node).unwrap_or_default();
633        let display = ref_display_options(&node);
634        let items = lower_reference(cx, lw, &node, &targets, &display)?;
635        Ok(Lowering::Emit(join_items(cx, lw, &self.list, items)?))
636    }
637}
638
639/// The implementation of [`HYPERREF_RULE`]: it stages the text the author
640/// wrote inside a [`flm.pres.link`](crate::stdlib::backends::pres::LINK) to
641/// the target, or inside a
642/// [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) styled as an
643/// unresolved reference where nothing resolved the target. See the module
644/// documentation.
645#[derive(Debug, Default)]
646pub struct HyperrefRule;
647
648impl Lower for HyperrefRule {
649    fn lower(
650        &self,
651        node: NodeRef<'_, Flm>,
652        cx: &mut LowerCx<'_>,
653        lw: &mut dyn Lowerer,
654    ) -> Result<Lowering, LowerError> {
655        // The author's text is what this shows, resolved or not, so it is
656        // lowered once, before anything is looked up. A text a parse recovery
657        // left absent lowers to nothing and is not reported a second time.
658        let body = lower_arg_named_or_nothing(cx, lw, &node, TEXT_ARG)?;
659        let target = hyperref_target(&node)
660            .unwrap_or(RefTargetText { text: String::new(), label: None });
661        if target.label.is_none() {
662            return Ok(Lowering::Emit(vec![unresolved_node(cx, lw, body)?]));
663        }
664        let node = match resolution_of(&node, lw, HYPERREF, 0)? {
665            // The target's own display takes no part here.
666            Some(Resolution::Resolved { href, .. }) => link_node(cx, lw, href, body)?,
667            Some(Resolution::Unresolved { .. }) => unresolved_node(cx, lw, body)?,
668            None => return Err(LowerError::structure("the reference has no resolution entry")),
669        };
670        Ok(Lowering::Emit(vec![node]))
671    }
672}
673
674/// The feature's two lowering rules, ready to be registered: the `\ref` rule,
675/// which joins its items with the texts that `list` holds once compiled, and
676/// the `\hyperref` rule, each the default on every backend for its own
677/// element.
678///
679/// The `\ref` rule reads the counter table `flm.counters` optionally, as a
680/// table of another feature ([`LoweringDecl::reads_opt`]): where the
681/// numbering feature is registered, the stage that writes the table is
682/// scheduled; where it is not, the rule shows a target's content, or its label with the Error
683/// `flm.refs.nothing-to-show` where it has no content.
684pub(super) fn rules(list: &Arc<ListTexts>) -> Vec<LoweringRule> {
685    let decl = || {
686        LoweringDecl::new().reads(REF_RESOLUTIONS).produces(pres::LINK).produces(pres::SPAN)
687    };
688    vec![
689        LoweringRule::new(
690            REF_RULE,
691            REF,
692            decl().reads_opt(COUNTERS),
693            Arc::new(RefRule { list: Arc::clone(list) }),
694            DefaultMark::Everywhere,
695        )
696        .docs(
697            "a `\\ref` lowers to one `flm.pres.link` per resolved target, around the target's \
698             number, its content or its label, and to a `flm.pres.span` styled as unresolved \
699             around the text of a target that nothing resolves",
700        ),
701        LoweringRule::new(
702            HYPERREF_RULE,
703            HYPERREF,
704            decl(),
705            Arc::new(HyperrefRule),
706            DefaultMark::Everywhere,
707        )
708        .docs(
709            "a `\\hyperref` lowers to a `flm.pres.link` around the text the author wrote when \
710             its target resolves, and to a `flm.pres.span` styled as unresolved around the \
711             same text when it does not",
712        ),
713    ]
714}