Skip to main content

flm_core/stdlib/features/refpoints/
mod.rs

1//! This module defines the `refpoints` feature, which collects the reference
2//! points of a document in the table [`REFPOINTS`] (`flm.refpoints`).
3//!
4//! A *reference point* ([`RefPoint`]) is a place in a document that can be
5//! referred to, numbered, or given an anchor, such as a heading, an equation
6//! line, a theorem or a footnote. An element declares the reference points of
7//! each of its nodes through the [`Referenceable`] aspect. A node can have
8//! several reference points; for instance, a display-math environment has one
9//! reference point for each equation line. The concepts overview explains how
10//! reference points relate to labels and anchors ([Reference points, labels
11//! and anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).
12//!
13//! Several features work on the reference points of a document. The
14//! [`refs`](crate::stdlib::features::refs) feature collects the labels of the
15//! reference points and computes their anchors, the
16//! [`numbering`](crate::stdlib::features::numbering) feature numbers them,
17//! and the [`xnotes`](crate::stdlib::features::xnotes) feature finds the
18//! footnotes and other notes among them. These features read the reference
19//! points from the table [`REFPOINTS`] and do not call the [`Referenceable`]
20//! aspect themselves. Therefore the aspect is called only once for each node
21//! in a run, and content that an element builds for a reference point
22//! ([`ContentRef::Synthesized`]) is built only once and shared by all readers
23//! of the table.
24//!
25//! # What the feature registers
26//!
27//! The `refpoints` feature offers no command or environment. It registers the
28//! following items:
29//!
30//! - The table [`REFPOINTS`] (`flm.refpoints`), whose value is a
31//!   [`RefPoints`]. The table contains one [`RefPointRecord`] for each
32//!   reference point of the run. A reference point is identified by a
33//!   [`PointId`]: the address of its node and its index among the reference
34//!   points of that node.
35//! - The stage [`SCAN`] (`flm.refpoints.scan`), which writes this table. The
36//!   stage runs once for each tree. It uses the element index
37//!   ([`ELEMENT_INDEX`]) to find the nodes of the tree whose element carries
38//!   the [`Referenceable`] aspect, and records their reference points in tree
39//!   order: the root, then its descendants in preorder.
40//!
41//! A stage reads the table like any other table: it declares the read with
42//! [`Needs::reads`]`(REFPOINTS)` and obtains the table with [`StageCx::get`].
43//! A stage that runs once for the whole document and needs the reference
44//! points in document order calls [`RefPoints::in_document_order`].
45//!
46//! # Features that require the table
47//!
48//! The stages of the `refs`, `numbering` and `xnotes` features require the
49//! table [`REFPOINTS`]. A registry that contains one of these features must
50//! therefore also contain the `refpoints` feature. The `refpoints` feature in
51//! turn requires the element index, so the registry must also contain the
52//! [`index`](crate::stdlib::features::index) feature.
53//!
54//! A registry that lacks the `refpoints` feature still builds. However, every
55//! plan made from it fails with
56//! [`PlanError::NeedsUndeclared`](crate::core::plan::PlanError::NeedsUndeclared):
57//! a stage reads the table `flm.refpoints`, and this table is not declared in
58//! any feature. This holds even for a plan that does not schedule the stages
59//! that read the table, because the needs of every registered stage are
60//! resolved when a plan is made.
61//!
62//! # Synthesized values
63//!
64//! A [*synthesized value*](crate::guide::concepts_overview#synthesized-values)
65//! is a small tree that a stage builds during a run, outside the document's
66//! trees, for instance the text displayed for a reference. Before a stage
67//! renders a synthesized value, it calls [`StageCx::resolve_value`], which
68//! performs [value catch-up](crate::guide::concepts_overview#value-catch-up):
69//! the stages that run once for each tree and that the calling stage depends
70//! on run over the synthesized value. The stage [`SCAN`] is among these stages
71//! if the calling stage depends on it, directly or through other stages. The
72//! table [`REFPOINTS`] computed during the catch-up then contains only the
73//! reference points of the synthesized value.
74//!
75//! A synthesized value is not part of the document, so it may not define a
76//! label. If the table computed during the catch-up contains a reference
77//! point with a label, the catch-up fails with
78//! [`StoreError::DocumentFactInValue`](crate::core::data::store::StoreError::DocumentFactInValue).
79//! A synthesized value may contain reference points without a label.
80
81// A feature of its own, read by both consumers: content an aspect builds for a
82// point is built once and stored, where two stages asking the aspect would build
83// it twice. A collection in the element index would make the scan part of every
84// registry, and two aspects, one for what may be referenced and one for what may
85// be numbered, would have to agree on count and order by convention.
86
87use std::collections::BTreeMap;
88use std::sync::Arc;
89
90use techy::error::{Diagnostic, DiagnosticInfo};
91use techy::serialize::SerialValue;
92
93use crate::core::data::store::StageOut;
94use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
95use crate::core::plan::PlanCx;
96use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
97use crate::core::run::StageCx;
98use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
99use crate::lang::text::plain_text;
100use crate::lang::{nowhere, FlmOrigin, FlmSpan};
101use crate::model::addr::{NodeAddr, TreeId};
102use crate::model::aspects::{
103    AnchorPolicy, ContentRef, Label, NumberSource, PointId, RefPoint, Referenceable,
104};
105use crate::stdlib::features::index::ELEMENT_INDEX;
106
107/// The feature's registered name, `refpoints`.
108pub const FEATURE: &str = "refpoints";
109
110/// The name of the stage that writes the table of reference points
111/// [`REFPOINTS`], `flm.refpoints.scan`.
112pub const SCAN: &str = "flm.refpoints.scan";
113
114/// The name of the table of reference points, `flm.refpoints`, whose value is
115/// a [`RefPoints`]. To read the table in a stage, declare the read with
116/// [`Needs::reads`]`(REFPOINTS)`.
117pub const REFPOINTS: TableName<RefPoints> = TableName::new("flm.refpoints");
118
119/// A `RefPointRecord` is one entry of the table [`REFPOINTS`]. It contains a
120/// reference point as the [`Referenceable`] aspect of its node returned it,
121/// together with the identifier of the reference point and the span of the
122/// node.
123#[derive(Debug, Clone)]
124pub struct RefPointRecord {
125    /// The identifier of the reference point: the address of its node and the
126    /// index of the reference point among the reference points of that node.
127    pub id: PointId,
128    /// The reference point, as the [`Referenceable`] aspect of the node
129    /// returned it.
130    pub point: RefPoint,
131    /// The span of the node that has the reference point. The stages that
132    /// report a diagnostic about the reference point report it at this span.
133    pub span: FlmSpan,
134}
135
136impl RefPointRecord {
137    /// Returns the labels of this reference point and the texts that were
138    /// written as labels but are not of the form `type:label`, in one list.
139    ///
140    /// Each item contains the text of a label and the parsed label, or a
141    /// malformed text and `None`. The labels that the element computed come
142    /// first. The labels written in the document and the malformed texts
143    /// follow, in the order in which the document wrote them.
144    ///
145    /// A [`RefPoint`] stores its labels ([`RefPoint::labels`]) and its
146    /// malformed texts ([`RefPoint::malformed`]) in two separate lists. This
147    /// method merges the two lists by the
148    /// [position](crate::model::aspects::MalformedLabel::position) of each
149    /// malformed text. Call it when you need the order in which the document
150    /// mentions the labels. For instance, the safe labels stage of the `refs`
151    /// feature ([`SafeLabelsStage`](crate::stdlib::features::refs::SafeLabelsStage))
152    /// numbers the labels in this order.
153    pub fn mentions(&self) -> Vec<(String, Option<&Label>)> {
154        let point = &self.point;
155        let mut mentions = Vec::with_capacity(point.labels.len() + point.malformed.len());
156        let mut labels = point.labels.iter();
157        let mut malformed = point.malformed.iter().peekable();
158        loop {
159            let next_is_malformed =
160                malformed.peek().is_some_and(|one| one.position <= mentions.len());
161            if next_is_malformed {
162                let one = malformed.next().expect("peeked");
163                mentions.push((one.text.clone(), None));
164            } else if let Some(label) = labels.next() {
165                mentions.push((label.to_string(), Some(label)));
166            } else if let Some(one) = malformed.next() {
167                // A position past the end: nothing is dropped.
168                mentions.push((one.text.clone(), None));
169            } else {
170                return mentions;
171            }
172        }
173    }
174}
175
176/// A `RefPoints` is the value of the table [`REFPOINTS`] (`flm.refpoints`). It
177/// contains one [`RefPointRecord`] for each reference point of the trees of
178/// the run.
179///
180/// The table stores the records tree after tree, in the run's order of the
181/// trees ([`StageCx::trees`]). Within a tree, the records follow tree order:
182/// the root, then its descendants in preorder. The records of one node follow
183/// the order in which the [`Referenceable`] aspect of the node returned the
184/// reference points. [`RefPoints::records`] returns the records in this order,
185/// and [`RefPoints::in_document_order`] returns them in document order.
186///
187/// [`RefPoints::point`] returns the record of a reference point, given its
188/// identifier ([`PointId`]). [`RefPoints::of_tree`] returns the records of one
189/// tree.
190#[derive(Debug, Clone, Default)]
191pub struct RefPoints {
192    records: Vec<RefPointRecord>,
193    by_id: BTreeMap<PointId, usize>,
194}
195
196impl RefPoints {
197    /// Appends `record` after the records already in the table.
198    pub fn insert(&mut self, record: RefPointRecord) {
199        self.by_id.insert(record.id, self.records.len());
200        self.records.push(record);
201    }
202
203    /// Returns all records in the order in which the table stores them: tree
204    /// after tree, and within a tree in tree order (see [`RefPoints`]). To
205    /// obtain the records in document order, call
206    /// [`RefPoints::in_document_order`].
207    pub fn records(&self) -> &[RefPointRecord] {
208        &self.records
209    }
210
211    /// Returns all records in the document order of the run, which is the
212    /// order of [`StageCx::walk`].
213    ///
214    /// The records are sorted by the position of their node in the document
215    /// ([`StageCx::position`]). The records of one node keep the order in
216    /// which the [`Referenceable`] aspect of the node returned them. When a
217    /// tree is placed inside another tree, the records of the placed tree come
218    /// immediately after the records of the node at which the tree is placed.
219    /// Records whose node has no position in the document, such as the
220    /// reference points of a synthesized value, come first, in the order of
221    /// the table.
222    ///
223    /// A stage that runs once for the whole document calls this method when
224    /// it counts or orders the reference points. For instance, the
225    /// [`numbering`](crate::stdlib::features::numbering) feature numbers the
226    /// reference points in this order.
227    pub fn in_document_order<'t>(&'t self, cx: &StageCx<'_>) -> Vec<&'t RefPointRecord> {
228        // The table holds no place in the document, which a per-tree stage
229        // cannot know: the run's position of each node gives the order.
230        // Every node of a tree of the run has a position; only a synthesized
231        // value's records have none, and the stable sort keeps their order
232        // (first).
233        let mut records: Vec<&RefPointRecord> = self.records.iter().collect();
234        records.sort_by_key(|record| cx.position(record.id.addr));
235        records
236    }
237
238    /// Returns the records of the tree `tree`, in tree order. Returns no
239    /// records if the table contains no reference point of this tree.
240    pub fn of_tree(&self, tree: TreeId) -> impl Iterator<Item = &RefPointRecord> {
241        self.records.iter().filter(move |record| record.id.addr.tree == tree)
242    }
243
244    /// Returns the record of the reference point `id`, or `None` if the table
245    /// does not contain this reference point.
246    pub fn point(&self, id: PointId) -> Option<&RefPointRecord> {
247        self.by_id.get(&id).and_then(|index| self.records.get(*index))
248    }
249
250    /// Returns the number of records in the table.
251    pub fn len(&self) -> usize {
252        self.records.len()
253    }
254
255    /// Returns `true` if the table contains no record.
256    pub fn is_empty(&self) -> bool {
257        self.records.is_empty()
258    }
259}
260
261impl Table for RefPoints {
262    /// Appends the records of `piece` after the records of this table, in
263    /// their order.
264    fn absorb(&mut self, piece: RefPoints) {
265        for record in piece.records {
266            self.insert(record);
267        }
268    }
269
270    /// Serializes the table as a map with one entry for each reference point,
271    /// in the order of the table.
272    ///
273    /// The key of an entry has the form `<node>#<index>`: the node as
274    /// [`ProjectCx::node_ref`] writes it, and the index of the reference point
275    /// among the reference points of the node. The value of an entry is a map
276    /// with the following entries:
277    ///
278    /// - `kind`: the reference kind, such as `section`.
279    /// - `labels`: the list of the labels.
280    /// - `malformed`: the list of the texts written as labels that are not of
281    ///   the form `type:label`. This entry is present only if the reference
282    ///   point has such a text.
283    /// - `anchor`: the anchor policy as a short text, such as `auto:sec` or
284    ///   `from-first-label`.
285    /// - `display`: a map with the entries `number` and `content`. `number` is
286    ///   the number source, with the entries `counter`, `style` and `advance`,
287    ///   and with `instances` and `number_format` where the number source has
288    ///   them. `content` is the content that a reference to the reference
289    ///   point displays when the reference point has no number. Each of the
290    ///   two entries is present only if the reference point has it.
291    ///
292    /// The content is written as a short text that refers to a part of the
293    /// node, such as `argument 1` or `body`. Content that the element built as
294    /// a tree ([`ContentRef::Synthesized`]) is written as the plain text of
295    /// that tree.
296    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
297        SerialValue::Map(
298            self.records
299                .iter()
300                .map(|record| {
301                    let point = &record.point;
302                    let tree = record.id.addr.tree;
303                    let labels = point
304                        .labels
305                        .iter()
306                        .map(|label| SerialValue::Str(label.to_string()))
307                        .collect();
308                    let mut entries = vec![
309                        ("kind".to_string(), SerialValue::Str(point.kind.to_string())),
310                        ("labels".to_string(), SerialValue::List(labels)),
311                    ];
312                    if !point.malformed.is_empty() {
313                        let malformed = point
314                            .malformed
315                            .iter()
316                            .map(|one| SerialValue::Str(one.text.clone()))
317                            .collect();
318                        entries.push(("malformed".to_string(), SerialValue::List(malformed)));
319                    }
320                    entries.push((
321                        "anchor".to_string(),
322                        SerialValue::Str(policy_text(cx, tree, &point.anchor)),
323                    ));
324                    let mut display = Vec::with_capacity(2);
325                    if let Some(number) = &point.number {
326                        display.push(("number".to_string(), project_number(cx, Some(tree), number)));
327                    }
328                    if let Some(content) = &point.content {
329                        display.push((
330                            "content".to_string(),
331                            SerialValue::Str(content_text(cx, tree, content)),
332                        ));
333                    }
334                    entries.push(("display".to_string(), SerialValue::Map(display)));
335                    (point_key(cx, record.id), SerialValue::Map(entries))
336                })
337                .collect(),
338        )
339    }
340
341    /// Returns [`PieceClass::DocumentFact`] for a table piece that contains a
342    /// reference point with a label, [`PieceClass::NodeKeyed`] for a table
343    /// piece whose reference points have no label, and [`PieceClass::Empty`]
344    /// for an empty table piece.
345    ///
346    /// A label is a fact about the document, because other places of the
347    /// document refer to it. A synthesized value may therefore not contain a
348    /// reference point with a label (see [Synthesized
349    /// values](crate::stdlib::features::refpoints#synthesized-values)).
350    fn piece_class(&self) -> PieceClass {
351        if self.records.is_empty() {
352            PieceClass::Empty
353        } else if self.records.iter().any(|record| !record.point.labels.is_empty()) {
354            PieceClass::DocumentFact
355        } else {
356            PieceClass::NodeKeyed
357        }
358    }
359}
360
361impl SingletonTable for RefPoints {
362    const NAME: &'static str = "flm.refpoints";
363}
364
365/// Returns the text that [`ProjectCx::node_ref`] writes for the node at
366/// `addr`. The projections of the tables about reference points use this text
367/// in map keys and in texts. If `node_ref` writes a value that is not a
368/// string, this function returns the debug form of the value.
369pub(crate) fn node_key(cx: &dyn ProjectCx, addr: NodeAddr) -> String {
370    match cx.node_ref(addr) {
371        SerialValue::Str(text) => text,
372        other => format!("{other:?}"),
373    }
374}
375
376/// Returns the key of the reference point `id` in a projection, of the form
377/// `<node>#<index>`. `<node>` is the text that [`node_key`] returns for the
378/// node, and `<index>` is the index of the reference point among the reference
379/// points of the node.
380pub(crate) fn point_key(cx: &dyn ProjectCx, id: PointId) -> String {
381    format!("{}#{}", node_key(cx, id.addr), id.index)
382}
383
384/// Serializes the number source `number` of a reference point as a map with
385/// the entries `counter`, `instances`, `style`, `advance` and
386/// `number_format`.
387///
388/// The entry `instances` lists the scoped instances of the counter in which
389/// the reference point is counted. It is present only if there are such
390/// instances and `tree` is given. The entry `number_format` is present only
391/// if the reference point has a number template of its own.
392///
393/// `tree` is the tree of the node that has the reference point. The scoped
394/// instances are nodes of this tree.
395pub(crate) fn project_number(
396    cx: &dyn ProjectCx,
397    tree: Option<TreeId>,
398    number: &NumberSource,
399) -> SerialValue {
400    let advance = number.advance.iter().map(|level| SerialValue::Int(i64::from(*level))).collect();
401    let mut source = vec![("counter".to_string(), SerialValue::Str(number.counter.to_string()))];
402    if let (Some(tree), false) = (tree, number.instances.is_empty()) {
403        let instances =
404            number.instances.iter().map(|node| cx.node_ref(NodeAddr::new(tree, *node))).collect();
405        source.push(("instances".to_string(), SerialValue::List(instances)));
406    }
407    source.push(("style".to_string(), SerialValue::Str(number.style.to_string())));
408    source.push(("advance".to_string(), SerialValue::List(advance)));
409    if let Some(format) = &number.number_format {
410        source.push(("number_format".to_string(), SerialValue::Str(format.clone())));
411    }
412    SerialValue::Map(source)
413}
414
415/// Returns the anchor policy `policy` as a short text for a projection, such
416/// as `auto:sec` or `from-first-label`. `tree` is the tree of the node that
417/// has the reference point; [`content_text`] uses it to write the content of
418/// an [`AnchorPolicy::Slug`] policy.
419pub(crate) fn policy_text(cx: &dyn ProjectCx, tree: TreeId, policy: &AnchorPolicy) -> String {
420    match policy {
421        AnchorPolicy::Explicit(id) => format!("explicit:{id}"),
422        AnchorPolicy::FromFirstLabel => "from-first-label".to_string(),
423        AnchorPolicy::Slug { prefix, content } => {
424            format!("slug:{prefix}:{}", content_text(cx, tree, content))
425        }
426        AnchorPolicy::FromValue { prefix } => format!("from-value:{prefix}"),
427        AnchorPolicy::Auto { prefix } => format!("auto:{prefix}"),
428    }
429}
430
431/// Returns the content reference `content` as a short text for a projection.
432///
433/// A reference to a part of a node is written as a short description of that
434/// part, such as `argument 1` or `body`. Content that the element built as a
435/// tree ([`ContentRef::Synthesized`]) is written as the plain text of that
436/// tree. `tree` is the tree of the node that has the reference point; it is
437/// needed to write a [`ContentRef::Node`] reference.
438pub(crate) fn content_text(cx: &dyn ProjectCx, tree: TreeId, content: &ContentRef) -> String {
439    match content {
440        ContentRef::Argument(index) => format!("argument {index}"),
441        ContentRef::ArgumentNamed(name) => format!("argument {name}"),
442        ContentRef::Body => "body".to_string(),
443        ContentRef::Node(id) => format!("node {}", node_key(cx, NodeAddr::new(tree, *id))),
444        ContentRef::Synthesized(value) => plain_text(value),
445    }
446}
447
448/// The error that is reported when the stage [`SCAN`] cannot read the element
449/// index or cannot write the table of reference points (id
450/// `flm.refpoints.stage-failed`).
451///
452/// A document cannot cause this error: it is caused by a fault of the
453/// program. Reported at no position in the document. The stage then writes no
454/// reference points for the tree, so the table [`REFPOINTS`] contains no
455/// reference point of that tree.
456#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
457#[diagnostic(
458    id = "flm.refpoints.stage-failed",
459    message = "Stage ‘flm.refpoints.scan’ failed: {detail}"
460)]
461pub struct StageFailed {
462    /// The error that the stage received when it accessed the table, as text.
463    pub detail: String,
464}
465
466/// Converts the index of a reference point among the reference points of its
467/// node to the type of [`PointId::index`]. An index above `u32::MAX` becomes
468/// `u32::MAX`; a document cannot produce a node with that many reference
469/// points.
470fn point_index(index: usize) -> u32 {
471    u32::try_from(index).unwrap_or(u32::MAX)
472}
473
474/// The stage [`SCAN`] (`flm.refpoints.scan`), which writes the table
475/// [`REFPOINTS`]. The stage runs once for each tree. It uses the element index
476/// ([`ELEMENT_INDEX`]) to find the nodes of the tree whose element carries the
477/// [`Referenceable`] aspect, calls the aspect once for each of these nodes,
478/// and records the returned reference points in tree order.
479struct Scan;
480
481impl Stage for Scan {
482    fn decl(&self) -> StageDecl {
483        StageDecl::new(SCAN, Effect::Compute, Scope::PerTree).writes(REFPOINTS).docs(
484            "Records in `flm.refpoints` the reference points of each node of the tree whose \
485             element carries the `Referenceable` aspect, in tree order.",
486        )
487    }
488
489    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
490        Needs::new().reads(ELEMENT_INDEX)
491    }
492
493    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
494        let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
495        let failed = |out: &mut StageOut<'_>, detail: String| {
496            out.diags.push(Diagnostic::error(StageFailed { detail }, nowhere(FlmOrigin::none())));
497        };
498        let index = match cx.get(ELEMENT_INDEX) {
499            Ok(Some(index)) => index,
500            Ok(None) => return,
501            Err(error) => return failed(out, error.to_string()),
502        };
503        let mut points = RefPoints::default();
504        for (addr, node, referenceable) in
505            index.nodes_with::<dyn Referenceable>(cx.registry(), id, &tree)
506        {
507            for (index, point) in referenceable.points(&node).into_iter().enumerate() {
508                points.insert(RefPointRecord {
509                    id: PointId { addr, index: point_index(index) },
510                    point,
511                    span: node.span().clone(),
512                });
513            }
514        }
515        match out.table(REFPOINTS) {
516            Ok(table) => *table = points,
517            Err(error) => failed(out, error.to_string()),
518        }
519    }
520}
521
522/// The `refpoints` feature, which registers the table [`REFPOINTS`] and the
523/// stage [`SCAN`] that writes this table. The [module
524/// documentation](crate::stdlib::features::refpoints) describes the table and
525/// the features that read it.
526///
527/// The stage [`SCAN`] reads the element index, so a registry that contains the
528/// `refpoints` feature must also contain the
529/// [`index`](crate::stdlib::features::index) feature.
530#[derive(Debug, Default, Clone, Copy)]
531pub struct Refpoints;
532
533impl FlmFeature for Refpoints {
534    fn info(&self) -> FeatureInfo {
535        FeatureInfo::new(FEATURE, "Reference points").docs(
536            "The table of reference points (table `flm.refpoints`), which lists the places of \
537             the document that can be referred to, numbered or given an anchor, such as \
538             headings and equation lines. The `refs`, `numbering` and `xnotes` features read \
539             this table.",
540        )
541    }
542
543    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
544        b.table(
545            REFPOINTS,
546            "For each tree, the reference points that the `Referenceable` aspect returns for \
547             the nodes of the tree, in tree order, each with the identifier of the reference \
548             point.",
549        )?;
550        b.stage(Arc::new(Scan))?;
551        Ok(())
552    }
553}
554
555/// Returns the [`Refpoints`] feature as a shared feature object, for instance
556/// to list it in a [`PackageEntry`](crate::core::registry::PackageEntry).
557pub fn feature() -> Arc<dyn FlmFeature> {
558    Arc::new(Refpoints)
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564    use crate::lang::{LangInputs, ParseOptions, build_language, parse_fragment};
565    use crate::model::aspects::{AcceptedRefTypes, MalformedLabel};
566    use crate::model::doc::FragmentLayout;
567    use crate::model::names::RefKind;
568    use techy::core::node::NodeId;
569    use techy::source::{Source, SourceSpan};
570
571    /// The root's id of a parse under the bare language: a point needs a node
572    /// address, and node ids come from trees only.
573    fn root_id() -> NodeId {
574        let lang = build_language(LangInputs::new());
575        let source = Arc::new(Source::new("x").with_origin(FlmOrigin::none()));
576        let fragment =
577            parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
578                .expect("a parse of `x`");
579        fragment.tree().root().id()
580    }
581
582    fn span() -> FlmSpan {
583        let source = Arc::new(Source::new("").with_origin(FlmOrigin::none()));
584        SourceSpan::new(&source, 0..0)
585    }
586
587    /// A point of the root node at the given point index.
588    fn record(root: NodeId, index: u32, labels: &[&str]) -> RefPointRecord {
589        RefPointRecord {
590            id: PointId { addr: NodeAddr::new(TreeId::tree(0), root), index },
591            point: RefPoint {
592                kind: RefKind::from("section"),
593                labels: labels.iter().map(|l| Label::parse(l).unwrap()).collect(),
594                malformed: Vec::new(),
595                computed: 0,
596                anchor: AnchorPolicy::Auto { prefix: "sec".to_string() },
597                number: None,
598                content: None,
599                accepts: AcceptedRefTypes::Any,
600            },
601            span: span(),
602        }
603    }
604
605    #[test]
606    fn the_table_keeps_the_points_in_order_and_finds_one_by_identity() {
607        let root = root_id();
608        let mut points = RefPoints::default();
609        points.insert(record(root, 0, &["sec:a"]));
610        points.insert(record(root, 1, &[]));
611        assert_eq!(points.len(), 2);
612        assert_eq!(points.records()[1].id.index, 1);
613        let second = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 1 };
614        assert!(points.point(second).is_some_and(|record| record.point.labels.is_empty()));
615        assert_eq!(points.of_tree(TreeId::tree(0)).count(), 2);
616        assert_eq!(points.of_tree(TreeId::tree(1)).count(), 0);
617    }
618
619    #[test]
620    fn a_piece_holding_a_label_states_a_document_fact() {
621        let root = root_id();
622        let mut unlabeled = RefPoints::default();
623        unlabeled.insert(record(root, 0, &[]));
624        assert_eq!(unlabeled.piece_class(), PieceClass::NodeKeyed);
625        let mut labeled = RefPoints::default();
626        labeled.insert(record(root, 0, &["sec:a"]));
627        assert_eq!(labeled.piece_class(), PieceClass::DocumentFact);
628    }
629
630    #[test]
631    fn a_points_mentions_come_back_in_the_order_the_document_wrote_them() {
632        // The point keeps the parsed labels and the texts that are no label in
633        // two lists; `mentions` puts them back in the written order, which is
634        // what decides the key a recomposed output allocates for each.
635        let root = root_id();
636        let malformed = |text: &str, position: usize| MalformedLabel {
637            text: text.to_string(),
638            span: span(),
639            position,
640        };
641        let written = |point: &RefPointRecord| {
642            point.mentions().into_iter().map(|(text, _)| text).collect::<Vec<_>>()
643        };
644
645        // `\label{bad}` before `\label{sec:a}`.
646        let mut first = record(root, 1, &["sec:a"]);
647        first.point.malformed = vec![malformed("bad", 0)];
648        assert_eq!(written(&first), ["bad", "sec:a"]);
649        assert_eq!(first.mentions()[1].1.map(Label::to_string), Some("sec:a".to_string()));
650        assert_eq!(first.mentions()[0].1, None);
651
652        // `\label{sec:a}` before `\label{bad}`: a trailing text, whose
653        // position is the end of the list.
654        let mut last = record(root, 2, &["sec:a"]);
655        last.point.malformed = vec![malformed("bad", 1)];
656        assert_eq!(written(&last), ["sec:a", "bad"]);
657
658        // Interleaved, and a point with no text that is no label.
659        let mut mixed = record(root, 3, &["sec:a", "sec:b"]);
660        mixed.point.malformed = vec![malformed("one", 1), malformed("two", 3)];
661        assert_eq!(written(&mixed), ["sec:a", "one", "sec:b", "two"]);
662        assert_eq!(written(&record(root, 4, &["sec:a"])), ["sec:a"]);
663    }
664
665    #[test]
666    fn the_projection_shows_a_text_that_is_no_label_under_a_key_of_its_own() {
667        // A tool reading the dump must never find, in a point's `labels`, a
668        // text that appears in no index and resolves nowhere.
669        struct NoCx;
670        impl ProjectCx for NoCx {
671            fn node_ref(&self, _: NodeAddr) -> SerialValue {
672                SerialValue::Null
673            }
674            fn tree_ref(&self, _: TreeId) -> SerialValue {
675                SerialValue::Null
676            }
677        }
678        let keys = |points: &RefPoints| {
679            let SerialValue::Map(points) = points.project(&NoCx) else { panic!("a map") };
680            let (_, point) = points.into_iter().next().expect("one point");
681            let SerialValue::Map(point) = point else { panic!("a map") };
682            point
683        };
684
685        let root = root_id();
686        let mut plain = RefPoints::default();
687        plain.insert(record(root, 1, &["sec:a"]));
688        let entries = keys(&plain);
689        assert!(entries.iter().all(|(key, _)| key != "malformed"), "{entries:?}");
690
691        let mut with_text = RefPoints::default();
692        let mut point = record(root, 1, &["sec:a"]);
693        point.point.malformed =
694            vec![MalformedLabel { text: "bad".to_string(), span: span(), position: 0 }];
695        with_text.insert(point);
696        let entries = keys(&with_text);
697        let labels = entries.iter().find(|(key, _)| key == "labels").expect("the labels");
698        assert_eq!(labels.1, SerialValue::List(vec![SerialValue::Str("sec:a".to_string())]));
699        let malformed =
700            entries.iter().find(|(key, _)| key == "malformed").expect("the malformed texts");
701        assert_eq!(malformed.1, SerialValue::List(vec![SerialValue::Str("bad".to_string())]));
702    }
703
704    #[test]
705    fn the_scan_is_per_tree_and_writes_the_table() {
706        let decl = Scan.decl();
707        assert_eq!(decl.name, SCAN);
708        assert_eq!(decl.effect, Effect::Compute);
709        assert_eq!(decl.scope, Scope::PerTree);
710        assert_eq!(decl.writes[0].name, REFPOINTS.name());
711        assert_eq!(RefPoints::NAME, REFPOINTS.name());
712        assert_eq!(Refpoints.info().name, FEATURE);
713    }
714
715    #[test]
716    fn an_empty_table_is_an_empty_piece() {
717        assert_eq!(RefPoints::default().piece_class(), PieceClass::Empty);
718        assert!(RefPoints::default().is_empty());
719    }
720}