flm_core/stdlib/features/refs/tables.rs
1//! The tables of the [`refs`](super) feature. A table is typed data that one
2//! stage writes beside the frozen trees and other stages read
3//! ([`Table`]); each of these is identified by its dotted name:
4//!
5//! - [`LABELS`] (`flm.labels`, a [`Labels`]): for every label, the reference
6//! point that keeps it; the labels written more than once; and the labels
7//! refused because their point does not accept their type. The label scan
8//! writes it, from the reference points that the
9//! [`refpoints`](crate::stdlib::features::refpoints) feature recorded.
10//! - [`ANCHORS`] (`flm.anchors`, an [`Anchors`]): the anchor of every
11//! reference point, or none. The anchors stage writes it.
12//! - [`REF_TARGETS`] (`flm.refs.targets`, a [`RefTargets`]): for every label
13//! whose point received an anchor, the point that keeps it, its link target
14//! and what a reference to it
15//! shows. The anchors stage writes it, and the resolve stage reads it.
16//! - [`REF_RESOLUTIONS`] (`flm.refs.resolutions`, a [`RefResolutions`]): the
17//! [`Resolution`] of every reference site. The resolve stage writes it, and
18//! the lowering rules of `\ref` and `\hyperref` read it.
19//! - [`EXTERNAL_INDEX`] (`flm.refs.external-index`, an [`ExternalIndex`]):
20//! labels of *other* documents. It is an external table, a table that no
21//! stage of the run writes: the caller installs its value when the run is
22//! constructed ([`Externals`](crate::core::run::Externals)), and the resolve
23//! stage reads it when the caller has installed it.
24//!
25//! Every table iterates in an order fixed by its content (a map in key
26//! order, a list in document order), so no hash-map order can reach a
27//! projection, a diagnostic or a golden file. In a projection, a node address
28//! is written by the projection context (`elem@line:col`), a point or a site
29//! as `<node>#<index>`, and content held as a synthesized value as its plain
30//! text, which keeps a projection readable.
31
32use std::collections::BTreeMap;
33use std::sync::Arc;
34
35use techy::core::node::NodeTree;
36use techy::serialize::SerialValue;
37
38use crate::model::addr::{NodeAddr, TreeId};
39use crate::model::aspects::{Label, NumberSource, PointId};
40use crate::model::names::RefKind;
41use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
42use crate::lang::{Flm, FlmSpan};
43use crate::stdlib::features::refpoints::{RefPointRecord, node_key, point_key, project_number};
44
45use crate::lang::text::plain_text;
46
47/// The typed name of the label table, `flm.labels`, a [`Labels`], which the
48/// label scan ([`SCAN`](super::SCAN)) writes.
49pub const LABELS: TableName<Labels> = TableName::new("flm.labels");
50
51/// The typed name of the anchors table, `flm.anchors`, an [`Anchors`], which
52/// the anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) writes.
53///
54/// An anchor is the identifier a link points at for a reference point:
55/// `<type>-<label>` from the first label the point keeps (for a point whose
56/// element asks for its label, or a labeled point whose element asks for its
57/// position), `<prefix>--<title>` for an unlabeled heading,
58/// `<prefix>-<numbers>` for a point identified by its number, labeled or not,
59/// an
60/// identifier derived from the position otherwise
61/// (`<prefix>--<position><four letters>`), or an identifier its element gives
62/// itself. The anchors stage of the `refs` feature computes it once for every
63/// point, and the backends write it as the link target (on HTML, the `id` of
64/// the element and the `href` of a link after a `#`). See the [module
65/// documentation of the feature](super#anchors) for the rules and
66/// [`encode_anchor`](super::encode_anchor) for the encoding.
67pub const ANCHORS: TableName<Anchors> = TableName::new("flm.anchors");
68
69/// The typed name of the targets table, `flm.refs.targets`, a
70/// [`RefTargets`], which the anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) writes and the
71/// resolve stage ([`RESOLVE`](super::RESOLVE)) reads.
72pub const REF_TARGETS: TableName<RefTargets> = TableName::new("flm.refs.targets");
73
74/// The typed name of the resolutions table, `flm.refs.resolutions`, a
75/// [`RefResolutions`], which the resolve stage ([`RESOLVE`](super::RESOLVE)) writes and the
76/// lowering rules
77/// of references read.
78pub const REF_RESOLUTIONS: TableName<RefResolutions> = TableName::new("flm.refs.resolutions");
79
80/// The typed name of the external index, `flm.refs.external-index`, an
81/// [`ExternalIndex`]: an external table, whose value the caller installs when
82/// it constructs the run ([`Externals`](crate::core::run::Externals)), and
83/// which no stage writes.
84pub const EXTERNAL_INDEX: TableName<ExternalIndex> = TableName::new("flm.refs.external-index");
85
86/// The identity of one reference site: the address of the node that declares
87/// it and the site's index among that node's sites.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
89pub struct SiteId {
90 /// The address of the node that declares the site.
91 pub addr: NodeAddr,
92 /// The site's index among the node's sites, in the order the node's
93 /// [`Referencing`](crate::model::aspects::Referencing) aspect returns
94 /// them.
95 pub index: u32,
96}
97
98/// The two things a reference to a point may show, as the anchors stage
99/// ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) records them: the number source
100/// and the content that the
101/// [`RefPoint`](crate::model::aspects::RefPoint) states, with the content
102/// copied out of the document.
103///
104/// A reference shows the first of them that exists: the point's number,
105/// formatted where the reference is written, where the numbering feature
106/// numbered the point; else the content; else the label the reference was
107/// written with, as written. Whether the point was numbered is not recorded
108/// here, because the numbering stage decides it for each run (a point that
109/// states a number source is numbered wherever it can be); this holds the
110/// number *source*, the counter and the counter style, and never a formatted
111/// number.
112///
113/// The content is stored as a [synthesized
114/// value](crate::guide::concepts_overview#synthesized-values), a small tree
115/// held in the table, which the `\ref` rule brings up to date and splices into
116/// the lowered tree.
117#[derive(Debug, Clone, Default)]
118pub struct PointDisplay {
119 /// The point's number source (the counter and the counter style it is
120 /// numbered by), where it can be numbered at all.
121 pub number: Option<NumberSource>,
122 /// The content the point shows where it has no number, as a synthesized
123 /// value.
124 pub content: Option<Arc<NodeTree<Flm>>>,
125}
126
127impl PointDisplay {
128 /// Projects the display as `{number?: {counter, instances?, style,
129 /// advance, number_format?}, content?: <plain text>}`. Each key is present
130 /// only where the point states that thing: a point that can show nothing
131 /// of its own projects as an empty map, a number source counted within no
132 /// scoped instance has no `instances`, and one without a number template
133 /// of its own has no `number_format`.
134 ///
135 /// `tree` is the tree of the node that carries the point, in which the
136 /// instances (nodes of that tree) are rendered; a point of no tree of this
137 /// run projects no instances.
138 fn project(&self, cx: &dyn ProjectCx, tree: Option<TreeId>) -> SerialValue {
139 let mut entries = Vec::with_capacity(2);
140 if let Some(number) = &self.number {
141 entries.push(("number".to_string(), project_number(cx, tree, number)));
142 }
143 if let Some(content) = &self.content {
144 entries.push(("content".to_string(), SerialValue::Str(plain_text(content))));
145 }
146 SerialValue::Map(entries)
147 }
148}
149
150/// A label written for two reference points, as [`Labels`] records it. The
151/// label scan ([`SCAN`](super::SCAN)) records the fact; the label check
152/// ([`CHECK_LABELS`](super::CHECK_LABELS)) reports it as
153/// `flm.refs.duplicate-label`.
154#[derive(Debug, Clone)]
155pub struct DuplicateLabel {
156 /// The label.
157 pub label: Label,
158 /// The point that keeps the label (the first in document order).
159 pub first: PointId,
160 /// The later point that also wrote it.
161 pub second: PointId,
162 /// The span of the later point's node.
163 pub span: FlmSpan,
164}
165
166/// A label whose type the point it was written for does not accept, as
167/// [`Labels`] records it. The label scan ([`SCAN`](super::SCAN)) records the fact;
168/// the label check ([`CHECK_LABELS`](super::CHECK_LABELS)) reports it as
169/// `flm.refs.label-type-not-accepted`.
170///
171/// A refused label defines nothing: no reference resolves to the point through
172/// it, and a point whose every label was refused gets no anchor.
173#[derive(Debug, Clone)]
174pub struct RefusedLabel {
175 /// The label as written.
176 pub label: Label,
177 /// The point it was written for.
178 pub point: PointId,
179 /// That point's reference kind (`section`), which says what sort of place
180 /// the label was written on.
181 pub kind: RefKind,
182 /// The label types the point does accept, in the order it declares them.
183 pub accepted: Vec<String>,
184 /// The span of the point's node.
185 pub span: FlmSpan,
186}
187
188/// The label table, `flm.labels` ([`LABELS`]): for every label, the first
189/// point that wrote it; the labels written more than once; and the labels
190/// refused because the point they were written for does not accept their
191/// type.
192///
193/// The points themselves (their kinds, their labels as written, their anchor
194/// policies) are held in the table of the
195/// [`refpoints`](crate::stdlib::features::refpoints) feature,
196/// [`REFPOINTS`](crate::stdlib::features::refpoints::REFPOINTS), which the
197/// label scan ([`SCAN`](super::SCAN)) reads; this table holds what the labels make of them.
198#[derive(Debug, Clone, Default)]
199pub struct Labels {
200 /// From a label to the point that keeps it.
201 pub by_label: BTreeMap<Label, PointId>,
202 /// The labels written more than once, in document order of the later
203 /// point.
204 pub duplicates: Vec<DuplicateLabel>,
205 /// The labels whose type the point they were written for does not accept,
206 /// in document order of that point.
207 pub refused: Vec<RefusedLabel>,
208}
209
210impl Labels {
211 /// Records the labels of a point: each label joins the index unless it is
212 /// a written label whose type the point does not accept (a refusal is
213 /// then recorded; the point's
214 /// [computed](crate::model::aspects::RefPoint::computed) labels are not
215 /// checked) or an earlier point already keeps it (a duplicate is then
216 /// recorded). The label scan records the points in document order, so
217 /// that the first point to write a label keeps it.
218 pub fn insert(&mut self, record: &RefPointRecord) {
219 let point = &record.point;
220 for (at, label) in point.labels.iter().enumerate() {
221 if at >= point.computed && !point.accepts.accepts(&label.ref_type) {
222 self.refused.push(RefusedLabel {
223 label: label.clone(),
224 point: record.id,
225 kind: point.kind.clone(),
226 accepted: point.accepts.listed().unwrap_or(&[]).to_vec(),
227 span: record.span.clone(),
228 });
229 continue;
230 }
231 match self.by_label.get(label) {
232 Some(first) if *first == record.id => {}
233 Some(first) => self.duplicates.push(DuplicateLabel {
234 label: label.clone(),
235 first: *first,
236 second: record.id,
237 span: record.span.clone(),
238 }),
239 None => {
240 self.by_label.insert(label.clone(), record.id);
241 }
242 }
243 }
244 }
245}
246
247impl Table for Labels {
248 /// The label scan runs once for the document and writes one table piece;
249 /// a table piece absorbed after another keeps the labels of the earlier
250 /// one, as a later point would.
251 fn absorb(&mut self, piece: Labels) {
252 for (label, point) in piece.by_label {
253 self.by_label.entry(label).or_insert(point);
254 }
255 self.duplicates.extend(piece.duplicates);
256 self.refused.extend(piece.refused);
257 }
258
259 /// Projects the table as `{labels: {<label>: <point>}, duplicates: […],
260 /// refused: […]}`.
261 fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
262 let labels = self
263 .by_label
264 .iter()
265 .map(|(label, id)| (label.to_string(), SerialValue::Str(point_key(cx, *id))))
266 .collect();
267 let duplicates = self
268 .duplicates
269 .iter()
270 .map(|dup| {
271 SerialValue::Map(vec![
272 ("label".to_string(), SerialValue::Str(dup.label.to_string())),
273 ("first".to_string(), SerialValue::Str(point_key(cx, dup.first))),
274 ("second".to_string(), SerialValue::Str(point_key(cx, dup.second))),
275 ])
276 })
277 .collect();
278 let refused = self
279 .refused
280 .iter()
281 .map(|refusal| {
282 let accepted = refusal
283 .accepted
284 .iter()
285 .map(|one| SerialValue::Str(one.clone()))
286 .collect();
287 SerialValue::Map(vec![
288 ("label".to_string(), SerialValue::Str(refusal.label.to_string())),
289 ("point".to_string(), SerialValue::Str(point_key(cx, refusal.point))),
290 ("kind".to_string(), SerialValue::Str(refusal.kind.to_string())),
291 ("accepted".to_string(), SerialValue::List(accepted)),
292 ])
293 })
294 .collect();
295 SerialValue::Map(vec![
296 ("labels".to_string(), SerialValue::Map(labels)),
297 ("duplicates".to_string(), SerialValue::List(duplicates)),
298 ("refused".to_string(), SerialValue::List(refused)),
299 ])
300 }
301
302 /// A label states a fact about the document, which a [synthesized
303 /// value](crate::guide::concepts_overview#synthesized-values) (a small
304 /// tree a stage builds during a run) may never state.
305 fn piece_class(&self) -> PieceClass {
306 if self.by_label.is_empty() && self.duplicates.is_empty() && self.refused.is_empty() {
307 PieceClass::Empty
308 } else {
309 PieceClass::DocumentFact
310 }
311 }
312}
313
314impl SingletonTable for Labels {
315 const NAME: &'static str = "flm.labels";
316}
317
318/// The anchors table, `flm.anchors` ([`ANCHORS`]): every reference point of
319/// the document with the anchor the anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE))
320/// computed for it, or no
321/// anchor when the point has nothing to form one from (no label it keeps,
322/// under a policy that needs one) or when an earlier point already holds the
323/// same one.
324///
325/// A point that the table does not hold at all is a point the stage never
326/// saw, which is a different case: a consumer that finds one is reading data
327/// that was never computed for the content it is looking at, and reports it
328/// as such rather than treating the point as one without an anchor.
329/// [`Anchors::lookup`] tells the two cases apart.
330#[derive(Debug, Clone, Default)]
331pub struct Anchors {
332 /// From a point to its anchor; `None` for a point that received none.
333 pub ids: BTreeMap<PointId, Option<String>>,
334}
335
336impl Anchors {
337 /// The anchor of a point: `None` both for a point the stage never saw and
338 /// for one that received no anchor. A consumer that must tell the two
339 /// apart calls [`Anchors::lookup`].
340 pub fn id(&self, point: PointId) -> Option<&str> {
341 self.ids.get(&point).and_then(|id| id.as_deref())
342 }
343
344 /// What the table holds for a point: `None` when the stage never saw the
345 /// point, `Some(None)` when it saw it and gave it no anchor (no label to
346 /// form it from, or a collision with an earlier point), and
347 /// `Some(Some(id))` when it gave it the anchor `id`.
348 pub fn lookup(&self, point: PointId) -> Option<Option<&str>> {
349 self.ids.get(&point).map(|id| id.as_deref())
350 }
351}
352
353impl Table for Anchors {
354 fn absorb(&mut self, piece: Anchors) {
355 self.ids.extend(piece.ids);
356 }
357
358 fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
359 SerialValue::Map(
360 self.ids
361 .iter()
362 .map(|(id, anchor)| {
363 let value = match anchor {
364 Some(anchor) => SerialValue::Str(anchor.clone()),
365 None => SerialValue::Null,
366 };
367 (point_key(cx, *id), value)
368 })
369 .collect(),
370 )
371 }
372
373 fn piece_class(&self) -> PieceClass {
374 if self.ids.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
375 }
376}
377
378impl SingletonTable for Anchors {
379 const NAME: &'static str = "flm.anchors";
380}
381
382/// What a label resolves to inside the document: the point that keeps it,
383/// the link target (`#` followed by the anchor) and what a reference to it
384/// shows.
385#[derive(Debug, Clone)]
386pub struct RefTarget {
387 /// The point that keeps the label.
388 pub point: PointId,
389 /// The link target, `#<anchor>`.
390 pub href: String,
391 /// What a reference to the point shows.
392 pub display: PointDisplay,
393}
394
395/// The targets table, `flm.refs.targets` ([`REF_TARGETS`]): from a label to
396/// what it resolves to inside the document. It combines the label table and
397/// the anchors, and the anchors stage
398/// ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)), which runs once for the
399/// document, writes it. A label whose point received no anchor (a point that
400/// lost an anchor collision, or that has nothing to form an anchor from) has
401/// no entry, so a reference to it resolves to nothing in the document.
402///
403/// The combination is a table of its own so that the resolve stage
404/// ([`RESOLVE`](super::RESOLVE)) can read
405/// it over a synthesized value. The resolve stage runs once per tree, so
406/// [value catch-up](crate::guide::concepts_overview#value-catch-up) runs it
407/// again over a synthesized value, and the per-tree tables it then reads are
408/// those of that value. The table of reference points, `flm.refpoints`, is
409/// one of them: inside a synthesized value it holds the value's own points,
410/// usually none. This table is written by a stage that runs once for the
411/// document, which value catch-up never runs again, so the resolve stage
412/// reads the document's targets even over a synthesized value. Any other
413/// table that holds facts about the whole document and that a per-tree stage
414/// must read over a synthesized value needs the same arrangement.
415#[derive(Debug, Clone, Default)]
416pub struct RefTargets {
417 /// From a label to its target.
418 pub by_label: BTreeMap<Label, RefTarget>,
419}
420
421impl Table for RefTargets {
422 fn absorb(&mut self, piece: RefTargets) {
423 self.by_label.extend(piece.by_label);
424 }
425
426 fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
427 SerialValue::Map(
428 self.by_label
429 .iter()
430 .map(|(label, target)| {
431 (
432 label.to_string(),
433 SerialValue::Map(vec![
434 ("point".to_string(), SerialValue::Str(point_key(cx, target.point))),
435 ("href".to_string(), SerialValue::Str(target.href.clone())),
436 (
437 "display".to_string(),
438 target.display.project(cx, Some(target.point.addr.tree)),
439 ),
440 ]),
441 )
442 })
443 .collect(),
444 )
445 }
446
447 fn piece_class(&self) -> PieceClass {
448 if self.by_label.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
449 }
450}
451
452impl SingletonTable for RefTargets {
453 const NAME: &'static str = "flm.refs.targets";
454}
455
456/// How one reference site resolved.
457#[derive(Debug, Clone)]
458pub enum Resolution {
459 /// The target was found: in the document (`point` set) or in the external
460 /// index (`point` absent).
461 Resolved {
462 /// The point, for a target inside the document.
463 point: Option<PointId>,
464 /// The link target: `#<anchor>` for a point, the index's target
465 /// otherwise.
466 href: String,
467 /// What the site displays.
468 display: PointDisplay,
469 },
470 /// No point of the document and no target of the external index carries
471 /// the label; the resolve stage ([`RESOLVE`](super::RESOLVE)) reported
472 /// `flm.refs.unresolved`.
473 Unresolved {
474 /// The label the site points at.
475 target: Label,
476 },
477}
478
479/// The resolutions table, `flm.refs.resolutions` ([`REF_RESOLUTIONS`]): how
480/// every reference site resolved, for every node whose element carries the
481/// [`Referencing`](crate::model::aspects::Referencing) aspect.
482#[derive(Debug, Clone, Default)]
483pub struct RefResolutions {
484 /// From a site to its resolution.
485 pub sites: BTreeMap<SiteId, Resolution>,
486}
487
488impl RefResolutions {
489 /// The resolution of a site, or `None` for a site this table does not
490 /// hold.
491 pub fn site(&self, site: SiteId) -> Option<&Resolution> {
492 self.sites.get(&site)
493 }
494}
495
496impl Table for RefResolutions {
497 fn absorb(&mut self, piece: RefResolutions) {
498 self.sites.extend(piece.sites);
499 }
500
501 fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
502 SerialValue::Map(
503 self.sites
504 .iter()
505 .map(|(id, resolution)| {
506 let key = format!("{}#{}", node_key(cx, id.addr), id.index);
507 let value = match resolution {
508 Resolution::Resolved { point, href, display } => SerialValue::Map(vec![(
509 "resolved".to_string(),
510 SerialValue::Map(vec![
511 (
512 "point".to_string(),
513 match point {
514 Some(point) => SerialValue::Str(point_key(cx, *point)),
515 None => SerialValue::Str("external".to_string()),
516 },
517 ),
518 ("href".to_string(), SerialValue::Str(href.clone())),
519 (
520 "display".to_string(),
521 display.project(cx, point.map(|point| point.addr.tree)),
522 ),
523 ]),
524 )]),
525 Resolution::Unresolved { target } => SerialValue::Map(vec![(
526 "unresolved".to_string(),
527 SerialValue::Str(target.to_string()),
528 )]),
529 };
530 (key, value)
531 })
532 .collect(),
533 )
534 }
535}
536
537impl SingletonTable for RefResolutions {
538 const NAME: &'static str = "flm.refs.resolutions";
539}
540
541/// A target of the external index: where a link to a label of another
542/// document leads, and what a reference to it shows. What it shows is content
543/// (a synthesized value), not a string, so that a reference to another
544/// document is rendered the same way as one inside this document.
545#[derive(Debug, Clone)]
546pub struct ExternalTarget {
547 /// The link target, as the caller wants it written (`other.html#sec`).
548 pub href: String,
549 /// The content a reference shows, as a synthesized value. Build it by
550 /// parsing the text with the registry's language
551 /// ([`parse_fragment`](crate::lang::parse_fragment)) and copying the
552 /// parsed nodes with [`value_of`](super::value_of), as in
553 /// `value_of(&nodes, &root, registry.lang().guard())`, where `root` is the
554 /// root of the parsed tree and `nodes` its children.
555 pub display: Arc<NodeTree<Flm>>,
556}
557
558/// The external index, `flm.refs.external-index` ([`EXTERNAL_INDEX`]): from
559/// a label of another document to its target.
560///
561/// An embedding program that processes several documents installs it when it
562/// constructs a run ([`Externals`](crate::core::run::Externals)); no stage
563/// writes it. The resolve stage ([`RESOLVE`](super::RESOLVE)) reads it when the caller
564/// has installed it and looks a
565/// label up there only when no point of the document carries it; a run
566/// without it has no external labels.
567///
568/// To install one, build it with [`ExternalIndex::new`] and
569/// [`with`](ExternalIndex::with), one [`ExternalTarget`] per label, and pass
570/// it as `Externals::none().install_unstamped(EXTERNAL_INDEX, index)`
571/// ([`Externals::install_unstamped`](crate::core::run::Externals::install_unstamped))
572/// when the run is constructed.
573#[derive(Debug, Clone, Default)]
574pub struct ExternalIndex {
575 /// From a label to its target.
576 pub targets: BTreeMap<Label, ExternalTarget>,
577}
578
579impl ExternalIndex {
580 /// An empty index.
581 pub fn new() -> ExternalIndex {
582 ExternalIndex::default()
583 }
584
585 /// Builder: adds a target, replacing any target already held for that
586 /// label.
587 pub fn with(mut self, label: Label, target: ExternalTarget) -> ExternalIndex {
588 self.targets.insert(label, target);
589 self
590 }
591}
592
593impl Table for ExternalIndex {
594 fn absorb(&mut self, piece: ExternalIndex) {
595 self.targets.extend(piece.targets);
596 }
597
598 fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
599 SerialValue::Map(
600 self.targets
601 .iter()
602 .map(|(label, target)| {
603 (
604 label.to_string(),
605 SerialValue::Map(vec![
606 ("href".to_string(), SerialValue::Str(target.href.clone())),
607 ("display".to_string(), SerialValue::Str(plain_text(&target.display))),
608 ]),
609 )
610 })
611 .collect(),
612 )
613 }
614
615 fn piece_class(&self) -> PieceClass {
616 if self.targets.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
617 }
618}
619
620impl SingletonTable for ExternalIndex {
621 const NAME: &'static str = "flm.refs.external-index";
622}
623
624#[cfg(test)]
625mod tests {
626 use super::*;
627 use crate::model::aspects::{AcceptedRefTypes, AnchorPolicy, RefPoint};
628 use crate::model::doc::FragmentLayout;
629 use crate::lang::{FlmOrigin, LangInputs, ParseOptions, build_language, parse_fragment};
630 use techy::core::node::NodeId;
631 use techy::source::{Source, SourceSpan};
632
633 /// The root's id of a parse under the bare language: a point needs a node
634 /// address, and node ids come from trees only.
635 fn root_id() -> NodeId {
636 let lang = build_language(LangInputs::new());
637 let source = Arc::new(Source::new("x").with_origin(FlmOrigin::none()));
638 let fragment =
639 parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
640 .expect("a parse of `x`");
641 fragment.tree().root().id()
642 }
643
644 fn span() -> FlmSpan {
645 let source = Arc::new(Source::new("").with_origin(FlmOrigin::none()));
646 SourceSpan::new(&source, 0..0)
647 }
648
649 /// A point of the root node at the given point index (distinct points of
650 /// one node, since the test needs distinct identities only).
651 fn record(root: NodeId, index: u32, labels: &[&str]) -> RefPointRecord {
652 RefPointRecord {
653 id: PointId { addr: NodeAddr::new(TreeId::tree(0), root), index },
654 point: RefPoint {
655 kind: RefKind::from("section"),
656 labels: labels.iter().map(|l| Label::parse(l).unwrap()).collect(),
657 malformed: Vec::new(),
658 computed: 0,
659 anchor: AnchorPolicy::Auto { prefix: "sec".to_string() },
660 number: None,
661 content: None,
662 accepts: AcceptedRefTypes::Any,
663 },
664 span: span(),
665 }
666 }
667
668 #[test]
669 fn a_repeated_label_is_recorded_as_a_duplicate_keeping_the_first_point() {
670 let root = root_id();
671 let (first, second) = (record(root, 1, &["sec:a"]), record(root, 2, &["sec:a", "sec:b"]));
672 let mut labels = Labels::default();
673 labels.insert(&first);
674 labels.insert(&second);
675 assert_eq!(labels.by_label[&Label::new("sec", "a")], first.id);
676 assert_eq!(labels.by_label[&Label::new("sec", "b")], second.id);
677 assert_eq!(labels.duplicates.len(), 1);
678 assert_eq!(labels.duplicates[0].second, second.id);
679 }
680
681 #[test]
682 fn a_labels_piece_states_a_document_fact_only_when_it_holds_a_label() {
683 let root = root_id();
684 assert_eq!(Labels::default().piece_class(), PieceClass::Empty);
685 let mut unlabeled = Labels::default();
686 unlabeled.insert(&record(root, 1, &[]));
687 assert_eq!(unlabeled.piece_class(), PieceClass::Empty);
688 let mut labeled = Labels::default();
689 labeled.insert(&record(root, 1, &["sec:a"]));
690 assert_eq!(labeled.piece_class(), PieceClass::DocumentFact);
691 }
692
693 #[test]
694 fn the_anchors_table_tells_an_unseen_point_from_one_without_an_anchor() {
695 let root = root_id();
696 let seen = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 1 };
697 let collided = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 2 };
698 let unseen = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 3 };
699 let mut anchors = Anchors::default();
700 anchors.ids.insert(seen, Some("sec-intro".to_string()));
701 anchors.ids.insert(collided, None);
702 assert_eq!(anchors.id(seen), Some("sec-intro"));
703 assert_eq!(anchors.id(collided), None);
704 assert_eq!(anchors.lookup(collided), Some(None));
705 assert_eq!(anchors.lookup(unseen), None);
706 }
707}