Skip to main content

flm_core/stdlib/features/index/
mod.rs

1//! This module defines the `index` feature, which provides the *element index*.
2//! The element index is a table that lists, for each frozen tree of a run, the
3//! nodes of the tree together with their elements. A stage reads the element
4//! index to find the nodes that it works on, without walking the trees itself.
5//!
6//! Many stages look for the nodes whose element carries a given
7//! [aspect](crate::guide::concepts_overview#elements-and-aspects), that is, a
8//! piece of behavior attached to an element. For instance, the scan stage of
9//! the [`refpoints`](crate::stdlib::features::refpoints) feature looks for
10//! every node whose element carries the
11//! [`Referenceable`](crate::model::aspects::Referenceable) aspect. With the
12//! element index, each tree is walked once, by the stage [`BUILD`] of the
13//! `index` feature, and these stages filter the result.
14//!
15//! # What the feature registers
16//!
17//! The `index` feature offers no command or environment. It registers the
18//! following items:
19//!
20//! - The table [`ELEMENT_INDEX`] (`flm.element-index`), whose value is an
21//!   [`ElementIndex`].
22//! - The stage [`BUILD`] (`flm.index.build`), which writes this table. The
23//!   stage runs once for each tree. It records every node of the tree whose
24//!   element is registered in the run's registry, in *tree order*: the root,
25//!   then its descendants in preorder. A node whose element is not registered,
26//!   for instance an element that a program created itself, is not recorded.
27//!
28//! # Reading the element index
29//!
30//! To read the element index in a stage, declare the read in the stage's
31//! [`Stage::needs`] method with [`Needs::reads`]`(ELEMENT_INDEX)`. This
32//! declaration requires the table's capability, which the stage [`BUILD`]
33//! provides. Then obtain the table in the stage's [`Stage::run`] method with
34//! [`StageCx::get`].
35//!
36//! The following functions find nodes in the element index:
37//!
38//! - [`ElementIndex::nodes_with`] returns the nodes of one tree whose element
39//!   carries a given aspect. A stage that runs once for each tree calls this
40//!   method for its own tree.
41//! - [`walk_nodes_with`] returns the nodes of all trees of the run whose
42//!   element carries a given aspect, in document order. A stage that runs once
43//!   for the whole document calls this function.
44//! - [`ElementIndex::values_of`] and [`walk_values_of`] are the same two reads,
45//!   but they select the nodes by the type of the element's data instead of by
46//!   an aspect.
47//!
48//! Each of these functions returns, for each node found, the node's
49//! [address](crate::model::addr::NodeAddr), the node, and either the aspect
50//! implementation or the element's data.
51//!
52//! The table stores the nodes of each tree separately, in tree order. The
53//! [document
54//! order](crate::guide::concepts_overview#documents-fragments-and-the-corpus)
55//! is the order of [`StageCx::walk`]: when another tree is placed at a node,
56//! the nodes of that tree come immediately after this node.
57//! [`walk_nodes_with`] and [`walk_values_of`] sort the nodes of all trees into
58//! document order.
59//!
60//! # Element numbers and aspects
61//!
62//! The element index stores the element number of each node
63//! ([`FlmRegistry::elem_idx`]), and no separate list of nodes for each aspect.
64//! To find the nodes with an aspect, [`ElementIndex::nodes_with`] tests each
65//! element number against the set of elements that carry the aspect. This set
66//! is computed when the registry is built ([`FlmRegistry::aspect_bitset`]).
67//! Therefore the `index` feature does not depend on the aspects defined in
68//! other features.
69//!
70//! A read of the element index finds the same nodes as a walk of the tree that
71//! inspects the element of each node. Reading the element index only saves the
72//! walk.
73//!
74//! # Synthesized values
75//!
76//! A [*synthesized
77//! value*](crate::guide::concepts_overview#synthesized-values) is a small tree
78//! that a stage builds during a run, outside the document's trees, for instance
79//! the text displayed for a reference. Before a stage renders a synthesized
80//! value, it calls [`StageCx::resolve_value`], which performs [value
81//! catch-up](crate::guide::concepts_overview#value-catch-up): the stages that
82//! run once for each tree and that the calling stage depends on run over the
83//! synthesized value. The synthesized value then has the same kinds of computed
84//! data as a tree of the document.
85//!
86//! The stage [`BUILD`] is among these stages if the calling stage depends on
87//! it, directly or through other stages. This is the case, for instance, when
88//! the calling stage reads [`ELEMENT_INDEX`]. The element index computed during
89//! the catch-up contains only the nodes of the synthesized value.
90//!
91//! During the catch-up, a stage that runs over the synthesized value obtains
92//! the identifier of the value with [`StageCx::tree_id`] and the value itself
93//! with [`StageCx::my_tree`]. With these, [`ElementIndex::nodes_with`] returns
94//! nodes of the synthesized value. [`walk_nodes_with`] and [`walk_values_of`]
95//! return only nodes of the document's trees, never nodes of a synthesized
96//! value.
97
98// The reading helpers live here, beside the table, rather than on the stage
99// context: they need the registry's aspect bit sets and the table, and a stage
100// already holds both.
101
102use std::any::Any;
103use std::collections::BTreeMap;
104use std::sync::Arc;
105
106use techy::core::node::{NodeId, NodeRef, NodeTree};
107use techy::serialize::SerialValue;
108
109use crate::model::addr::{NodeAddr, TreeId};
110use crate::model::element::{ElemIdx, element_of};
111use crate::core::plan::PlanCx;
112use crate::core::registry::{
113    BuildError, FeatureBuilder, FeatureInfo, FlmFeature, FlmRegistry,
114};
115use crate::core::run::StageCx;
116use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
117use crate::core::data::store::StageOut;
118use crate::core::data::table::{ProjectCx, SingletonTable, Table, TableName};
119use crate::lang::Flm;
120
121/// The feature's registered name, `index`.
122pub const FEATURE: &str = "index";
123
124/// The name of the stage that builds the element index, `flm.index.build`.
125pub const BUILD: &str = "flm.index.build";
126
127/// The name of the element index table, `flm.element-index`, whose value is an
128/// [`ElementIndex`]. To read the table in a stage, declare the read with
129/// [`Needs::reads`]`(ELEMENT_INDEX)`.
130pub const ELEMENT_INDEX: TableName<ElementIndex> = TableName::new("flm.element-index");
131
132/// An `ElementIndex` lists the nodes of each frozen tree of a run, together
133/// with the element number of each node. It is the value of the table
134/// [`ELEMENT_INDEX`].
135///
136/// For each tree, the list contains every node whose element is registered in
137/// the registry, in tree order: the root, then its descendants in preorder. The
138/// element number of a node is the number of the node's element in the
139/// registry ([`FlmRegistry::elem_idx`]).
140///
141/// To find nodes in the element index, call [`ElementIndex::nodes_with`] or
142/// [`ElementIndex::values_of`] for one tree, or [`walk_nodes_with`] or
143/// [`walk_values_of`] for all trees of the run, in document order. The [module
144/// documentation](crate::stdlib::features::index) explains how a stage reads
145/// the element index.
146#[derive(Debug, Clone, Default, PartialEq, Eq)]
147pub struct ElementIndex {
148    /// The list of indexed nodes of each tree, keyed by the identifier of the
149    /// tree. Each list is in tree order, and contains each node with its
150    /// element number.
151    pub per_tree: BTreeMap<TreeId, Vec<(NodeId, ElemIdx)>>,
152}
153
154impl ElementIndex {
155    /// Returns the indexed nodes of the tree `tree`, in tree order, each with
156    /// its element number. Returns an empty slice if the element index contains
157    /// no list for `tree`.
158    pub fn entries(&self, tree: TreeId) -> &[(NodeId, ElemIdx)] {
159        self.per_tree.get(&tree).map(Vec::as_slice).unwrap_or(&[])
160    }
161
162    /// Returns the indexed nodes of one tree whose element carries the aspect
163    /// `A`, in tree order.
164    ///
165    /// `id` is the identifier of the tree, and `tree` is the frozen tree
166    /// itself. The aspect is given as a trait-object type, as in
167    /// `index.nodes_with::<dyn Referenceable>(registry, id, &tree)`. Each item
168    /// contains the address of the node, the node, and the element's
169    /// implementation of `A`.
170    ///
171    /// `registry` must be the registry of the run ([`StageCx::registry`]),
172    /// because the element numbers in the element index are numbers of that
173    /// registry. With another registry, the result can miss nodes.
174    ///
175    /// To find the nodes of all trees of the run, in document order, call
176    /// [`walk_nodes_with`].
177    pub fn nodes_with<'t, A: ?Sized + Any>(
178        &self,
179        registry: &FlmRegistry,
180        id: TreeId,
181        tree: &'t NodeTree<Flm>,
182    ) -> impl Iterator<Item = (NodeAddr, NodeRef<'t, Flm>, &'t A)> {
183        let bits = registry.aspect_bitset::<A>();
184        self.entries(id).iter().filter_map(move |(node_id, idx)| {
185            if !bits.contains(*idx) {
186                return None;
187            }
188            let node = tree.get(*node_id)?;
189            let aspect = element_of(&node).aspect::<A>()?;
190            Some((NodeAddr::new(id, *node_id), node, aspect))
191        })
192    }
193
194    /// Returns the indexed nodes of one tree whose element has data of type
195    /// `V`, in tree order.
196    ///
197    /// Same as [`ElementIndex::nodes_with`], but selects the nodes by the type
198    /// of the element's data
199    /// ([`ElementSpec::value_as`](crate::model::element::ElementSpec::value_as))
200    /// instead of by an aspect, as in `index.values_of::<HeadingElement>(id,
201    /// &tree)`. Each item contains the address of the node, the node, and the
202    /// element's data.
203    ///
204    /// This method inspects the element of every indexed node of the tree,
205    /// whereas [`ElementIndex::nodes_with`] tests the element number against a
206    /// precomputed set. Use [`ElementIndex::nodes_with`] where an aspect
207    /// identifies the nodes that you want. To find the nodes of all trees of
208    /// the run, in document order, call [`walk_values_of`].
209    pub fn values_of<'t, V: Any + Send + Sync>(
210        &self,
211        id: TreeId,
212        tree: &'t NodeTree<Flm>,
213    ) -> impl Iterator<Item = (NodeAddr, NodeRef<'t, Flm>, &'t V)> {
214        self.entries(id).iter().filter_map(move |(node_id, _)| {
215            let node = tree.get(*node_id)?;
216            let value = element_of(&node).value_as::<V>()?;
217            Some((NodeAddr::new(id, *node_id), node, value))
218        })
219    }
220}
221
222impl Table for ElementIndex {
223    fn absorb(&mut self, piece: ElementIndex) {
224        self.per_tree.extend(piece.per_tree);
225    }
226
227    /// Serializes the element index as a map from each tree identifier, such as
228    /// `tree#0`, to the list of the indexed nodes of the tree, in tree order.
229    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
230        SerialValue::Map(
231            self.per_tree
232                .iter()
233                .map(|(tree, entries)| {
234                    let nodes = entries
235                        .iter()
236                        .map(|(node, _)| cx.node_ref(NodeAddr::new(*tree, *node)))
237                        .collect();
238                    (tree.to_string(), SerialValue::List(nodes))
239                })
240                .collect(),
241        )
242    }
243}
244
245impl SingletonTable for ElementIndex {
246    const NAME: &'static str = "flm.element-index";
247}
248
249/// Returns the indexed nodes of all frozen trees of the run whose element
250/// carries the aspect `A`, in document order.
251///
252/// The aspect is given as a trait-object type, as in `walk_nodes_with::<dyn
253/// Referenceable>(cx, index)`. Each item contains the address of the node, the
254/// node, and the element's implementation of `A`.
255///
256/// Document order is the order of [`StageCx::walk`]: when another tree is
257/// placed at a node, the nodes of that tree come immediately after this node. A
258/// stage that runs once for the whole document calls this function. A stage
259/// that runs once for each tree calls [`ElementIndex::nodes_with`] for its own
260/// tree.
261pub fn walk_nodes_with<'a, A: ?Sized + Any>(
262    cx: &StageCx<'a>,
263    index: &'a ElementIndex,
264) -> impl Iterator<Item = (NodeAddr, NodeRef<'a, Flm>, &'a A)> + 'a {
265    let registry = cx.registry();
266    let found = cx.trees().flat_map(|(id, tree)| index.nodes_with::<A>(registry, id, tree));
267    in_document_order(cx, found)
268}
269
270/// Returns the indexed nodes of all frozen trees of the run whose element has
271/// data of type `V`, in document order.
272///
273/// Same as [`walk_nodes_with`], but selects the nodes by the type of the
274/// element's data instead of by an aspect, as in
275/// `walk_values_of::<HeadingElement>(cx, index)`. Each item contains the
276/// address of the node, the node, and the element's data. A stage that runs
277/// once for each tree calls [`ElementIndex::values_of`] for its own tree.
278pub fn walk_values_of<'a, V: Any + Send + Sync>(
279    cx: &StageCx<'a>,
280    index: &'a ElementIndex,
281) -> impl Iterator<Item = (NodeAddr, NodeRef<'a, Flm>, &'a V)> + 'a {
282    let found = cx.trees().flat_map(|(id, tree)| index.values_of::<V>(id, tree));
283    in_document_order(cx, found)
284}
285
286/// Sorts the items `found`, gathered from several trees, into document order by
287/// the position of each node ([`StageCx::position`]). The sort is stable: items
288/// with the same position keep their order in `found`.
289fn in_document_order<'a, T>(
290    cx: &StageCx<'a>,
291    found: impl Iterator<Item = (NodeAddr, NodeRef<'a, Flm>, T)>,
292) -> std::vec::IntoIter<(NodeAddr, NodeRef<'a, Flm>, T)> {
293    // A per-tree table holds no place in the document, so the entries gathered
294    // from several trees are sorted by the position the run gives each node in
295    // its one walk of the document.
296    // Every node of a tree of the run has a position; only a synthesized
297    // value's nodes have none, and the stable sort keeps their order (first).
298    let mut found: Vec<_> = found.collect();
299    found.sort_by_key(|(addr, _, _)| cx.position(*addr));
300    found.into_iter()
301}
302
303/// The `index` feature, which registers the table [`ELEMENT_INDEX`] and the
304/// stage [`BUILD`] that writes this table. The [module
305/// documentation](crate::stdlib::features::index) explains how a stage reads
306/// the element index.
307///
308/// The table [`ELEMENT_INDEX`] is read by stages of several features, among
309/// them [`refpoints`](crate::stdlib::features::refpoints) and
310/// [`refs`](crate::stdlib::features::refs). A registry that contains one of
311/// these features must also contain the `index` feature.
312#[derive(Debug, Default, Clone, Copy)]
313pub struct Index;
314
315impl FlmFeature for Index {
316    fn info(&self) -> FeatureInfo {
317        FeatureInfo::new(FEATURE, "Element index").docs(
318            "The element index (table `flm.element-index`), which lists the nodes of each \
319             tree together with their elements. Stages read it to find the nodes whose \
320             element carries a given aspect, without walking the trees.",
321        )
322    }
323
324    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
325        b.table(
326            ELEMENT_INDEX,
327            "For each tree, the nodes whose element is registered, in tree order, each \
328             with the number of its element in the registry.",
329        )?;
330        b.stage(Arc::new(BuildIndex))?;
331        Ok(())
332    }
333}
334
335/// Returns the [`Index`] feature as a shared feature object, for instance to
336/// list it in a [`PackageEntry`](crate::core::registry::PackageEntry).
337pub fn feature() -> Arc<dyn FlmFeature> {
338    Arc::new(Index)
339}
340
341/// The stage [`BUILD`] (`flm.index.build`), which writes the element index. The
342/// stage runs once for each tree. It walks the tree once and records each node
343/// whose element is registered in the registry, in tree order.
344struct BuildIndex;
345
346impl Stage for BuildIndex {
347    fn decl(&self) -> StageDecl {
348        StageDecl::new(BUILD, Effect::Compute, Scope::PerTree).writes(ELEMENT_INDEX).docs(
349            "Records in `flm.element-index` each node of the tree whose element is \
350             registered, in tree order.",
351        )
352    }
353
354    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
355        Needs::new()
356    }
357
358    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
359        let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
360        let registry = cx.registry();
361        let root = tree.root();
362        let entries: Vec<(NodeId, ElemIdx)> = std::iter::once(root)
363            .chain(root.descendants())
364            .filter_map(|node| registry.elem_idx(element_of(&node)).map(|idx| (node.id(), idx)))
365            .collect();
366        // The write is declared above, so the piece is always obtainable;
367        // the runner refuses an undeclared write before a stage ever runs.
368        if let Ok(index) = out.table(ELEMENT_INDEX) {
369            index.per_tree.insert(id, entries);
370        }
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[test]
379    fn the_stage_writes_the_index_per_tree_and_needs_nothing() {
380        let decl = BuildIndex.decl();
381        assert_eq!(decl.name, BUILD);
382        assert_eq!(decl.effect, Effect::Compute);
383        assert_eq!(decl.scope, Scope::PerTree);
384        assert_eq!(decl.writes[0].name, ELEMENT_INDEX.name());
385        assert_eq!(ElementIndex::NAME, ELEMENT_INDEX.name());
386    }
387
388    #[test]
389    fn absorbing_pieces_keeps_every_tree() {
390        let mut index = ElementIndex::default();
391        let mut piece = ElementIndex::default();
392        piece.per_tree.insert(TreeId::tree(1), Vec::new());
393        index.per_tree.insert(TreeId::tree(0), Vec::new());
394        index.absorb(piece);
395        assert_eq!(index.per_tree.len(), 2);
396        assert!(index.entries(TreeId::tree(2)).is_empty());
397    }
398}