Skip to main content

flm_core/stdlib/features/defterm/
elements.rs

1//! The two elements of the [`defterm`](super) feature, the term definition
2//! (`\begin{defterm}{term}…\end{defterm}`, [`DEFTERM`]) and the term link
3//! (`\term[ref]{shown}`, [`TERM`]), with the identity of a term, which both
4//! compute with the same function, [`spelling_identity`].
5//!
6//! # The identity of a term
7//!
8//! A term is matched by what its author wrote, not by what it shows. The
9//! **identity** of a term is the source text of the nodes the term is written
10//! as, each node written out again from what it records of its own source
11//! text (its characters, the command and arguments of a call, the delimiters
12//! of a group, a formula as written), with every run of whitespace made one
13//! space and the ends trimmed. Source comments between those nodes are left
14//! out. `\(\alpha\)-decay` and `\emph{Markov} chain` keep their markup, and
15//! `Markov  chain` written across a line break is the same term as `Markov
16//! chain`. The space literals `~` and `\ ` are markup there too, written out
17//! again as they are written: they are part of the term, so `~x` is not the
18//! term `x`, and a term holding only `~` is not empty. Matching is exact, case
19//! included: `Entropy` and `entropy` are two terms. A term is read in the
20//! tree where it occurs, after the same passes over the document as every
21//! other term, so the typographic substitutions of the block-structure pass
22//! (`--` read as a dash) apply alike to a term definition's term and to a term
23//! link's.
24//!
25//! The source text of each node is read on its own, never as one slice of a
26//! source: the term of a term definition written through a user definition's
27//! template holds nodes of the template beside nodes of the use site, and
28//! each of them reads as it was written.
29//!
30//! # The term definition
31//!
32//! A term definition is one [reference
33//! point](crate::model::aspects::RefPoint) of the reference kind
34//! [`DEFINITION_KIND`], declared by [`DeftermElement`]. Its content, which a
35//! reference to it shows, is the term argument. It carries labels of three
36//! origins, in this order:
37//!
38//! 1. one label computed from the term's identity, by which a term link finds
39//!    the term definition;
40//! 2. one more label computed from the identity of each alias, written
41//!    `\aliasterm{…}`, a repeatable field of the environment: another way of
42//!    writing the term (for example a plural) under which a term link finds
43//!    the same term definition;
44//! 3. the labels the author wrote with `\label{…}`, of the types `term` and
45//!    `topic`, by which `\ref` and `\hyperref` refer to the term definition.
46//!
47//! The computed labels are labels of the references feature like any other,
48//! so that a term link resolves through that feature's stages. They are
49//! never written in a document, and the label types a term definition
50//! accepts apply to its written labels alone: a written label of any other
51//! type is refused. The point is anchored on its first label: the label
52//! computed from the term, or, where the term is empty (and so computes no
53//! label), the first alias's label or the first written label.
54//!
55//! # The term link
56//!
57//! A term link, [`TermElement`], declares one
58//! [reference site](crate::model::aspects::RefSite) whose target is the
59//! label computed from the term in its bracket argument, or, where it has
60//! none, from the term in its braces ([`term_target`]). The references
61//! feature resolves it as it resolves every site; no code of this feature
62//! looks a term definition up.
63
64use std::sync::{Arc, LazyLock};
65
66use techy::core::node::{NodeRef, NodeSlice};
67
68use crate::lang::mint::{ArgDef, ArgStdKind, TackOnField, field_name};
69use crate::lang::text::collapse_whitespace;
70use crate::lang::{Flm, FlmCallableType};
71use crate::model::aspects::{
72    AcceptedRefTypes, AnchorPolicy, ApartFromText, BlockRole, BlockRoleAspect, ContentRef,
73    FixedBlockRole, Label, RefDisplayOptions, RefPoint, RefSite, Referenceable, Referencing,
74};
75use crate::model::element::{ElementSpec, element_value};
76use crate::model::names::RefKind;
77use crate::stdlib::backends::pres::spelling_identity;
78use crate::stdlib::features::refs;
79
80/// The element name of a term definition, `flm.defterm`: the environment
81/// `defterm`. Its single element value carries a [`DeftermElement`]
82/// ([`defterm_element`]).
83pub const DEFTERM: &str = "flm.defterm";
84
85/// The element name of a term link, `flm.term`: the command `\term`. Its
86/// single element value carries a [`TermElement`] ([`term_element`]).
87pub const TERM: &str = "flm.term";
88
89/// The name of the `defterm` environment's argument that holds the term,
90/// `term`.
91pub const TERM_ARG: &str = "term";
92
93/// The name of the field that declares an alias of the term being defined,
94/// `aliasterm`, written `\aliasterm{…}` after the term, beside the
95/// `\label{…}` fields. It is one of the fields of the environment's tack-on
96/// argument (the trailing argument that absorbs field macros; see
97/// [`defterm_args`]).
98pub const ALIAS_FIELD: &str = "aliasterm";
99
100/// The name of the single argument of an [`ALIAS_FIELD`] field, `term`: the
101/// alias.
102pub const ALIAS_ARG: &str = "term";
103
104/// The name of a term link's optional argument, `ref`: the term it links
105/// to, where that term is not the text the link shows.
106pub const REF_ARG: &str = "ref";
107
108/// The name of a term link's mandatory argument, `shown`: the text it
109/// shows.
110pub const SHOWN_ARG: &str = "shown";
111
112/// The argument role of a term that a definition defines,
113/// `flm.defterm.defined-term`: the role of the term argument ([`TERM_ARG`])
114/// of the `defterm` environment and of the argument of its `\aliasterm`
115/// field ([`ALIAS_ARG`]).
116pub const DEFINED_TERM_ARG_ROLE: &str = "flm.defterm.defined-term";
117
118/// The argument role of the term that a term link points to,
119/// `flm.defterm.target`: the role of the bracket argument ([`REF_ARG`]) of
120/// `\term`.
121pub const TARGET_ARG_ROLE: &str = "flm.defterm.target";
122
123/// The reference kind of a term definition's reference point, `defterm`.
124pub const DEFINITION_KIND: &str = "defterm";
125
126/// The label types an author may write on a term definition with
127/// `\label{…}`, `term` and `topic`: `term` is to a term definition what `sec`
128/// is to a heading, and `topic` is accepted by a heading too.
129pub const LABEL_TYPES: [&str; 2] = ["term", "topic"];
130
131/// The type of the labels computed from a term's identity, `defterm`: kept
132/// apart from every type an author writes, so that a computed label can never
133/// equal a label an author writes.
134pub(crate) const COMPUTED_TYPE: &str = "defterm";
135
136/// The label computed from the identity `identity`, or `None` for the empty
137/// identity, which identifies no term.
138fn computed_label(identity: String) -> Option<Label> {
139    (!identity.is_empty()).then(|| Label::new(COMPUTED_TYPE, identity))
140}
141
142/// Whether a placeholder of a user definition's template is among `nodes`
143/// or their descendants: then `nodes` are the content of a template kept
144/// rather than expanded, in which no term can be read.
145pub(super) fn holds_placeholder<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> bool {
146    nodes.into_iter().any(|node| {
147        std::iter::once(node)
148            .chain(node.descendants())
149            .any(|inner| inner.callable_type() == Some(FlmCallableType::Placeholder))
150    })
151}
152
153// --- the definition --------------------------------------------------------------------------
154
155/// The data of the element value of [`DEFTERM`], and the aspects it
156/// implements: a block, with one reference point ([`Referenceable`]) and its
157/// fields kept apart from its text ([`ApartFromText`]). See the [module
158/// documentation](self#the-term-definition).
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct DeftermElement;
161
162/// The labels a term definition computes, in order: its term's, then each
163/// alias's, each once; empty for a node that is not a term definition. A term
164/// link finds the term definition by one of these ([`term_target`]).
165pub(super) fn computed_labels(node: &NodeRef<'_, Flm>) -> Vec<Label> {
166    if element_value::<DeftermElement>(node).is_none() {
167        return Vec::new();
168    }
169    let mut labels = Vec::new();
170    let term = node.argument_content_nodes_named(TERM_ARG).ok().flatten();
171    if let Some(label) = term.and_then(|content| computed_label(declared_identity(content.iter()))) {
172        labels.push(label);
173    }
174    let fields = node.argument_content_nodes_named(refs::FIELDS_ARG).ok().flatten();
175    for field in fields.iter().flat_map(|fields| fields.iter()) {
176        if field_name(&field).is_none_or(|name| name != ALIAS_FIELD) {
177            continue;
178        }
179        let alias = field.argument_content_nodes_named(ALIAS_ARG).ok().flatten();
180        if let Some(label) = alias.and_then(|content| computed_label(declared_identity(content.iter())))
181        {
182            if !labels.contains(&label) {
183                labels.push(label);
184            }
185        }
186    }
187    labels
188}
189
190/// The identity a term definition declares for the term or the alias written
191/// as `nodes`: [`spelling_identity`], except for a term that holds a
192/// placeholder of a user definition's template. No document holds such a
193/// term, only a template kept rather than expanded does, and it is read as
194/// the template's text as written, `#1` included. Such a term definition
195/// still declares its labels, so that the user-definitions feature refuses
196/// the template that holds it, as it refuses every template that declares a
197/// reference point.
198fn declared_identity<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>> + Clone) -> String {
199    if !holds_placeholder(nodes.clone()) {
200        return spelling_identity(nodes);
201    }
202    // The span, not `spelling_identity`: the source recomposer re-emits nothing
203    // for a placeholder, so `spelling_identity` reads `#1` as the empty text,
204    // which would declare no label and let the kept template through.
205    let written: String = nodes
206        .into_iter()
207        .filter(|node| !node.is_comment())
208        .map(|node| node.span_content())
209        .collect();
210    collapse_whitespace(&written)
211}
212
213/// Whether the term definition `node` defines the term that `target`
214/// identifies, under its term or under one of its aliases.
215fn defines(node: &NodeRef<'_, Flm>, target: &Label) -> bool {
216    computed_labels(node).iter().any(|label| label == target)
217}
218
219/// One reference point per term definition: the term's computed label, each
220/// alias's, then the labels the author wrote. The computed labels are counted
221/// as such ([`RefPoint::computed`]), so that the types [`LABEL_TYPES`] the
222/// point accepts apply to the written labels alone. The point's content is
223/// the term, and it is anchored on its first label: the label computed from
224/// the term, or, where the term is empty (and so computes no label), the
225/// first alias's label or the first written label.
226// One point, not one for the computed labels and one for the written ones: a
227// term definition carries one identifier in every output, so it has one anchor.
228impl Referenceable for DeftermElement {
229    fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
230        let mut labels = computed_labels(node);
231        let computed = labels.len();
232        let (written, mut malformed) = refs::point_labels(&refs::label_uses(node));
233        labels.extend(written);
234        // A malformed text's position counts every label of the point, the
235        // computed ones standing first.
236        for text in &mut malformed {
237            text.position += computed;
238        }
239        vec![RefPoint {
240            kind: RefKind::from(DEFINITION_KIND),
241            labels,
242            computed,
243            malformed,
244            anchor: AnchorPolicy::FromFirstLabel,
245            number: None,
246            content: Some(ContentRef::ArgumentNamed(TERM_ARG.to_string())),
247            accepts: AcceptedRefTypes::these(LABEL_TYPES),
248        }]
249    }
250}
251
252/// A term definition's fields, its `\label{…}` and `\aliasterm{…}`, are not
253/// part of its text: they label it.
254impl ApartFromText for DeftermElement {
255    fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
256        vec![ContentRef::ArgumentNamed(refs::FIELDS_ARG.to_string())]
257    }
258}
259
260static DEFTERM_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
261    Arc::new(
262        ElementSpec::new(DEFTERM)
263            .docs(
264                "The definition of a term (the `defterm` environment), the target of the term \
265                 links to that term.",
266            )
267            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
268            .with::<dyn Referenceable>(Arc::new(DeftermElement))
269            .with::<dyn ApartFromText>(Arc::new(DeftermElement))
270            .with_value(Arc::new(DeftermElement)),
271    )
272});
273
274/// The element value of every term definition node: the same value for
275/// every node, carrying [`DeftermElement`].
276pub fn defterm_element() -> Arc<ElementSpec> {
277    Arc::clone(&DEFTERM_ELEMENT)
278}
279
280/// The arguments of the `defterm` environment, in order: the term
281/// ([`TERM_ARG`]), then the tack-on argument (the trailing argument that
282/// absorbs field macros; [`ArgStdKind::TackOn`]) under the references
283/// feature's argument name ([`FIELDS_ARG`](refs::FIELDS_ARG)), holding the
284/// fields `\label{…}` (the references feature's declaration,
285/// [`label_field`](refs::label_field)) and `\aliasterm{…}`
286/// ([`ALIAS_FIELD`]), each repeatable.
287pub fn defterm_args() -> Vec<ArgDef> {
288    let alias = TackOnField::new(
289        ALIAS_FIELD,
290        vec![ArgDef::named(ALIAS_ARG, ArgStdKind::Mandatory).docs("The alias.").role(DEFINED_TERM_ARG_ROLE)],
291    )
292    .repeatable()
293    .docs("Declares another way of writing the term, by which term links find it too.");
294    let fields = ArgStdKind::TackOn { fields: vec![refs::label_field(), alias] };
295    vec![
296        ArgDef::named(TERM_ARG, ArgStdKind::Mandatory)
297            .docs("The term being defined.")
298            .role(DEFINED_TERM_ARG_ROLE),
299        ArgDef::named(refs::FIELDS_ARG, fields)
300            .docs(
301                "The `\\label{…}` and `\\aliasterm{…}` fields written after the term: they \
302                 label the term definition.",
303            ),
304    ]
305}
306
307// --- the term link ---------------------------------------------------------------------------
308
309/// The data of the element value of [`TERM`], and the aspects it
310/// implements: inline content, with one reference site ([`Referencing`]) and
311/// its bracket argument kept apart from its text ([`ApartFromText`]). See the
312/// [module documentation](self#the-term-link).
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub struct TermElement;
315
316/// The label under which the term link `node` finds its term definition: the
317/// label computed from the term in its bracket argument, or, where the
318/// bracket is absent or blank, from the term in its braces.
319///
320/// `None` for a node that is not a term link; for a term that is empty or
321/// only whitespace, which identifies no term; and for a term that holds a
322/// placeholder of a user definition's template that was not expanded (only a
323/// template kept rather than expanded holds one), whose term cannot be read.
324/// No reference site is declared then, and this function reports nothing.
325pub fn term_target(node: &NodeRef<'_, Flm>) -> Option<Label> {
326    let written = written_term(node)?;
327    if holds_placeholder(written.iter()) {
328        return None;
329    }
330    computed_label(spelling_identity(written.iter()))
331}
332
333/// The nodes in which the term link `node` writes the term it links to: its
334/// bracket argument, or its braces where the bracket is absent or blank.
335/// `None` for a node that is not a term link, or one that a parse recovery
336/// left without them. [`term_target`] reads these nodes, and the recomposed
337/// LaTeX looks in them for a template's placeholder, which leaves the term
338/// unknown until a call.
339pub(super) fn written_term<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeSlice<'t, Flm>> {
340    element_value::<TermElement>(node)?;
341    let named = |name: &str| node.argument_content_nodes_named(name).ok().flatten();
342    // A placeholder reads as no text through `spelling_identity` (the source
343    // recomposer re-emits nothing for it), so a bracket holding one is not
344    // blank: it names the term the template leaves open.
345    named(REF_ARG)
346        .filter(|content| holds_placeholder(content.iter()) || !spelling_identity(content.iter()).is_empty())
347        .or_else(|| named(SHOWN_ARG))
348}
349
350/// Whether the term link `node`, whose target is `target`, is inside the
351/// definition of that same term: whether a term definition enclosing it
352/// defines the term that `target` identifies, under its term or under an
353/// alias.
354///
355/// The answer is read from the structure of the tree: the nodes enclosing
356/// `node` in its own tree. A term link in content copied out of the document
357/// (the term that a reference to the term definition shows) has no enclosing
358/// term definition there. Every rule that writes a term link calls this
359/// function, so that every output agrees on the answer.
360pub fn in_own_definition(node: &NodeRef<'_, Flm>, target: &Label) -> bool {
361    let mut current = node.parent();
362    while let Some(ancestor) = current {
363        if defines(&ancestor, target) {
364            return true;
365        }
366        current = ancestor.parent();
367    }
368    false
369}
370
371/// The target of a term link, and whether the link is inside the definition
372/// of that term: the decision every rule that writes a term link takes,
373/// computed once per link by [`decide_term`].
374#[derive(Debug, Clone, PartialEq, Eq)]
375pub(super) struct TermDecision {
376    /// The label the link targets ([`term_target`]).
377    pub(super) target: Label,
378    /// Whether the link is inside the definition of that term
379    /// ([`in_own_definition`]).
380    pub(super) in_own_definition: bool,
381}
382
383/// The decision for the term link `node`: its target and whether it is
384/// inside its own term's definition; `None` where the link has no target
385/// ([`term_target`]).
386pub(super) fn decide_term(node: &NodeRef<'_, Flm>) -> Option<TermDecision> {
387    let target = term_target(node)?;
388    let in_own_definition = in_own_definition(node, &target);
389    Some(TermDecision { target, in_own_definition })
390}
391
392/// One reference site, whose target is [`term_target`], shown without any
393/// prefix word: what it shows is the text the author wrote. No site where
394/// the link has no target.
395impl Referencing for TermElement {
396    fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
397        term_target(node)
398            .map(|target| RefSite {
399                target,
400                display: RefDisplayOptions { variant: None, with_prefix: false },
401                shown: true,
402            })
403            .into_iter()
404            .collect()
405    }
406}
407
408/// The term a link gives in its bracket argument, [`REF_ARG`], is not part
409/// of the text around the link; the text it shows is, and stays part of it.
410impl ApartFromText for TermElement {
411    fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
412        vec![ContentRef::ArgumentNamed(REF_ARG.to_string())]
413    }
414}
415
416static TERM_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
417    Arc::new(
418        ElementSpec::new(TERM)
419            .docs("A link to the definition of a term, showing the text written for it.")
420            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
421            .with::<dyn Referencing>(Arc::new(TermElement))
422            .with::<dyn ApartFromText>(Arc::new(TermElement))
423            .with_value(Arc::new(TermElement)),
424    )
425});
426
427/// The element value of every term link node: the same value for every
428/// node, carrying [`TermElement`].
429pub fn term_element() -> Arc<ElementSpec> {
430    Arc::clone(&TERM_ELEMENT)
431}
432
433/// The arguments of `\term`, in order: the optional term linked to
434/// ([`REF_ARG`]), then the text shown ([`SHOWN_ARG`]).
435pub fn term_args() -> Vec<ArgDef> {
436    vec![
437        ArgDef::named(REF_ARG, ArgStdKind::Optional)
438            .docs("The term linked to, where it is not the text shown.")
439            .role(TARGET_ARG_ROLE),
440        ArgDef::named(SHOWN_ARG, ArgStdKind::Mandatory).docs("The text shown."),
441    ]
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    #[test]
449    fn the_two_elements_carry_their_aspects() {
450        assert!(defterm_element().has_aspect::<dyn Referenceable>());
451        assert!(defterm_element().has_aspect::<dyn ApartFromText>());
452        assert!(term_element().has_aspect::<dyn Referencing>());
453        assert!(term_element().has_aspect::<dyn ApartFromText>());
454        assert!(!ElementSpec::same_value(&defterm_element(), &term_element()));
455    }
456
457    #[test]
458    fn the_empty_identity_names_no_term() {
459        assert_eq!(computed_label(String::new()), None);
460        assert_eq!(
461            computed_label("entropy".to_string()),
462            Some(Label::new(COMPUTED_TYPE, "entropy"))
463        );
464    }
465}