Skip to main content

flm_core/core/data/
store.rs

1//! The store of computed tables, and the checked access through which a stage
2//! reads and writes it.
3//!
4//! The store is the run's collection of computed tables: one writer per table, a
5//! declared write always installs a value, and every read and write is checked
6//! against the stage's declarations at the access site ([`Computed`]). A table
7//! is typed data that one stage writes beside the frozen trees and other stages
8//! read ([`Table`]).
9//!
10//! A stage never changes the store. It reads the frozen trees and a view of the
11//! store ([`ComputedView`]), and writes table pieces and diagnostics into a
12//! collector ([`StageOut`]); a table piece is the part of one table that one
13//! stage invocation produced ([`PieceClass`]). The runner then folds the
14//! collectors into the next version of the store with [`fold_outs`].
15//!
16//! # Determinism of the store
17//!
18//! During a run, the store changes in three ways:
19//! [`Run::new`](crate::core::run::Run::new) installs the values of the external
20//! tables, the runner installs the table of each rewrite stage once the rewrite
21//! stages are over, and [`fold_outs`] folds the collectors of each later stage
22//! into it. The sequential and the parallel runner use the same fold, which
23//! follows these rules, so that the store's content never depends on the order
24//! in which the stages finished:
25//!
26//! - the table pieces of one per-tree stage (a stage of
27//!   [`Scope::PerTree`](crate::core::stage::Scope::PerTree), run once for each
28//!   tree) are absorbed in **the run's order of the trees**
29//!   ([`Run::tree_order`](crate::core::run::Run::tree_order)), the order in
30//!   which the runner passes them. In document order, a placed tree (the tree of
31//!   an included file that opens with a heading, see [`crate::core::run::order`])
32//!   comes in the middle of the tree that includes it, so a table
33//!   holding entries of every tree holds them tree after tree, not in document
34//!   order; a reader that needs document order across trees sorts by
35//!   [`StageCx::position`](crate::core::run::StageCx::position);
36//! - the tables of one stage are installed in **[`TableId`] order**;
37//! - **one writer per table**: installing a table that is already present is
38//!   refused with [`StoreError::SecondWriter`]; plan construction already
39//!   guarantees that it never happens;
40//! - **a declared write always installs a value**: a write that a stage
41//!   declared but produced no table piece for still installs an empty table,
42//!   so a read that returns `None` always means "no stage provided this table"
43//!   and never "a stage ran and found nothing".
44//!
45//! # Access checks
46//!
47//! Every read and every write is checked against the stage's declarations
48//! **at the access site**, in every build: an undeclared read or write returns
49//! an [`AccessError`] that identifies the stage and the table, never a silent
50//! `None`. These checks come in addition to the checks that plan construction
51//! makes before any stage runs.
52//!
53//! # Reading during value catch-up
54//!
55//! [Value catch-up](crate::guide::concepts_overview#value-catch-up) runs
56//! per-tree stages again over a synthesized value, a small tree that a stage
57//! built during the run. What these stages compute goes into a catch-up store,
58//! a [`Computed`] of its own that a view reads on top of the run's store
59//! ([`ComputedView::with_overlay`]); value catch-up never writes the run's
60//! store. [`ComputedView::with_overlay`] states the reading rule that a feature
61//! author has to know.
62//!
63//! # Items
64//!
65//! - [`Computed`]: one version of the store, each present table by its
66//!   [`TableId`].
67//! - [`ComputedView`]: a stage's read view, checked against the stage's
68//!   [`ReadSet`].
69//! - [`StageOut`]: a stage's write collector, checked against the stage's
70//!   [`WriteSet`].
71//! - [`fold_outs`] and [`FoldTarget`]: the runner's fold of a stage's
72//!   collectors into the store.
73//! - [`StoreError`] and [`AccessError`]: the errors of the store and of the
74//!   access sites.
75//!
76//! [`Table`]: crate::core::data::table::Table
77//! [`PieceClass`]: crate::core::data::table::PieceClass
78//!
79//! # Examples
80//!
81//! One stage writes a table in two calls, the runner folds the two collectors
82//! into the store, and a later stage reads the result. Plan construction
83//! resolves each stage's [`ReadSet`] and [`WriteSet`], and the runner does the
84//! fold; a feature author writes only the two middle steps, the writing into a
85//! [`StageOut`] and the reading through a view.
86//!
87//! ```
88//! use flm_core::model::names::StageName;
89//! use flm_core::core::data::store::{
90//!     Computed, ComputedView, FoldTarget, ReadEntry, ReadSet, StageOut, WriteEntry, WriteSet,
91//!     fold_outs,
92//! };
93//! use flm_core::core::data::table::{SingletonTable, Table, TableId, TableType};
94//! use flm_core::lang::origin::FlmDiagnostics;
95//!
96//! #[derive(Default)]
97//! struct Count(u32);
98//!
99//! impl Table for Count {
100//!     fn absorb(&mut self, piece: Count) {
101//!         self.0 += piece.0;
102//!     }
103//! }
104//!
105//! impl SingletonTable for Count {
106//!     const NAME: &'static str = "example.count";
107//! }
108//!
109//! let stage: StageName = "example.counter".into();
110//! let id = TableId(0);
111//!
112//! let mut writes = WriteSet::new();
113//! writes.insert("example.count".into(), WriteEntry { id, ty: TableType::of::<Count>() });
114//!
115//! // Two calls of the stage, each producing one table piece.
116//! let mut first = StageOut::new(&stage, &writes);
117//! first.table_singleton::<Count>()?.0 = 2;
118//! let mut second = StageOut::new(&stage, &writes);
119//! second.table_singleton::<Count>()?.0 = 3;
120//!
121//! // The runner folds them into the next version of the store.
122//! let mut store = Computed::new();
123//! let mut diags = FlmDiagnostics::new();
124//! fold_outs(&stage, &writes, vec![first, second], FoldTarget::Main, &mut store, &mut diags)?;
125//!
126//! // A stage that declared the read reads the absorbed table.
127//! let mut reads = ReadSet::new();
128//! reads.insert(
129//!     "example.count".into(),
130//!     ReadEntry {
131//!         id,
132//!         ty: TableType::of::<Count>(),
133//!         optional: false,
134//!         producer: Some(stage.clone()),
135//!     },
136//! );
137//! let reader: StageName = "example.reader".into();
138//! let view = ComputedView::new(&reader, &reads, &store);
139//! assert_eq!(view.get_singleton::<Count>()?.unwrap().0, 5);
140//! # Ok::<(), Box<dyn std::error::Error>>(())
141//! ```
142
143// This module uses the name newtypes of `crate::model::names` and the
144// diagnostics alias of `crate::lang::origin`; it does not depend on the
145// registry, on plan construction or on the runner.
146
147use std::any::Any;
148use std::collections::BTreeMap;
149use std::fmt;
150use std::sync::Arc;
151
152use crate::model::names::{CapName, StageName};
153use crate::core::data::table::{
154    PieceClass, SingletonTable, Table, TableId, TableKey, TableRef, TableType,
155};
156use crate::lang::origin::FlmDiagnostics;
157
158/// One version of the store: each present table, under its [`TableId`], as a
159/// shared value.
160///
161/// The store is the run's collection of computed tables: one writer per table,
162/// a declared write always installs a value, and every read and write is
163/// checked against the stage's declarations at the access site. `Computed`
164/// itself enforces the first rule ([`Computed::install`]); [`fold_outs`]
165/// enforces the second; the third is enforced by [`ComputedView`] and
166/// [`StageOut`], through which every stage reads and writes. `Computed`
167/// performs no access check of its own.
168///
169/// A [`Run`](crate::core::run::Run) owns the store; an embedding program reads
170/// it after the run with [`Run::table`](crate::core::run::Run::table) or
171/// [`Run::computed`](crate::core::run::Run::computed). Value catch-up fills a
172/// `Computed` of its own, the catch-up store.
173///
174/// Cloning a `Computed` shares every table rather than copying it (one
175/// reference count per table), so deriving the next version of the store is
176/// cheap.
177#[derive(Clone, Default)]
178pub struct Computed {
179    tables: BTreeMap<TableId, Arc<dyn Any + Send + Sync>>,
180}
181
182impl Computed {
183    /// Creates an empty store.
184    pub fn new() -> Computed {
185        Computed::default()
186    }
187
188    /// Returns the type-erased table with this id, if one is present.
189    pub fn get_erased(&self, id: TableId) -> Option<&Arc<dyn Any + Send + Sync>> {
190        self.tables.get(&id)
191    }
192
193    /// Returns the table with this id as a `T`: `None` when no table is
194    /// present under `id`, and also `None` when the table present is not a
195    /// `T`. The checked views compare the value type before they read, so
196    /// they never ask for the wrong type.
197    pub fn get_as<T: Table>(&self, id: TableId) -> Option<&T> {
198        self.tables.get(&id).and_then(|table| table.downcast_ref::<T>())
199    }
200
201    /// Whether a table with this id is present.
202    pub fn contains(&self, id: TableId) -> bool {
203        self.tables.contains_key(&id)
204    }
205
206    /// The ids of the present tables, in `TableId` order.
207    pub fn ids(&self) -> impl Iterator<Item = TableId> + '_ {
208        self.tables.keys().copied()
209    }
210
211    /// The number of present tables.
212    pub fn len(&self) -> usize {
213        self.tables.len()
214    }
215
216    /// Whether no table is present.
217    pub fn is_empty(&self) -> bool {
218        self.tables.is_empty()
219    }
220
221    /// Installs `table` under `id`: the table that the table's one writer
222    /// produced, or the value of an external table installed when the run is
223    /// constructed.
224    ///
225    /// This performs no check of the value type: the caller must ensure that
226    /// `table` is a value of the type declared for `id`. A typed read of a
227    /// mismatched table panics ([`ComputedView::get`]). The runner checks the
228    /// type before it installs anything.
229    ///
230    /// # Errors
231    ///
232    /// [`StoreError::SecondWriter`] if a table is already present under `id`.
233    /// A table has one writer, and plan construction guarantees it.
234    pub fn install(
235        &mut self,
236        id: TableId,
237        table: Arc<dyn Any + Send + Sync>,
238    ) -> Result<(), StoreError> {
239        if self.tables.contains_key(&id) {
240            return Err(StoreError::SecondWriter { table: id });
241        }
242        self.tables.insert(id, table);
243        Ok(())
244    }
245}
246
247impl fmt::Debug for Computed {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.debug_list().entries(self.tables.keys()).finish()
250    }
251}
252
253/// An error of the store itself, as opposed to an error at an access site
254/// ([`AccessError`]).
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub enum StoreError {
257    /// A table was installed under a [`TableId`] that already holds one. Plan
258    /// construction schedules one writer per table, so this error means that
259    /// the runner, or a caller that fills a [`Computed`] directly, broke that
260    /// invariant.
261    SecondWriter {
262        /// The number of the table.
263        table: TableId,
264    },
265    /// During [value
266    /// catch-up](crate::guide::concepts_overview#value-catch-up), a stage run
267    /// over a synthesized value produced a table piece that states a fact
268    /// about the document as a whole ([`PieceClass::DocumentFact`]).
269    ///
270    /// A synthesized value is not part of the document, so it may not add to
271    /// the document's facts.
272    DocumentFactInValue {
273        /// The stage that produced the table piece.
274        stage: StageName,
275        /// The name of the table.
276        table: CapName,
277    },
278}
279
280impl fmt::Display for StoreError {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        match self {
283            StoreError::SecondWriter { table } => {
284                write!(f, "{table} is already installed: a table can be installed only once")
285            }
286            StoreError::DocumentFactInValue { stage, table } => write!(
287                f,
288                "stage `{stage}`, run over content generated during processing, wrote data \
289                 about the whole document into table `{table}`; generated content must not \
290                 add data about the whole document"
291            ),
292        }
293    }
294}
295
296impl std::error::Error for StoreError {}
297
298/// An error at a table access site: a stage read or wrote a table it did not
299/// declare, or used a typed table key whose value type is not the declared
300/// one.
301///
302/// These checks run in every build, so an undeclared access always returns this
303/// error, never a silent `None`. [`Run::table`](crate::core::run::Run::table)
304/// returns it too, for a table that the registry does not declare or a key of
305/// another value type; the stage it reports is then `_host`
306/// ([`HOST_FEATURE`](crate::core::registry::builder::HOST_FEATURE)).
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub enum AccessError {
309    /// A stage read a table that it did not declare as a read
310    /// ([`Needs::reads`](crate::core::stage::Needs::reads) or
311    /// [`Needs::reads_opt`](crate::core::stage::Needs::reads_opt)).
312    UndeclaredRead {
313        /// The reading stage.
314        stage: StageName,
315        /// The name of the table.
316        table: CapName,
317        /// The tables the stage declared as reads, ordinary and optional, in
318        /// name order.
319        declared: Vec<CapName>,
320    },
321    /// A stage wrote a table that it did not declare as a write
322    /// ([`StageDecl::writes`](crate::core::stage::StageDecl::writes)).
323    UndeclaredWrite {
324        /// The writing stage.
325        stage: StageName,
326        /// The name of the table.
327        table: CapName,
328        /// The tables the stage declared as writes, in name order.
329        declared: Vec<CapName>,
330    },
331    /// A typed table key's value type is not the value type declared for the
332    /// table.
333    TypeMismatch {
334        /// The stage that accessed the table.
335        stage: StageName,
336        /// The name of the table.
337        table: CapName,
338        /// The short name of the declared value type.
339        declared: &'static str,
340        /// The short name of the value type of the key.
341        requested: &'static str,
342    },
343}
344
345impl fmt::Display for AccessError {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        match self {
348            AccessError::UndeclaredRead { stage, table, declared } => write!(
349                f,
350                "stage `{stage}` reads table `{table}` without declaring it; declared reads: \
351                 [{}]",
352                join_names(declared)
353            ),
354            AccessError::UndeclaredWrite { stage, table, declared } => write!(
355                f,
356                "stage `{stage}` writes table `{table}` without declaring it; declared writes: \
357                 [{}]",
358                join_names(declared)
359            ),
360            AccessError::TypeMismatch { stage, table, declared, requested } => write!(
361                f,
362                "stage `{stage}` accesses table `{table}` with value type `{requested}`, but the \
363                 table is declared with value type `{declared}`"
364            ),
365        }
366    }
367}
368
369impl std::error::Error for AccessError {}
370
371fn join_names(names: &[CapName]) -> String {
372    names.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
373}
374
375/// One read that a stage declared, as plan construction resolved it: the
376/// table's number and value type, whether the read is optional, and which
377/// stage the plan scheduled to write the table.
378///
379/// The writer is absent for an external table, whose value the caller installs
380/// when the run is constructed, and for an optional read that no stage of the
381/// plan provides. A plan holds the resolved reads of each stage in the stage's
382/// record ([`Plan::manifest`](crate::core::plan::Plan::manifest)).
383///
384/// It is written to data with `Serialize`; see [serialized
385/// forms](crate::core::registry#serialized-forms).
386#[derive(Debug, Clone)]
387#[derive(serde::Serialize, schemars::JsonSchema)]
388pub struct ReadEntry {
389    /// The number of the table.
390    pub id: TableId,
391    /// The table's declared value type.
392    #[serde(skip)]
393    pub ty: TableType,
394    /// Whether the table may be absent: the stage declared this read with
395    /// [`Needs::reads_opt`](crate::core::stage::Needs::reads_opt).
396    pub optional: bool,
397    /// The stage the plan scheduled to write the table, when there is one.
398    pub producer: Option<StageName>,
399}
400
401/// The reads that one stage declared, as plan construction resolved them, by
402/// table name. A [`ComputedView`] checks every read against it.
403///
404/// It is written to data with `Serialize`; see [serialized
405/// forms](crate::core::registry#serialized-forms).
406#[derive(Debug, Clone, Default)]
407#[derive(serde::Serialize, schemars::JsonSchema)]
408#[serde(transparent)]
409pub struct ReadSet {
410    entries: BTreeMap<CapName, ReadEntry>,
411}
412
413impl ReadSet {
414    /// Creates an empty set.
415    pub fn new() -> ReadSet {
416        ReadSet::default()
417    }
418
419    /// Adds a resolved read.
420    pub fn insert(&mut self, name: CapName, entry: ReadEntry) {
421        self.entries.insert(name, entry);
422    }
423
424    /// Returns the resolved read of the table `name`, if the stage declared
425    /// one.
426    pub fn get(&self, name: &str) -> Option<&ReadEntry> {
427        self.entries.get(name)
428    }
429
430    /// The declared table names, in name order.
431    pub fn names(&self) -> Vec<CapName> {
432        self.entries.keys().cloned().collect()
433    }
434
435    /// The entries, in name order.
436    pub fn iter(&self) -> impl Iterator<Item = (&CapName, &ReadEntry)> + '_ {
437        self.entries.iter()
438    }
439}
440
441/// One write that a stage declared, as plan construction resolved it: the
442/// table's number and value type.
443///
444/// It is written to data with `Serialize`; see [serialized
445/// forms](crate::core::registry#serialized-forms).
446#[derive(Debug, Clone)]
447#[derive(serde::Serialize, schemars::JsonSchema)]
448pub struct WriteEntry {
449    /// The number of the table.
450    pub id: TableId,
451    /// The table's declared value type.
452    #[serde(skip)]
453    pub ty: TableType,
454}
455
456/// The writes that one stage declared, as plan construction resolved them, by
457/// table name. A [`StageOut`] checks every write against it, and [`fold_outs`]
458/// installs a table for each of them.
459///
460/// It is written to data with `Serialize`; see [serialized
461/// forms](crate::core::registry#serialized-forms).
462#[derive(Debug, Clone, Default)]
463#[derive(serde::Serialize, schemars::JsonSchema)]
464#[serde(transparent)]
465pub struct WriteSet {
466    entries: BTreeMap<CapName, WriteEntry>,
467}
468
469impl WriteSet {
470    /// Creates an empty set.
471    pub fn new() -> WriteSet {
472        WriteSet::default()
473    }
474
475    /// Adds a resolved write.
476    pub fn insert(&mut self, name: CapName, entry: WriteEntry) {
477        self.entries.insert(name, entry);
478    }
479
480    /// Returns the resolved write of the table `name`, if the stage declared
481    /// one.
482    pub fn get(&self, name: &str) -> Option<&WriteEntry> {
483        self.entries.get(name)
484    }
485
486    /// The declared table names, in name order.
487    pub fn names(&self) -> Vec<CapName> {
488        self.entries.keys().cloned().collect()
489    }
490
491    /// The entries, in name order.
492    pub fn iter(&self) -> impl Iterator<Item = (&CapName, &WriteEntry)> + '_ {
493        self.entries.iter()
494    }
495
496    /// Whether no write is declared.
497    pub fn is_empty(&self) -> bool {
498        self.entries.is_empty()
499    }
500}
501
502/// A stage's read view of the store: typed reads, each checked at the access
503/// site against the reads the stage declared, with an optional catch-up store
504/// read before the run's store.
505///
506/// The runner creates one view for each stage call and hands it to the stage
507/// inside the [`StageCx`](crate::core::run::StageCx); a stage usually reads
508/// through [`StageCx::get`](crate::core::run::StageCx::get), which reads
509/// through this view. Read a declared table with [`get`](ComputedView::get) or
510/// [`get_singleton`](ComputedView::get_singleton). The view is `Copy` and
511/// borrows the store, so passing it around costs nothing.
512#[derive(Clone, Copy)]
513pub struct ComputedView<'a> {
514    stage: &'a StageName,
515    reads: &'a ReadSet,
516    store: &'a Computed,
517    overlay: Option<&'a Computed>,
518}
519
520impl<'a> ComputedView<'a> {
521    /// Creates a view of `store` for `stage`, checked against `reads`.
522    pub fn new(stage: &'a StageName, reads: &'a ReadSet, store: &'a Computed) -> ComputedView<'a> {
523        ComputedView { stage, reads, store, overlay: None }
524    }
525
526    /// Returns the same view, reading the catch-up store `overlay` before the
527    /// run's store: a table present in `overlay` is read from there, any other
528    /// table from the run's store.
529    ///
530    /// **A catch-up store shadows a table whole, never entry by entry.**
531    /// During [value catch-up](crate::guide::concepts_overview#value-catch-up),
532    /// the catch-up store holds the synthesized value's own table piece of
533    /// every table that the stages run over the value write, and a read of
534    /// such a table returns that table piece alone, with none of the entries of
535    /// the run's store.
536    ///
537    /// Consequently, a stage that runs during value catch-up and needs data
538    /// about the whole document must read a table that the catch-up store can
539    /// never hold, that is, a table that no per-tree stage (a stage of
540    /// [`Scope::PerTree`](crate::core::stage::Scope::PerTree), run once for
541    /// each tree) run during the catch-up writes. In practice, it is a table
542    /// that a document-scope stage (a stage of
543    /// [`Scope::Document`](crate::core::stage::Scope::Document), run once for
544    /// the whole document) writes. The `refs` feature does so:
545    /// its resolve stage reads
546    /// [`REF_TARGETS`](crate::stdlib::features::refs::REF_TARGETS), written
547    /// once for the document, rather than the reference points of
548    /// [`REFPOINTS`](crate::stdlib::features::refpoints::REFPOINTS), written
549    /// per tree.
550    ///
551    /// This rule is the reading side of the rule that
552    /// [`StoreError::DocumentFactInValue`] enforces on the writing side: a
553    /// synthesized value neither adds facts to the document nor reads them
554    /// through a per-tree table.
555    ///
556    /// See also [`StageCx::resolve_value`](crate::core::run::StageCx::resolve_value)
557    /// and [`CaughtUp::view`](crate::core::run::CaughtUp::view).
558    pub fn with_overlay(self, overlay: &'a Computed) -> ComputedView<'a> {
559        ComputedView { overlay: Some(overlay), ..self }
560    }
561
562    /// The stage whose reads this view checks.
563    pub fn stage(&self) -> &'a StageName {
564        self.stage
565    }
566
567    /// The resolved reads that this view checks against.
568    pub fn reads(&self) -> &'a ReadSet {
569        self.reads
570    }
571
572    /// The declared entry of a table, checked against the handle's type.
573    fn entry(&self, key: &TableRef) -> Result<&'a ReadEntry, AccessError> {
574        let Some(entry) = self.reads.get(&key.name) else {
575            return Err(AccessError::UndeclaredRead {
576                stage: self.stage.clone(),
577                table: key.name.clone(),
578                declared: self.reads.names(),
579            });
580        };
581        if entry.ty.type_id() != key.type_id {
582            return Err(AccessError::TypeMismatch {
583                stage: self.stage.clone(),
584                table: key.name.clone(),
585                declared: entry.ty.short_name(),
586                requested: key.short_type_name(),
587            });
588        }
589        Ok(entry)
590    }
591
592    fn lookup(&self, id: TableId) -> Option<&'a Arc<dyn Any + Send + Sync>> {
593        self.overlay
594            .and_then(|overlay| overlay.get_erased(id))
595            .or_else(|| self.store.get_erased(id))
596    }
597
598    /// Reads a table that the stage declared as a read, through a typed table
599    /// key.
600    ///
601    /// `Ok(None)` means the table is not present, which happens only for an
602    /// optional read that no stage of the plan provides: plan construction
603    /// schedules a writer for every other read, and
604    /// [`Run::new`](crate::core::run::Run::new) requires a value for every
605    /// external table the plan needs.
606    ///
607    /// # Errors
608    ///
609    /// [`AccessError::UndeclaredRead`] if the stage did not declare a read of
610    /// this table; [`AccessError::TypeMismatch`] if the value type of `key` is
611    /// not the declared one.
612    ///
613    /// # Panics
614    ///
615    /// Panics if the table installed under this name holds a value of another
616    /// type than the declared one. A stage cannot cause this: the declared type
617    /// is checked here and when the table is written, and
618    /// [`Run::new`](crate::core::run::Run::new) checks the type of every
619    /// external table's value before it installs it. The panic can only be
620    /// reached through a [`Computed`] that a caller filled directly with
621    /// [`Computed::install`], which does not check the value type.
622    pub fn get<K: TableKey>(&self, key: K) -> Result<Option<&'a K::Table>, AccessError> {
623        let entry = self.entry(&key.table_ref())?;
624        Ok(self.lookup(entry.id).map(|table| {
625            table
626                .downcast_ref::<K::Table>()
627                .expect("a table is stored under its declared type, which the key matched")
628        }))
629    }
630
631    /// Reads the one table of a value type `T` that exactly one table uses
632    /// ([`SingletonTable`]): [`get`](ComputedView::get) with the table name
633    /// `T::NAME`.
634    ///
635    /// # Errors
636    ///
637    /// As for [`get`](ComputedView::get).
638    ///
639    /// # Panics
640    ///
641    /// As for [`get`](ComputedView::get).
642    pub fn get_singleton<T: SingletonTable>(&self) -> Result<Option<&'a T>, AccessError> {
643        self.get(T::table_name())
644    }
645
646    /// Reads a table that the stage declared as a read, by name and
647    /// type-erased, for a reader that has no Rust type for the value, such as a
648    /// dump.
649    ///
650    /// # Errors
651    ///
652    /// [`AccessError::UndeclaredRead`] if the stage did not declare a read of
653    /// this table. No type check applies, since the call gives no value type.
654    pub fn get_erased(
655        &self,
656        name: &str,
657    ) -> Result<Option<&'a Arc<dyn Any + Send + Sync>>, AccessError> {
658        let Some(entry) = self.reads.get(name) else {
659            return Err(AccessError::UndeclaredRead {
660                stage: self.stage.clone(),
661                table: CapName::from(name),
662                declared: self.reads.names(),
663            });
664        };
665        Ok(self.lookup(entry.id))
666    }
667
668    /// Returns the stage that plan construction scheduled to write the table
669    /// `name`, which this stage declared as a read. A diagnostic uses it to
670    /// identify where a missing table entry should have come from
671    /// ([`MissingEntry`](crate::core::run::MissingEntry)). `None` for an
672    /// external table, for a table that no stage of the plan provides, and for
673    /// a table that this stage did not declare as a read.
674    pub fn producer_of(&self, name: &str) -> Option<&'a StageName> {
675        self.reads.get(name).and_then(|entry| entry.producer.as_ref())
676    }
677}
678
679impl fmt::Debug for ComputedView<'_> {
680    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
681        f.debug_struct("ComputedView")
682            .field("stage", self.stage)
683            .field("reads", &self.reads.names())
684            .field("overlay", &self.overlay.is_some())
685            .finish()
686    }
687}
688
689/// One table piece that a stage call produced, with its value type.
690struct Piece {
691    ty: TableType,
692    table: Box<dyn Any + Send + Sync>,
693}
694
695/// A stage's write collector for one call: the table pieces that the call
696/// produces, each checked at first access against the writes the stage
697/// declared, and the diagnostics that the call reports.
698///
699/// The runner creates one collector for each stage call and passes it to
700/// [`Stage::run`](crate::core::stage::Stage::run) together with the
701/// [`StageCx`](crate::core::run::StageCx). A stage writes here, never into the
702/// store; once the batch is over, the runner folds the collectors of every call
703/// of the stage into the store with [`fold_outs`].
704pub struct StageOut<'a> {
705    stage: &'a StageName,
706    writes: &'a WriteSet,
707    pieces: BTreeMap<TableId, Piece>,
708    /// The diagnostics that the stage call reports. The runner appends them
709    /// to the run's diagnostics in the order in which it folds the calls.
710    pub diags: FlmDiagnostics,
711}
712
713impl<'a> StageOut<'a> {
714    /// Creates a collector for one call of `stage`, checked against `writes`.
715    pub fn new(stage: &'a StageName, writes: &'a WriteSet) -> StageOut<'a> {
716        StageOut { stage, writes, pieces: BTreeMap::new(), diags: FlmDiagnostics::new() }
717    }
718
719    /// The stage whose writes this collector checks.
720    pub fn stage(&self) -> &'a StageName {
721        self.stage
722    }
723
724    /// Returns this call's table piece of a table that the stage declared as a
725    /// write. The table piece is created empty (the value type's `Default`)
726    /// on first access.
727    ///
728    /// # Errors
729    ///
730    /// [`AccessError::UndeclaredWrite`] if the stage did not declare a write of
731    /// this table; [`AccessError::TypeMismatch`] if `key`'s value type is not
732    /// the declared one.
733    pub fn table<K: TableKey>(&mut self, key: K) -> Result<&mut K::Table, AccessError> {
734        let key = key.table_ref();
735        let Some(entry) = self.writes.get(&key.name) else {
736            return Err(AccessError::UndeclaredWrite {
737                stage: self.stage.clone(),
738                table: key.name.clone(),
739                declared: self.writes.names(),
740            });
741        };
742        if entry.ty.type_id() != key.type_id {
743            return Err(AccessError::TypeMismatch {
744                stage: self.stage.clone(),
745                table: key.name.clone(),
746                declared: entry.ty.short_name(),
747                requested: key.short_type_name(),
748            });
749        }
750        let piece = self
751            .pieces
752            .entry(entry.id)
753            .or_insert_with(|| Piece { ty: entry.ty, table: entry.ty.make_default() });
754        Ok(piece
755            .table
756            .downcast_mut::<K::Table>()
757            .expect("a piece is created from its declared type, which the key matched"))
758    }
759
760    /// Returns this call's table piece of the one table of a value type `T`
761    /// that exactly one table uses ([`SingletonTable`]):
762    /// [`table`](StageOut::table) with the table name `T::NAME`.
763    ///
764    /// # Errors
765    ///
766    /// As for [`table`](StageOut::table).
767    pub fn table_singleton<T: SingletonTable>(&mut self) -> Result<&mut T, AccessError> {
768        self.table(T::table_name())
769    }
770
771    /// Whether this call produced a table piece of the table `id`, that is,
772    /// whether [`table`](StageOut::table) was called for it.
773    pub fn has_piece(&self, id: TableId) -> bool {
774        self.pieces.contains_key(&id)
775    }
776}
777
778impl fmt::Debug for StageOut<'_> {
779    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
780        f.debug_struct("StageOut")
781            .field("stage", self.stage)
782            .field("pieces", &self.pieces.keys().collect::<Vec<_>>())
783            .field("diags", &self.diags.len())
784            .finish()
785    }
786}
787
788/// Which store [`fold_outs`] installs the tables it folds into: the run's
789/// store, or the catch-up store of one value catch-up.
790#[derive(Debug, Clone, Copy, PartialEq, Eq)]
791pub enum FoldTarget {
792    /// The run's own store. Every declared write installs a table, an empty
793    /// one if the stage produced no table piece for it.
794    Main,
795    /// The catch-up store of one [value
796    /// catch-up](crate::guide::concepts_overview#value-catch-up). A table
797    /// piece that states a fact about the document as a whole is refused with
798    /// [`StoreError::DocumentFactInValue`]. A declared write without a table
799    /// piece still installs an empty table, so the catch-up store holds every
800    /// table that the stages run during the catch-up write, and a read of
801    /// such a table never falls through to the run's store.
802    Scratch,
803}
804
805/// Folds the collectors of one stage's calls into `store`.
806///
807/// The runner uses this function on both the sequential and the parallel path,
808/// so both produce identical results. The fold:
809///
810/// - keeps, for each table, the first table piece and absorbs the following
811///   ones into it ([`Table::absorb`]) in the order of `outs`; the runner passes
812///   the collectors in the run's order of the trees;
813/// - installs a table for each write the stage declared, an empty one when the
814///   stage produced no table piece for it;
815/// - installs the tables in [`TableId`] order;
816/// - appends the diagnostics of each collector to `diags`, in the order of
817///   `outs`.
818///
819/// `outs` must be collectors of calls of the stage that `writes` was resolved
820/// for.
821///
822/// # Errors
823///
824/// [`StoreError::SecondWriter`] if a table folded here is already present in
825/// `store`; [`StoreError::DocumentFactInValue`] if `target` is
826/// [`FoldTarget::Scratch`] and a table piece states a fact about the document
827/// as a whole. On an error, the tables before the refused one in [`TableId`]
828/// order are already installed.
829///
830/// [`Table::absorb`]: crate::core::data::table::Table::absorb
831///
832/// # Panics
833///
834/// Panics if a table piece's value is not of the value type that its write
835/// declaration gives. Neither [`StageOut`] nor the store can produce such a
836/// table piece.
837pub fn fold_outs(
838    stage: &StageName,
839    writes: &WriteSet,
840    outs: Vec<StageOut<'_>>,
841    target: FoldTarget,
842    store: &mut Computed,
843    diags: &mut FlmDiagnostics,
844) -> Result<(), StoreError> {
845    let mut acc: BTreeMap<TableId, Piece> = BTreeMap::new();
846    for out in outs {
847        for (id, piece) in out.pieces {
848            match acc.get_mut(&id) {
849                Some(existing) => existing.ty.absorb(&mut existing.table, piece.table),
850                None => {
851                    acc.insert(id, piece);
852                }
853            }
854        }
855        for diagnostic in out.diags {
856            diags.push(diagnostic);
857        }
858    }
859    // Declared writes that produced no piece still install, empty.
860    for (_, entry) in writes.iter() {
861        acc.entry(entry.id)
862            .or_insert_with(|| Piece { ty: entry.ty, table: entry.ty.make_default() });
863    }
864    for (id, piece) in acc {
865        if target == FoldTarget::Scratch
866            && piece.ty.piece_class(piece.table.as_ref()) == PieceClass::DocumentFact
867        {
868            let table = writes
869                .iter()
870                .find(|(_, entry)| entry.id == id)
871                .map(|(name, _)| name.clone())
872                .unwrap_or_else(|| CapName::from(id.to_string()));
873            return Err(StoreError::DocumentFactInValue { stage: stage.clone(), table });
874        }
875        store.install(id, Arc::from(piece.table))?;
876    }
877    Ok(())
878}
879
880#[cfg(test)]
881mod tests {
882    use super::*;
883
884    #[derive(Debug, Default)]
885    struct Count(u32);
886
887    impl Table for Count {
888        fn absorb(&mut self, piece: Count) {
889            self.0 += piece.0;
890        }
891
892        fn piece_class(&self) -> PieceClass {
893            if self.0 == 0 { PieceClass::Empty } else { PieceClass::DocumentFact }
894        }
895    }
896
897    impl SingletonTable for Count {
898        const NAME: &'static str = "test.count";
899    }
900
901    fn writes() -> WriteSet {
902        let mut writes = WriteSet::new();
903        writes.insert(
904            "test.count".into(),
905            WriteEntry { id: TableId(3), ty: TableType::of::<Count>() },
906        );
907        writes
908    }
909
910    fn reads(optional: bool) -> ReadSet {
911        let mut reads = ReadSet::new();
912        reads.insert(
913            "test.count".into(),
914            ReadEntry {
915                id: TableId(3),
916                ty: TableType::of::<Count>(),
917                optional,
918                producer: Some("s".into()),
919            },
920        );
921        reads
922    }
923
924    #[test]
925    fn pieces_absorb_in_the_order_given_and_install_once() {
926        let stage: StageName = "s".into();
927        let writes = writes();
928        let mut first = StageOut::new(&stage, &writes);
929        first.table_singleton::<Count>().unwrap().0 = 1;
930        let mut second = StageOut::new(&stage, &writes);
931        second.table_singleton::<Count>().unwrap().0 = 2;
932        let mut store = Computed::new();
933        let mut diags = FlmDiagnostics::new();
934        fold_outs(&stage, &writes, vec![first, second], FoldTarget::Main, &mut store, &mut diags)
935            .unwrap();
936        assert_eq!(store.get_as::<Count>(TableId(3)).unwrap().0, 3);
937        let empty = StageOut::new(&stage, &writes);
938        let error =
939            fold_outs(&stage, &writes, vec![empty], FoldTarget::Main, &mut store, &mut diags)
940                .unwrap_err();
941        assert_eq!(error, StoreError::SecondWriter { table: TableId(3) });
942    }
943
944    #[test]
945    fn a_declared_write_without_a_piece_installs_empty() {
946        let stage: StageName = "s".into();
947        let writes = writes();
948        let mut store = Computed::new();
949        let mut diags = FlmDiagnostics::new();
950        fold_outs(&stage, &writes, Vec::new(), FoldTarget::Main, &mut store, &mut diags).unwrap();
951        assert_eq!(store.get_as::<Count>(TableId(3)).unwrap().0, 0);
952    }
953
954    #[test]
955    fn an_undeclared_write_is_a_typed_error_naming_stage_and_table() {
956        let stage: StageName = "s".into();
957        let writes = WriteSet::new();
958        let mut out = StageOut::new(&stage, &writes);
959        let error = out.table_singleton::<Count>().unwrap_err();
960        assert!(
961            matches!(error, AccessError::UndeclaredWrite { ref table, .. } if table == "test.count")
962        );
963    }
964
965    #[test]
966    fn an_undeclared_read_is_a_typed_error_never_a_silent_none() {
967        let stage: StageName = "s".into();
968        let reads = ReadSet::new();
969        let store = Computed::new();
970        let view = ComputedView::new(&stage, &reads, &store);
971        let error = view.get_singleton::<Count>().unwrap_err();
972        assert!(
973            matches!(error, AccessError::UndeclaredRead { ref table, .. } if table == "test.count")
974        );
975    }
976
977    #[test]
978    fn a_declared_read_of_an_absent_table_is_none() {
979        let stage: StageName = "s".into();
980        let reads = reads(true);
981        let store = Computed::new();
982        let view = ComputedView::new(&stage, &reads, &store);
983        assert!(view.get_singleton::<Count>().unwrap().is_none());
984    }
985
986    #[test]
987    fn the_overlay_is_read_before_the_main_store() {
988        let stage: StageName = "s".into();
989        let reads = reads(false);
990        let mut main = Computed::new();
991        main.install(TableId(3), Arc::new(Count(1))).unwrap();
992        let mut scratch = Computed::new();
993        scratch.install(TableId(3), Arc::new(Count(7))).unwrap();
994        let plain = ComputedView::new(&stage, &reads, &main);
995        assert_eq!(plain.get_singleton::<Count>().unwrap().unwrap().0, 1);
996        assert_eq!(plain.with_overlay(&scratch).get_singleton::<Count>().unwrap().unwrap().0, 7);
997    }
998
999    #[test]
1000    fn a_document_fact_piece_is_refused_in_scratch() {
1001        let stage: StageName = "s".into();
1002        let writes = writes();
1003        let mut out = StageOut::new(&stage, &writes);
1004        out.table_singleton::<Count>().unwrap().0 = 1;
1005        let mut scratch = Computed::new();
1006        let mut diags = FlmDiagnostics::new();
1007        let error =
1008            fold_outs(&stage, &writes, vec![out], FoldTarget::Scratch, &mut scratch, &mut diags)
1009                .unwrap_err();
1010        assert!(
1011            matches!(
1012                error,
1013                StoreError::DocumentFactInValue { ref table, .. } if table == "test.count"
1014            )
1015        );
1016    }
1017
1018    #[test]
1019    fn a_cloned_version_shares_its_tables() {
1020        let mut store = Computed::new();
1021        store.install(TableId(0), Arc::new(Count(4))).unwrap();
1022        let version = store.clone();
1023        assert!(Arc::ptr_eq(
1024            store.get_erased(TableId(0)).unwrap(),
1025            version.get_erased(TableId(0)).unwrap()
1026        ));
1027    }
1028}