flm_core/core/run/externals.rs
1//! External tables, the values that a caller installs into them when it
2//! constructs a run, and the stamp that records what such a value was produced
3//! under.
4//!
5//! An external table is a table that no stage of the run writes: the caller
6//! installs its value when the run is constructed ([`Externals`]). External
7//! tables bring data from outside one document into the stages of a run, for
8//! example an index of the labels defined in the other documents of a
9//! collection, so that references between the documents resolve. A feature
10//! declares an external table with
11//! [`FeatureBuilder::external_table`](crate::core::registry::FeatureBuilder::external_table);
12//! [`FlmRegistry::external_tables`](crate::core::registry::FlmRegistry::external_tables)
13//! lists those a registry declares, and
14//! [`Plan::externals`](crate::core::plan::Plan::externals) those a plan needs.
15//!
16//! The installed values are inputs of the run and do not change during its
17//! lifetime. [`Run::new`](crate::core::run::Run::new) refuses to construct a run
18//! when a value is missing for an external table that the plan needs, when an
19//! install refers to a table that the registry does not declare or does not
20//! declare as external, when a value is not of the table's declared type, or when a value's
21//! stamp differs from the run's own (see [`RunError`](crate::core::run::RunError)).
22//!
23//! # Stamps
24//!
25//! A value that an earlier run of this library produced can carry a [`Stamp`]:
26//! the digest of the registry it was produced under
27//! ([`crate::model::digest`]), the rewrite stages that ran, and a digest of the
28//! values of the options those rewrite stages read.
29//! [`Run::new`](crate::core::run::Run::new) compares the stamp of each
30//! installed value with the stamp of the run being constructed and refuses a
31//! mismatch, so that a run never uses data computed under another registry,
32//! other rewrite stages or other option values.
33//!
34//! Data that did not come from a run of this library has no stamp, and is
35//! installed with [`Externals::install_unstamped`]. Nothing then checks that it
36//! agrees with the document; the caller is responsible for that.
37//!
38//! See [external tables and two-run
39//! composition](crate::guide::embedding#external-tables-and-two-run-composition)
40//! for how an embedding program uses them.
41
42use std::any::Any;
43use std::collections::BTreeMap;
44use std::fmt;
45use std::sync::Arc;
46
47use crate::model::names::{CapName, StageName};
48use crate::core::data::table::{TableKey, TableRef};
49
50/// A record of what a value produced by a run of this library was produced
51/// under: the registry digest, the rewrite stages that ran, and a digest of
52/// the option values that those rewrite stages read.
53///
54/// Two runs with equal stamps read a document the same way: the same registry,
55/// the same rewrite stages in the same order, and the same values for the
56/// options those rewrite stages read, so they produce the same frozen trees
57/// from the same document. A value whose stamp equals a run's own stamp
58/// ([`Run::stamp`](crate::core::run::Run::stamp)) is therefore data that the
59/// run could have computed itself. Install such a value with
60/// [`Externals::install`]; [`Run::new`](crate::core::run::Run::new) refuses it
61/// with [`RunError::StampMismatch`](crate::core::run::RunError::StampMismatch)
62/// when the stamps differ.
63///
64/// Its `Display` form lists the three parts, the two digests in hexadecimal.
65#[derive(Debug, Clone, PartialEq, Eq, Hash)]
66pub struct Stamp {
67 /// The digest of the registry that the value was produced under
68 /// ([`crate::model::digest`]).
69 pub digest: u64,
70 /// The rewrite stages that ran, in the order in which they ran.
71 pub active_rewrites: Vec<StageName>,
72 /// A digest of the values of every option that those rewrite stages
73 /// read.
74 pub option_reads: u64,
75}
76
77impl fmt::Display for Stamp {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 write!(
80 f,
81 "registry digest {:016x}, rewrite stages [{}], digest of the option values they \
82 read {:016x}",
83 self.digest,
84 self.active_rewrites.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", "),
85 self.option_reads
86 )
87 }
88}
89
90/// One value installed into one external table, with the value's stamp.
91///
92/// [`Externals`] holds one `Install` for each table, and
93/// [`Run::new`](crate::core::run::Run::new) checks it.
94pub struct Install {
95 /// The table that the value is installed into, with the value type that
96 /// the value was installed as.
97 pub table: TableRef,
98 /// The value, type-erased. [`Run::new`](crate::core::run::Run::new)
99 /// checks its type against the table's declaration.
100 pub value: Arc<dyn Any + Send + Sync>,
101 /// What the value was produced under, or `None` when it did not come from
102 /// a run of this library.
103 pub stamp: Option<Stamp>,
104}
105
106impl fmt::Debug for Install {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 f.debug_struct("Install").field("table", &self.table).field("stamp", &self.stamp).finish()
109 }
110}
111
112/// The values that a caller installs into a run's external tables, by table
113/// name.
114///
115/// An external table is a table that no stage of the run writes: the caller
116/// installs its value when the run is constructed. See the [module
117/// documentation](self) for what external tables are for and for the checks
118/// that [`Run::new`](crate::core::run::Run::new) performs.
119///
120/// Create an empty set with [`Externals::none`], add values with
121/// [`Externals::install`] (a value produced by a run of this library, with its
122/// [`Stamp`]) or [`Externals::install_unstamped`] (any other value), and pass
123/// the set to [`Run::new`](crate::core::run::Run::new). Installing twice into
124/// one table keeps the later value.
125///
126/// # Examples
127///
128/// ```
129/// use flm_core::core::run::Externals;
130/// use flm_core::core::data::table::{Table, TableName};
131///
132/// #[derive(Debug, Default)]
133/// struct KnownLabels(Vec<String>);
134///
135/// impl Table for KnownLabels {
136/// fn absorb(&mut self, piece: KnownLabels) {
137/// self.0.extend(piece.0);
138/// }
139/// }
140///
141/// const KNOWN: TableName<KnownLabels> = TableName::new("example.known-labels");
142///
143/// // Data from outside this library: nothing checks it against the document.
144/// let externals = Externals::none()
145/// .install_unstamped(KNOWN, KnownLabels(vec!["thm:main".to_string()]));
146///
147/// assert_eq!(externals.len(), 1);
148/// assert!(externals.get("example.known-labels").is_some());
149/// ```
150#[derive(Debug, Default)]
151pub struct Externals {
152 installs: BTreeMap<CapName, Install>,
153}
154
155impl Externals {
156 /// Creates an empty set: no value installed.
157 pub fn none() -> Externals {
158 Externals::default()
159 }
160
161 /// Installs `value`, produced by an earlier run of this library, into the
162 /// external table of `key`, with the stamp that run returned
163 /// ([`Run::stamp`](crate::core::run::Run::stamp)).
164 ///
165 /// [`Run::new`](crate::core::run::Run::new) compares `stamp` with the
166 /// stamp of the run being constructed and refuses a mismatch. Use
167 /// [`Externals::install_unstamped`] for data that did not come from a run
168 /// of this library.
169 ///
170 /// `value` is taken by value. [`Run::table`](crate::core::run::Run::table)
171 /// returns a reference, so a value read from another run is passed as an
172 /// owned copy, for example a clone of it or a value rebuilt from it.
173 pub fn install<K: TableKey>(mut self, key: K, value: K::Table, stamp: Stamp) -> Externals {
174 let table = key.table_ref();
175 self.installs.insert(
176 table.name.clone(),
177 Install { table, value: Arc::new(value), stamp: Some(stamp) },
178 );
179 self
180 }
181
182 /// Installs `value`, which did not come from a run of this library, into
183 /// the external table of `key`.
184 ///
185 /// Nothing checks that it agrees with the document being processed; the
186 /// caller is responsible for that.
187 pub fn install_unstamped<K: TableKey>(mut self, key: K, value: K::Table) -> Externals {
188 let table = key.table_ref();
189 self.installs
190 .insert(table.name.clone(), Install { table, value: Arc::new(value), stamp: None });
191 self
192 }
193
194 /// Returns the install of the table `name`, if a value is installed.
195 pub fn get(&self, name: &str) -> Option<&Install> {
196 self.installs.get(name)
197 }
198
199 /// Every install, in table-name order.
200 pub fn iter(&self) -> impl Iterator<Item = (&CapName, &Install)> + '_ {
201 self.installs.iter()
202 }
203
204 /// The number of tables that have an installed value.
205 pub fn len(&self) -> usize {
206 self.installs.len()
207 }
208
209 /// Whether no value is installed.
210 pub fn is_empty(&self) -> bool {
211 self.installs.is_empty()
212 }
213}