Skip to main content

flm_core/stdlib/features/refs/
elements.rs

1//! The `\label` field and the two referencing elements of the
2//! [`refs`](super) feature, `\ref` and `\hyperref`: their declarations and
3//! the functions that read what an author wrote in them.
4//!
5//! # The label field
6//!
7//! `\label{type:label}` is a
8//! [field](crate::guide::concepts_overview#fields-data-a-construct-reads): a
9//! macro that a construct absorbs as data after its own arguments, as in
10//! `\section{Introduction}\label{sec:intro}`. The parser builds it, inside
11//! the construct's trailing argument, as a macro node named `label` that
12//! carries the language's field element
13//! ([`FIELD`](crate::lang::structural::FIELD)). It can be written only after a construct that
14//! declares it.
15//!
16//! A field is data that its parent construct reads, so no function here looks
17//! for `\label` nodes across a document: the construct that declared the
18//! field reads it with [`label_uses`] and turns what it read into the
19//! reference point it declares. A `\label` node that reaches a backend's
20//! lowering on its own is an error, reported by the field rule
21//! ([`FieldRule`](crate::stdlib::backends::lowering::FieldRule)).
22//!
23//! A construct that accepts labels declares [`label_fields_arg`] as its last
24//! argument: a tack-on argument (the trailing argument that absorbs field
25//! macros; [`ArgStdKind::TackOn`]) named [`FIELDS_ARG`], holding a repeatable
26//! field named [`LABEL_FIELD`] whose one character-group argument is named
27//! [`TARGET_ARG`]. [`label_uses`] reads that shape, so the declaration is
28//! written once, here.
29//!
30//! [`label_uses`] returns every field as written together with its parsed
31//! label, and [`point_labels`] splits the result into the two lists a
32//! reference point holds: the labels, and the texts that are not spelled
33//! `type:label`, which the label scan reports.
34//!
35//! A `\label` that is not a tack-on field can be written in two other places.
36//! In both, its node is a field node (its element is named `flm.field`)
37//! written `\label`, so that one function, [`label_use`], reads a `\label`
38//! node wherever it is written:
39//!
40//! - inside the body of a display-math environment, where the
41//!   [`math`](crate::stdlib::features::math) feature declares `\label` as a
42//!   command of its own, so that the environment reads its lines' labels
43//!   exactly as a heading reads its own;
44//! - inside an argument that refers to the scoped package [`LABEL_PACKAGE`]
45//!   (`flm.refs.label`), which this feature declares ([`label_package`]). A
46//!   scoped package ([`ScopedPackageDef`]) is a set of element declarations
47//!   that can be written only inside the environment bodies and arguments
48//!   whose declarations refer to it by name
49//!   ([scoped packages](crate::guide::concepts_overview#scoped-packages)). This
50//!   one holds one command, `\label`, and the optional argument of `\footnote`
51//!   refers to it, so that `\footnote[\label{fn:x}]{…}` labels the note. The
52//!   construct reads the labels of such an argument with [`label_uses_in`],
53//!   which reads a run of nodes.
54//!
55//! # The `\ref` element
56//!
57//! `\ref[options]{type:label}` is the element [`REF`] (`flm.ref`), one shared
58//! element value ([`ref_element`]) whose per-value data is [`RefElement`],
59//! which implements the [`Referencing`] aspect. **A `\ref` may point at
60//! several targets**, written as one text with commas between them
61//! (`\ref{eq:a,eq:b}`): the text is split at the commas ([`split_targets`])
62//! and each part is a target of its own. The node declares one reference site
63//! per target that is spelled `type:label`, in the order they were written; a
64//! target that is not spelled that way declares no site, and the label scan
65//! reports it.
66//!
67//! The key-value options argument holds the display options, read with
68//! [`ref_display_options`]: a bare key requests a wording variant of the word
69//! before a number, and the key [`NO_PREFIX_KEY`] (`noprefix`) leaves that
70//! word out. The argument is declared with an opaque wrapper
71//! ([`ArgDef::with_opaque_wrapper`]), because its keys are read as data: the
72//! typographic substitutions of the document's text do not apply to them.
73//! They are recorded as the document wrote them: the key
74//! [`CAPITAL_KEY`] (`S`) is kept as written, and the `\ref` lowering rule
75//! turns it into a request for the variant [`CAPITAL_VARIANT`] where the
76//! counter style declares it, and for the usual wording otherwise. The
77//! recomposed LaTeX leaves the typesetting of a reference to LaTeX and writes the
78//! options back as the document wrote them; the default definition of the
79//! LaTeX hook `\flmRef` translates them for the LaTeX package that sets the
80//! reference
81//! ([`refs_piece`](crate::stdlib::backends::latex::preamble::refs_piece)).
82//!
83//! # The `\hyperref` element
84//!
85//! `\hyperref[type:label]{text}` is the element [`HYPERREF`]
86//! (`flm.hyperref`), one shared element value ([`hyperref_element`]) whose
87//! per-value data is [`HyperrefElement`], which implements the
88//! [`Referencing`] aspect as [`RefElement`] does: one reference site per node,
89//! whose target is the label in the brackets. A `\hyperref` differs from a
90//! `\ref` in one respect: it displays the text the author wrote in the
91//! braces, not what its target has to show. Its site is therefore recorded
92//! without the word before a number, so that nothing is placed before the
93//! author's text, and the command takes no display options.
94//!
95//! The brackets are an *optional* argument, parsed as FLM code rather than as
96//! the characters-only group a `\ref` target is written in, and declared with
97//! an opaque wrapper ([`ArgDef::with_opaque_wrapper`]), so that the label in
98//! them is kept as typed, as a `\ref` target is. [`hyperref_target`] reads it
99//! as characters: a target that holds anything but characters (a command, or
100//! a special character such as `~`) reads as the empty text, and so does an
101//! absent argument. The empty text is not spelled `type:label`, so it declares
102//! no site, and the label scan reports it as it reports any other text that is
103//! not a label.
104//!
105//! [`reference_targets`] reads the targets of either element. The places that
106//! walk every referencing node of the document call it: the label scan, the
107//! safe-labels stage and the recomposition rules.
108
109use std::sync::{Arc, LazyLock};
110
111use techy::core::node::NodeRef;
112use techy::extract::parse_keyval_drop_annotations;
113
114use crate::model::aspects::{
115    ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole, Label, MalformedLabel,
116    RefDisplayOptions, RefSite, Referencing,
117};
118use crate::model::element::{ElementSpec, element_value};
119use crate::lang::text::{chars_text, is_space, read_chars};
120use crate::lang::{Flm, FlmSpan};
121use crate::lang::mint::{
122    ArgDef, ArgStdKind, ElementDef, ScopedPackageDef, SyntaxDef, TackOnField, field_element,
123    is_field_named,
124};
125use crate::model::names::{FeatureName, Name};
126
127/// The `\ref` element's type name, `flm.ref`.
128///
129/// Its per-value data is a [`RefElement`], which is also the element's
130/// [`Referencing`] implementation. [`ref_element`] returns the element value.
131pub const REF: &str = "flm.ref";
132
133/// The `\label` field's name, `label`: what an author writes after the
134/// backslash, and the name under which a construct declares the field.
135pub const LABEL_FIELD: &str = "label";
136
137/// The name of the trailing tack-on argument a construct holds its `\label`
138/// fields in, `fields`: the argument [`label_fields_arg`] declares and
139/// [`label_uses`] reads.
140pub const FIELDS_ARG: &str = "fields";
141
142/// The name of the target argument of a `\ref`, a `\hyperref` and a
143/// `\label`, `target`: the argument that holds the label.
144pub const TARGET_ARG: &str = "target";
145
146/// The name of the scoped package that holds `\label` as a command,
147/// `flm.refs.label`: an argument whose declaration refers to it
148/// ([`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped)) accepts
149/// `\label{type:label}`. See [`label_package`].
150pub const LABEL_PACKAGE: &str = "flm.refs.label";
151
152/// The argument role of a label that a reference points to,
153/// `flm.refs.target`: the role of the target argument ([`TARGET_ARG`]) of
154/// `\ref` and `\hyperref`. The feature declares it; a feature with a
155/// reference command of its own sets it on that command's target argument
156/// and, so that a registry without this feature still builds, declares the
157/// role as a peer
158/// ([`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role)),
159/// as the `math` feature does for `\eqref`.
160pub const TARGET_ARG_ROLE: &str = "flm.refs.target";
161
162/// The argument role of a label that a `\label` attaches to a construct,
163/// `flm.refs.defined-label`: the role of the argument of the `\label` field
164/// ([`label_field`]) and of the `\label` command of the scoped package
165/// [`LABEL_PACKAGE`]. The feature declares it; a feature whose declarations
166/// hold either declares the role as a peer
167/// ([`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role)),
168/// so that a registry without this feature still builds.
169pub const DEFINED_LABEL_ARG_ROLE: &str = "flm.refs.defined-label";
170
171/// The name of a `\ref`'s options argument, `options`.
172pub const OPTIONS_ARG: &str = "options";
173
174/// The `\hyperref` element's type name, `flm.hyperref`.
175///
176/// Its per-value data is a [`HyperrefElement`], which is also the element's
177/// [`Referencing`] implementation. [`hyperref_element`] returns the element
178/// value.
179pub const HYPERREF: &str = "flm.hyperref";
180
181/// The name of the argument holding a `\hyperref`'s displayed text, `text`.
182pub const TEXT_ARG: &str = "text";
183
184/// The key of a `\ref`'s options that leaves out the word before a number
185/// (the prefix, such as "Eq."), `noprefix`.
186pub const NO_PREFIX_KEY: &str = "noprefix";
187
188/// The key of a `\ref`'s options that asks for the capitalized wording, `S`.
189///
190/// It is the only key of the display options that differs from the name of
191/// the variant it selects, and the only one that is a preference rather than
192/// a requirement: it selects [`CAPITAL_VARIANT`] where the counter style
193/// declares that variant, and the style's usual wording where it does not,
194/// with nothing reported. Every other bare key requests the variant of its
195/// own name, and a counter style that does not declare it makes the reference
196/// an Error ([`UndeclaredVariant`](super::UndeclaredVariant)).
197pub const CAPITAL_KEY: &str = "S";
198
199/// The counter style variant that the key [`CAPITAL_KEY`] selects, `capital`:
200/// the wording a counter style declares for a reference that opens a sentence
201/// (`Equation~(3)` rather than `Eq.~(3)`).
202///
203/// Requested through `S`, it is written where the counter style declares it,
204/// and the style's usual wording is written otherwise, with nothing reported.
205/// Written as a key itself (`\ref[capital]{…}`), it is a requirement like any
206/// other variant: where the counter style of a numbered target does not
207/// declare it, the reference is an Error, and that style writes its usual
208/// wording.
209pub const CAPITAL_VARIANT: &str = "capital";
210
211/// The counter style variant of the words written all in lowercase,
212/// `lowercase` (`lemma~4` rather than `Lemma~4`), which `\ref[lowercase]{…}`
213/// requests.
214pub const LOWERCASE_VARIANT: &str = "lowercase";
215
216/// The counter style variant of the abbreviated words, `abbreviated`
217/// (`Lem.~4` rather than `Lemma~4`), which `\ref[abbreviated]{…}` requests.
218pub const ABBREVIATED_VARIANT: &str = "abbreviated";
219
220/// The per-value data of the `flm.ref` element, and the element's
221/// [`Referencing`] implementation: it returns the reference sites a `\ref`
222/// node declares, one per target spelled `type:label`. See the module
223/// documentation.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct RefElement;
226
227/// The per-value data of the `flm.hyperref` element, and the element's
228/// [`Referencing`] implementation: it returns the one reference site a
229/// `\hyperref` node declares, or none when its target is not spelled
230/// `type:label`. See the module documentation.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub struct HyperrefElement;
233
234/// The trailing tack-on argument that a labeled construct declares as its
235/// last argument, so that `\thing{…}\label{x:y}` parses: one repeatable
236/// `\label` field with one character-group argument, under the names that
237/// [`label_uses`] reads ([`FIELDS_ARG`], [`LABEL_FIELD`], [`TARGET_ARG`]).
238///
239/// The field carries no element of this feature: like every tack-on field,
240/// its node carries the language's field element
241/// ([`FIELD`](crate::lang::structural::FIELD)) and is read by its name, and
242/// only the construct that declared it reads it, through
243/// [`label_uses`]. A construct that accepts other fields beside `\label`
244/// builds the argument itself and lists the same field ([`label_field`])
245/// among them.
246///
247/// The field's argument has the argument role [`DEFINED_LABEL_ARG_ROLE`],
248/// which this feature declares. A feature whose declarations use this
249/// argument also declares that role as a peer
250/// ([`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role)),
251/// as the standard features do, so that a registry without this feature
252/// still builds; without the peer declaration, building such a registry
253/// fails.
254///
255/// # Examples
256///
257/// ```
258/// use flm_core::stdlib::features::refs::{FIELDS_ARG, label_fields_arg};
259///
260/// let arg = label_fields_arg();
261/// assert_eq!(arg.name.as_deref(), Some(FIELDS_ARG));
262/// assert_eq!(arg.kind.tack_on_fields().map(<[_]>::len), Some(1));
263/// ```
264pub fn label_fields_arg() -> ArgDef {
265    ArgDef::named(FIELDS_ARG, ArgStdKind::TackOn { fields: vec![label_field()] })
266        .docs("`\\label{…}` fields written after the construct, each attaching a label to it.")
267}
268
269/// The `\label` field of [`label_fields_arg`]: repeatable, with one
270/// character-group argument named [`TARGET_ARG`]. A construct that accepts
271/// other fields beside `\label` lists this one among them in its own tack-on
272/// argument, which it declares under the name [`FIELDS_ARG`] so that
273/// [`label_uses`] reads it.
274///
275/// The field's argument has the argument role [`DEFINED_LABEL_ARG_ROLE`]:
276/// a feature that lists the field also declares that role as a peer, as for
277/// [`label_fields_arg`].
278pub fn label_field() -> TackOnField {
279    TackOnField::new(
280        LABEL_FIELD,
281        vec![
282            ArgDef::named(TARGET_ARG, ArgStdKind::CharsGroup)
283                .docs("The label, written `type:label` (`sec:intro`).")
284                .role(DEFINED_LABEL_ARG_ROLE),
285        ],
286    )
287    .repeatable()
288    .docs("Attaches a label to the construct, which a reference can point at; may be repeated.")
289}
290
291/// One `\label` written on a node, as [`label_uses`], [`label_uses_in`] and
292/// [`label_use`] return it: the text as written, the span of the `\label`
293/// node, and the label when the text is spelled `type:label`.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct LabelUse {
296    /// The text between the braces.
297    pub text: String,
298    /// The span of the `\label` node.
299    pub span: FlmSpan,
300    /// The parsed label, when the text is `type:label`.
301    pub label: Option<Label>,
302}
303
304/// The text of a `\label` node (the characters of its target argument,
305/// trimmed), or `None` when the node is not a `\label` field, has no target
306/// argument, or holds something that is not characters: a command, or a
307/// placeholder of a user definition's template that was not expanded
308/// ([`chars_text`]). The text is not checked for the `type:label` spelling.
309///
310/// Returning `None` for a placeholder does not let a labeled template
311/// through unnoticed: the user-definitions feature refuses a template, kept
312/// rather than expanded, that holds a `\label` completed by a placeholder
313/// ([`KeptTemplateDeclaresPoint`](crate::stdlib::features::userdefs::KeptTemplateDeclaresPoint)).
314pub fn field_text(node: &NodeRef<'_, Flm>) -> Option<String> {
315    if !is_field_named(node, LABEL_FIELD) {
316        return None;
317    }
318    let content = node.argument_content_nodes_named(TARGET_ARG).ok()??;
319    chars_text(content.iter()).map(|text| text.trim_matches(is_space).to_string())
320}
321
322/// Every `\label` field written on `node`, in its [`FIELDS_ARG`] argument, in
323/// document order. Empty for a node with no such argument.
324///
325/// A construct that declared the field ([`label_fields_arg`]) calls this
326/// function to read its labels. Pass the result to [`point_labels`] to build
327/// the reference point the construct declares.
328pub fn label_uses(node: &NodeRef<'_, Flm>) -> Vec<LabelUse> {
329    let Ok(Some(fields)) = node.argument_content_nodes_named(FIELDS_ARG) else {
330        return Vec::new();
331    };
332    label_uses_in(fields.iter())
333}
334
335/// Every `\label` node of `nodes`, in their order, read as [`label_uses`]
336/// reads the fields written on a node. A construct whose labels are written
337/// in a run of nodes of their own calls it: the content of an argument that
338/// refers to the scoped package [`LABEL_PACKAGE`], such as the optional
339/// argument of `\footnote`. Every other node of the run is skipped; a
340/// construct that must refuse anything but labels in that argument looks for
341/// the other nodes itself.
342///
343/// Pass the result to [`point_labels`] to build the reference point the
344/// construct declares.
345///
346/// # Examples
347///
348/// ```
349/// use std::sync::Arc;
350/// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
351/// use flm_core::lang::{parse_fragment, FlmOrigin, FlmSource, ParseOptions};
352/// use flm_core::model::aspects::Label;
353/// use flm_core::model::doc::FragmentLayout;
354/// use flm_core::stdlib::{self, StdlibConfig};
355/// use flm_core::stdlib::features::refs::label_uses_in;
356///
357/// let mut builder = RegistryBuilder::new();
358/// builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
359/// builder.use_package(flm_core::math_passthrough::package());
360/// let registry = builder.build(&RegistryInputs::new())?;
361/// let source = FlmSource::new(r"Text.\footnote[\label{fn:a} \label{fn:b}]{A note.}");
362/// let fragment = parse_fragment(
363///     registry.lang(),
364///     Arc::new(source.with_origin(FlmOrigin::none())),
365///     FragmentLayout::default(),
366///     &ParseOptions::default(),
367/// )?;
368/// let note = fragment.tree().root().descendants()
369///     .find(|node| node.name() == Some("footnote"))
370///     .expect("the note");
371/// let run = note.argument_content_nodes_named("labels")?.expect("written");
372/// let uses = label_uses_in(run.iter());
373/// assert_eq!(uses.len(), 2);
374/// assert_eq!(uses[1].label, Some(Label::new("fn", "b")));
375/// # Ok::<(), Box<dyn std::error::Error>>(())
376/// ```
377pub fn label_uses_in<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> Vec<LabelUse> {
378    // One reader of one `\label` node, [`label_use`], is what reads each of
379    // them, wherever they stand, so the forms can never answer differently.
380    nodes.into_iter().filter_map(|node| label_use(&node)).collect()
381}
382
383/// The scoped package [`LABEL_PACKAGE`], declared by `owner`: one command,
384/// `\label{type:label}`, whose one character-group argument is named
385/// [`TARGET_ARG`] and whose element is named `flm.field`
386/// ([`field_element`]), so that its node is a field node named
387/// [`LABEL_FIELD`], which [`label_use`] reads as it reads a tack-on
388/// `\label`.
389///
390/// The `refs` feature registers it. A scoped package
391/// ([`ScopedPackageDef`]) can be written only inside the bodies and arguments
392/// whose declarations refer to it, so `\label{…}` is accepted in such an
393/// argument and nowhere else: `\label` written in running text is an unknown
394/// command, as everywhere outside a construct that accepts labels. A feature
395/// that refers to the package from an argument of its own declares it with a
396/// peer declaration
397/// ([`FeatureBuilder::peer_scoped_package`](crate::core::registry::FeatureBuilder::peer_scoped_package)),
398/// so that a registry without this feature still builds; the argument then
399/// accepts no `\label`.
400///
401/// The argument of the package's `\label` has the argument role
402/// [`DEFINED_LABEL_ARG_ROLE`], which this feature declares. A feature that
403/// places the package's declaration in a scoped package of its own, as the
404/// `floats` feature does, also declares that role as a peer
405/// ([`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role)),
406/// so that a registry without this feature still builds.
407///
408/// The registry's feature builder attributes the package and its declaration
409/// to the registering feature regardless of `owner`; the parameter matters
410/// only for a package built by hand.
411pub fn label_package(owner: impl Into<FeatureName>) -> ScopedPackageDef {
412    let owner = owner.into();
413    let label = ElementDef::new(
414        owner.clone(),
415        [LABEL_FIELD],
416        SyntaxDef::Macro {
417            args: vec![
418                ArgDef::named(TARGET_ARG, ArgStdKind::CharsGroup)
419                    .docs("The label, written `type:label` (`fn:intro`).")
420                    .role(DEFINED_LABEL_ARG_ROLE),
421            ],
422        },
423        field_element(
424            "A `\\label{type:label}` inside an argument that accepts labels: a label \
425             attached to the construct the argument belongs to.",
426        ),
427    )
428    .docs("Attaches a label to the construct whose argument holds it.");
429    ScopedPackageDef {
430        owner,
431        name: Name::from(LABEL_PACKAGE),
432        elements: vec![label],
433        docs: String::from(
434            "The command available in an argument that accepts labels: \
435             `\\label{type:label}`.",
436        ),
437    }
438}
439
440/// Splits the `\label`s a construct read into the two lists a reference
441/// point holds: the labels spelled `type:label`, in the order they were
442/// written, and the texts that are not, each with the span to report it at
443/// and its position in the whole list.
444///
445/// A construct's [`Referenceable`](crate::model::aspects::Referenceable)
446/// implementation passes the two lists unchanged into the point it declares
447/// ([`RefPoint::labels`](crate::model::aspects::RefPoint::labels) and
448/// [`RefPoint::malformed`](crate::model::aspects::RefPoint::malformed)). A
449/// malformed text defines nothing; the label scan ([`SCAN`](super::SCAN))
450/// reports it once, at its own
451/// `\label`, when it reads the point. The positions put the two lists back
452/// into the order the document wrote them
453/// ([`RefPointRecord::mentions`](crate::stdlib::features::refpoints::RefPointRecord::mentions)).
454pub fn point_labels<'u>(
455    uses: impl IntoIterator<Item = &'u LabelUse>,
456) -> (Vec<Label>, Vec<MalformedLabel>) {
457    let mut labels = Vec::new();
458    let mut malformed = Vec::new();
459    for (position, us) in uses.into_iter().enumerate() {
460        match &us.label {
461            Some(label) => labels.push(label.clone()),
462            None => malformed.push(MalformedLabel {
463                text: us.text.clone(),
464                span: us.span.clone(),
465                position,
466            }),
467        }
468    }
469    (labels, malformed)
470}
471
472/// Reads one `\label` node, wherever it is written (a field absorbed by a
473/// labeled element, the `\label` command the
474/// [`math`](crate::stdlib::features::math) feature declares inside a
475/// display-math environment's body, or the command of the scoped package
476/// [`LABEL_PACKAGE`]): its text as written, its span, and the label when the
477/// text is spelled `type:label`. `None` when `node` is not a `\label` node,
478/// has no target argument, or holds something that is not characters
479/// ([`field_text`]).
480///
481/// [`label_uses`] reads the fields attached to a labeled element;
482/// [`label_uses_in`] reads a run of nodes; this function reads one `\label`
483/// node.
484pub fn label_use(node: &NodeRef<'_, Flm>) -> Option<LabelUse> {
485    let text = field_text(node)?;
486    let label = Label::parse(&text);
487    Some(LabelUse { text, span: node.span().clone(), label })
488}
489
490/// One target written in a reference command: the text as written, with the
491/// whitespace around it trimmed, and the label when that text is spelled
492/// `type:label`.
493///
494/// A `\ref` may point at several targets, so its target argument is read as
495/// a list of these ([`ref_targets`]); a `\hyperref` has one
496/// ([`hyperref_target`]).
497///
498/// A target whose text is not spelled `type:label` points at nothing: it
499/// declares no reference site, the label scan ([`SCAN`](super::SCAN)) reports it, and the output
500/// shows the text as written, marked unresolved.
501#[derive(Debug, Clone, PartialEq, Eq)]
502pub struct RefTargetText {
503    /// The text as written, trimmed.
504    pub text: String,
505    /// The label, when the text is spelled `type:label`.
506    pub label: Option<Label>,
507}
508
509/// The targets written in the text of a reference's target argument: the text
510/// split at the commas, each part trimmed and parsed as a label.
511///
512/// The empty text is one target, not none, so that `\ref{}` has one target,
513/// which points at nothing, rather than no target at all.
514///
515/// # Examples
516///
517/// ```
518/// use flm_core::model::aspects::Label;
519/// use flm_core::stdlib::features::refs::split_targets;
520///
521/// let targets = split_targets("sec:intro, eq:euler");
522/// assert_eq!(targets.len(), 2);
523/// assert_eq!(targets[0].label, Some(Label::new("sec", "intro")));
524/// assert_eq!(targets[1].text, "eq:euler");
525///
526/// // A part that is not spelled `type:label` has no label.
527/// assert_eq!(split_targets("nolabel")[0].label, None);
528/// ```
529pub fn split_targets(text: &str) -> Vec<RefTargetText> {
530    text.split(',')
531        .map(|piece| {
532            let text = piece.trim_matches(is_space).to_string();
533            let label = Label::parse(&text);
534            RefTargetText { text, label }
535        })
536        .collect()
537}
538
539/// The targets of a `\ref` node, in the order they were written: its target
540/// argument read as characters and split at the commas ([`split_targets`]).
541///
542/// `None` when the node is not a `\ref`, has no target argument, or holds
543/// something that is not characters: a command, or a placeholder of a user
544/// definition's template that was not expanded ([`chars_text`]). Such a
545/// target has no text to read, declares no site, and nothing is reported for
546/// it.
547pub fn ref_targets(node: &NodeRef<'_, Flm>) -> Option<Vec<RefTargetText>> {
548    element_value::<RefElement>(node)?;
549    let content = node.argument_content_nodes_named(TARGET_ARG).ok()??;
550    let text = chars_text(content.iter())?;
551    Some(split_targets(&text))
552}
553
554/// A `\ref` node's display options, read from its key-value options
555/// argument: a key other than [`NO_PREFIX_KEY`] requests the wording variant
556/// of its own name (the last such key wins), and [`NO_PREFIX_KEY`] leaves out
557/// the word before a number. An absent or unreadable argument gives the
558/// default options.
559pub fn ref_display_options(node: &NodeRef<'_, Flm>) -> RefDisplayOptions {
560    let mut options = RefDisplayOptions::default();
561    let Ok(Some(content)) = node.argument_content_nodes_named(OPTIONS_ARG) else {
562        return options;
563    };
564    let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
565        return options;
566    };
567    for entry in keyvals.iter() {
568        let key = entry.key();
569        if key.is_empty() {
570            continue;
571        }
572        if key == NO_PREFIX_KEY {
573            options.with_prefix = false;
574        } else {
575            options.variant = Some(key.to_string());
576        }
577    }
578    options
579}
580
581/// The target of a `\hyperref` node (the label written in the brackets) as
582/// characters with the whitespace around it trimmed, and the label when that
583/// text is spelled `type:label`.
584///
585/// `None` when the node is not a `\hyperref`, or when its target holds a
586/// placeholder of a user definition's template that was not expanded: such a
587/// target has no text to read, declares no site, and nothing is reported for
588/// it.
589///
590/// The brackets are an optional argument parsed as FLM code and kept as
591/// typed, so a target that is not made of characters (a command, a special
592/// character such as `~`) reads as the empty text, and so does an absent
593/// argument (`\hyperref{text}`). The empty text is not a label: the label scan
594/// ([`SCAN`](super::SCAN)) reports it, and the reference is shown unresolved.
595/// See the module documentation.
596pub fn hyperref_target(node: &NodeRef<'_, Flm>) -> Option<RefTargetText> {
597    element_value::<HyperrefElement>(node)?;
598    let text = match node.argument_content_nodes_named(TARGET_ARG) {
599        Ok(Some(content)) => match read_chars(content.iter()) {
600            Ok(read) if read.has_placeholder() => return None,
601            Ok(read) => read.text().unwrap_or_default().trim_matches(is_space).to_string(),
602            Err(_) => String::new(),
603        },
604        _ => String::new(),
605    };
606    let label = Label::parse(&text);
607    Some(RefTargetText { text, label })
608}
609
610/// The targets of `node` when it is a `\ref` or a `\hyperref`:
611/// [`ref_targets`] for a `\ref`, the one target of [`hyperref_target`] for a
612/// `\hyperref`, and `None` for any other node.
613///
614/// The places that walk every node of a document to find the targets of
615/// references call it: the label scan ([`SCAN`](super::SCAN)), which reports a target that
616/// is not spelled `type:label`; the safe-labels stage
617/// ([`SafeLabelsStage`](super::SafeLabelsStage)), which allocates a safe label
618/// at a label's first mention; and the recomposition rules, which write those
619/// safe labels.
620pub fn reference_targets(node: &NodeRef<'_, Flm>) -> Option<Vec<RefTargetText>> {
621    ref_targets(node).or_else(|| hyperref_target(node).map(|target| vec![target]))
622}
623
624impl Referencing for RefElement {
625    /// One site per target of the `\ref` that is spelled `type:label`, in the
626    /// order the targets were written, all with the node's own display
627    /// options. A target that is not a label declares no site, so the index
628    /// of a site is its place among the *labeled* targets, not among all
629    /// targets; [`lower_reference`](super::lower_reference) counts the same
630    /// way.
631    fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
632        let display = ref_display_options(node);
633        ref_targets(node)
634            .into_iter()
635            .flatten()
636            .filter_map(|target| target.label)
637            .map(|target| RefSite { target, display: display.clone(), shown: true })
638            .collect()
639    }
640}
641
642impl Referencing for HyperrefElement {
643    /// The one site a `\hyperref` declares, or none when its target is not
644    /// spelled `type:label`. Its display options leave out the word before a
645    /// number, because the site shows the author's own text and nothing is
646    /// placed before it.
647    fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
648        match hyperref_target(node) {
649            Some(RefTargetText { label: Some(target), .. }) => vec![RefSite {
650                target,
651                display: RefDisplayOptions { variant: None, with_prefix: false },
652                shown: true,
653            }],
654            _ => Vec::new(),
655        }
656    }
657}
658
659/// The target of a `\ref` (its argument [`TARGET_ARG`]) and its display
660/// options (its argument [`OPTIONS_ARG`]) are not words of the text around
661/// the reference: they are instructions to the reference. A heading whose
662/// title holds a `\ref` is identified by the title's own words, without the
663/// target and the options.
664impl ApartFromText for RefElement {
665    fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
666        vec![
667            ContentRef::ArgumentNamed(TARGET_ARG.to_string()),
668            ContentRef::ArgumentNamed(OPTIONS_ARG.to_string()),
669        ]
670    }
671}
672
673/// The target of a `\hyperref` (its argument [`TARGET_ARG`]) is not part of
674/// the words of the text around the reference, as for a `\ref`; the text the
675/// author wrote for it is, and is kept.
676impl ApartFromText for HyperrefElement {
677    fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
678        vec![ContentRef::ArgumentNamed(TARGET_ARG.to_string())]
679    }
680}
681
682static REF_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
683    Arc::new(
684        ElementSpec::new(REF)
685            .docs(
686                "A reference to a labeled place, showing its number, else its content, else \
687                 the label.",
688            )
689            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
690            .with::<dyn ApartFromText>(Arc::new(RefElement))
691            .with::<dyn Referencing>(Arc::new(RefElement))
692            .with_value(Arc::new(RefElement)),
693    )
694});
695
696/// The element value of every `\ref` node. It is one shared value, like the
697/// label field's, so that no caller can create a second element value of type
698/// `flm.ref` (an element is identified by its value, not by its name).
699pub fn ref_element() -> Arc<ElementSpec> {
700    Arc::clone(&REF_ELEMENT)
701}
702
703/// The arguments of `\ref`, in order: the key-value options, then the target
704/// label. A feature declaring a reference-like command of its own can reuse
705/// this list.
706pub fn ref_args() -> Vec<ArgDef> {
707    vec![
708        ArgDef::named(OPTIONS_ARG, ArgStdKind::KeyVals)
709            .docs(
710                "Display options: the name of a wording variant of the word before a number, \
711                 `S` for the capitalized wording, or `noprefix` to leave the word out.",
712            )
713            .with_opaque_wrapper(),
714        ArgDef::named(TARGET_ARG, ArgStdKind::CharsGroup)
715            .docs("The target label, `type:label`, or several separated by commas.")
716            .role(TARGET_ARG_ROLE),
717    ]
718}
719
720static HYPERREF_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
721    Arc::new(
722        ElementSpec::new(HYPERREF)
723            .docs("A reference to a labeled place, showing the text written for it.")
724            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
725            .with::<dyn ApartFromText>(Arc::new(HyperrefElement))
726            .with::<dyn Referencing>(Arc::new(HyperrefElement))
727            .with_value(Arc::new(HyperrefElement)),
728    )
729});
730
731/// The element value of every `\hyperref` node, shared as [`ref_element`]'s
732/// is for every `\ref` node.
733pub fn hyperref_element() -> Arc<ElementSpec> {
734    Arc::clone(&HYPERREF_ELEMENT)
735}
736
737/// The arguments of `\hyperref`, in order: the optional target label, then
738/// the text to display for it.
739pub fn hyperref_args() -> Vec<ArgDef> {
740    vec![
741        ArgDef::named(TARGET_ARG, ArgStdKind::Optional)
742            .docs("The target label, `type:label`.")
743            .role(TARGET_ARG_ROLE)
744            .with_opaque_wrapper(),
745        ArgDef::named(TEXT_ARG, ArgStdKind::Mandatory).docs("The text shown for the target."),
746    ]
747}
748
749#[cfg(test)]
750mod tests {
751    use super::*;
752
753    #[test]
754    fn the_ref_element_carries_the_referencing_aspect_and_its_value() {
755        let element = ref_element();
756        assert!(element.has_aspect::<dyn Referencing>());
757        assert!(element.value_as::<RefElement>().is_some());
758    }
759
760    #[test]
761    fn the_ref_element_is_one_shared_value() {
762        assert!(ElementSpec::same_value(&ref_element(), &ref_element()));
763    }
764
765    #[test]
766    fn the_hyperref_element_carries_the_referencing_aspect_and_is_one_shared_value() {
767        let element = hyperref_element();
768        assert!(element.has_aspect::<dyn Referencing>());
769        assert!(element.value_as::<HyperrefElement>().is_some());
770        assert!(ElementSpec::same_value(&hyperref_element(), &hyperref_element()));
771        // Two elements, two values: a rule for one never fires at the other.
772        assert!(!ElementSpec::same_value(&hyperref_element(), &ref_element()));
773    }
774}