use std::any::Any;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use crate::model::names::{CapName, StageName};
use crate::core::data::table::{
PieceClass, SingletonTable, Table, TableId, TableKey, TableRef, TableType,
};
use crate::lang::origin::FlmDiagnostics;
#[derive(Clone, Default)]
pub struct Computed {
tables: BTreeMap<TableId, Arc<dyn Any + Send + Sync>>,
}
impl Computed {
pub fn new() -> Computed {
Computed::default()
}
pub fn get_erased(&self, id: TableId) -> Option<&Arc<dyn Any + Send + Sync>> {
self.tables.get(&id)
}
pub fn get_as<T: Table>(&self, id: TableId) -> Option<&T> {
self.tables.get(&id).and_then(|table| table.downcast_ref::<T>())
}
pub fn contains(&self, id: TableId) -> bool {
self.tables.contains_key(&id)
}
pub fn ids(&self) -> impl Iterator<Item = TableId> + '_ {
self.tables.keys().copied()
}
pub fn len(&self) -> usize {
self.tables.len()
}
pub fn is_empty(&self) -> bool {
self.tables.is_empty()
}
pub fn install(
&mut self,
id: TableId,
table: Arc<dyn Any + Send + Sync>,
) -> Result<(), StoreError> {
if self.tables.contains_key(&id) {
return Err(StoreError::SecondWriter { table: id });
}
self.tables.insert(id, table);
Ok(())
}
}
impl fmt::Debug for Computed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.tables.keys()).finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoreError {
SecondWriter {
table: TableId,
},
DocumentFactInValue {
stage: StageName,
table: CapName,
},
}
impl fmt::Display for StoreError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StoreError::SecondWriter { table } => {
write!(f, "{table} is already installed: a table can be installed only once")
}
StoreError::DocumentFactInValue { stage, table } => write!(
f,
"stage `{stage}`, run over content generated during processing, wrote data \
about the whole document into table `{table}`; generated content must not \
add data about the whole document"
),
}
}
}
impl std::error::Error for StoreError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessError {
UndeclaredRead {
stage: StageName,
table: CapName,
declared: Vec<CapName>,
},
UndeclaredWrite {
stage: StageName,
table: CapName,
declared: Vec<CapName>,
},
TypeMismatch {
stage: StageName,
table: CapName,
declared: &'static str,
requested: &'static str,
},
}
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AccessError::UndeclaredRead { stage, table, declared } => write!(
f,
"stage `{stage}` reads table `{table}` without declaring it; declared reads: \
[{}]",
join_names(declared)
),
AccessError::UndeclaredWrite { stage, table, declared } => write!(
f,
"stage `{stage}` writes table `{table}` without declaring it; declared writes: \
[{}]",
join_names(declared)
),
AccessError::TypeMismatch { stage, table, declared, requested } => write!(
f,
"stage `{stage}` accesses table `{table}` with value type `{requested}`, but the \
table is declared with value type `{declared}`"
),
}
}
}
impl std::error::Error for AccessError {}
fn join_names(names: &[CapName]) -> String {
names.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
}
#[derive(Debug, Clone)]
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct ReadEntry {
pub id: TableId,
#[serde(skip)]
pub ty: TableType,
pub optional: bool,
pub producer: Option<StageName>,
}
#[derive(Debug, Clone, Default)]
#[derive(serde::Serialize, schemars::JsonSchema)]
#[serde(transparent)]
pub struct ReadSet {
entries: BTreeMap<CapName, ReadEntry>,
}
impl ReadSet {
pub fn new() -> ReadSet {
ReadSet::default()
}
pub fn insert(&mut self, name: CapName, entry: ReadEntry) {
self.entries.insert(name, entry);
}
pub fn get(&self, name: &str) -> Option<&ReadEntry> {
self.entries.get(name)
}
pub fn names(&self) -> Vec<CapName> {
self.entries.keys().cloned().collect()
}
pub fn iter(&self) -> impl Iterator<Item = (&CapName, &ReadEntry)> + '_ {
self.entries.iter()
}
}
#[derive(Debug, Clone)]
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct WriteEntry {
pub id: TableId,
#[serde(skip)]
pub ty: TableType,
}
#[derive(Debug, Clone, Default)]
#[derive(serde::Serialize, schemars::JsonSchema)]
#[serde(transparent)]
pub struct WriteSet {
entries: BTreeMap<CapName, WriteEntry>,
}
impl WriteSet {
pub fn new() -> WriteSet {
WriteSet::default()
}
pub fn insert(&mut self, name: CapName, entry: WriteEntry) {
self.entries.insert(name, entry);
}
pub fn get(&self, name: &str) -> Option<&WriteEntry> {
self.entries.get(name)
}
pub fn names(&self) -> Vec<CapName> {
self.entries.keys().cloned().collect()
}
pub fn iter(&self) -> impl Iterator<Item = (&CapName, &WriteEntry)> + '_ {
self.entries.iter()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
#[derive(Clone, Copy)]
pub struct ComputedView<'a> {
stage: &'a StageName,
reads: &'a ReadSet,
store: &'a Computed,
overlay: Option<&'a Computed>,
}
impl<'a> ComputedView<'a> {
pub fn new(stage: &'a StageName, reads: &'a ReadSet, store: &'a Computed) -> ComputedView<'a> {
ComputedView { stage, reads, store, overlay: None }
}
pub fn with_overlay(self, overlay: &'a Computed) -> ComputedView<'a> {
ComputedView { overlay: Some(overlay), ..self }
}
pub fn stage(&self) -> &'a StageName {
self.stage
}
pub fn reads(&self) -> &'a ReadSet {
self.reads
}
fn entry(&self, key: &TableRef) -> Result<&'a ReadEntry, AccessError> {
let Some(entry) = self.reads.get(&key.name) else {
return Err(AccessError::UndeclaredRead {
stage: self.stage.clone(),
table: key.name.clone(),
declared: self.reads.names(),
});
};
if entry.ty.type_id() != key.type_id {
return Err(AccessError::TypeMismatch {
stage: self.stage.clone(),
table: key.name.clone(),
declared: entry.ty.short_name(),
requested: key.short_type_name(),
});
}
Ok(entry)
}
fn lookup(&self, id: TableId) -> Option<&'a Arc<dyn Any + Send + Sync>> {
self.overlay
.and_then(|overlay| overlay.get_erased(id))
.or_else(|| self.store.get_erased(id))
}
pub fn get<K: TableKey>(&self, key: K) -> Result<Option<&'a K::Table>, AccessError> {
let entry = self.entry(&key.table_ref())?;
Ok(self.lookup(entry.id).map(|table| {
table
.downcast_ref::<K::Table>()
.expect("a table is stored under its declared type, which the key matched")
}))
}
pub fn get_singleton<T: SingletonTable>(&self) -> Result<Option<&'a T>, AccessError> {
self.get(T::table_name())
}
pub fn get_erased(
&self,
name: &str,
) -> Result<Option<&'a Arc<dyn Any + Send + Sync>>, AccessError> {
let Some(entry) = self.reads.get(name) else {
return Err(AccessError::UndeclaredRead {
stage: self.stage.clone(),
table: CapName::from(name),
declared: self.reads.names(),
});
};
Ok(self.lookup(entry.id))
}
pub fn producer_of(&self, name: &str) -> Option<&'a StageName> {
self.reads.get(name).and_then(|entry| entry.producer.as_ref())
}
}
impl fmt::Debug for ComputedView<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ComputedView")
.field("stage", self.stage)
.field("reads", &self.reads.names())
.field("overlay", &self.overlay.is_some())
.finish()
}
}
struct Piece {
ty: TableType,
table: Box<dyn Any + Send + Sync>,
}
pub struct StageOut<'a> {
stage: &'a StageName,
writes: &'a WriteSet,
pieces: BTreeMap<TableId, Piece>,
pub diags: FlmDiagnostics,
}
impl<'a> StageOut<'a> {
pub fn new(stage: &'a StageName, writes: &'a WriteSet) -> StageOut<'a> {
StageOut { stage, writes, pieces: BTreeMap::new(), diags: FlmDiagnostics::new() }
}
pub fn stage(&self) -> &'a StageName {
self.stage
}
pub fn table<K: TableKey>(&mut self, key: K) -> Result<&mut K::Table, AccessError> {
let key = key.table_ref();
let Some(entry) = self.writes.get(&key.name) else {
return Err(AccessError::UndeclaredWrite {
stage: self.stage.clone(),
table: key.name.clone(),
declared: self.writes.names(),
});
};
if entry.ty.type_id() != key.type_id {
return Err(AccessError::TypeMismatch {
stage: self.stage.clone(),
table: key.name.clone(),
declared: entry.ty.short_name(),
requested: key.short_type_name(),
});
}
let piece = self
.pieces
.entry(entry.id)
.or_insert_with(|| Piece { ty: entry.ty, table: entry.ty.make_default() });
Ok(piece
.table
.downcast_mut::<K::Table>()
.expect("a piece is created from its declared type, which the key matched"))
}
pub fn table_singleton<T: SingletonTable>(&mut self) -> Result<&mut T, AccessError> {
self.table(T::table_name())
}
pub fn has_piece(&self, id: TableId) -> bool {
self.pieces.contains_key(&id)
}
}
impl fmt::Debug for StageOut<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StageOut")
.field("stage", self.stage)
.field("pieces", &self.pieces.keys().collect::<Vec<_>>())
.field("diags", &self.diags.len())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FoldTarget {
Main,
Scratch,
}
pub fn fold_outs(
stage: &StageName,
writes: &WriteSet,
outs: Vec<StageOut<'_>>,
target: FoldTarget,
store: &mut Computed,
diags: &mut FlmDiagnostics,
) -> Result<(), StoreError> {
let mut acc: BTreeMap<TableId, Piece> = BTreeMap::new();
for out in outs {
for (id, piece) in out.pieces {
match acc.get_mut(&id) {
Some(existing) => existing.ty.absorb(&mut existing.table, piece.table),
None => {
acc.insert(id, piece);
}
}
}
for diagnostic in out.diags {
diags.push(diagnostic);
}
}
for (_, entry) in writes.iter() {
acc.entry(entry.id)
.or_insert_with(|| Piece { ty: entry.ty, table: entry.ty.make_default() });
}
for (id, piece) in acc {
if target == FoldTarget::Scratch
&& piece.ty.piece_class(piece.table.as_ref()) == PieceClass::DocumentFact
{
let table = writes
.iter()
.find(|(_, entry)| entry.id == id)
.map(|(name, _)| name.clone())
.unwrap_or_else(|| CapName::from(id.to_string()));
return Err(StoreError::DocumentFactInValue { stage: stage.clone(), table });
}
store.install(id, Arc::from(piece.table))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Default)]
struct Count(u32);
impl Table for Count {
fn absorb(&mut self, piece: Count) {
self.0 += piece.0;
}
fn piece_class(&self) -> PieceClass {
if self.0 == 0 { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
impl SingletonTable for Count {
const NAME: &'static str = "test.count";
}
fn writes() -> WriteSet {
let mut writes = WriteSet::new();
writes.insert(
"test.count".into(),
WriteEntry { id: TableId(3), ty: TableType::of::<Count>() },
);
writes
}
fn reads(optional: bool) -> ReadSet {
let mut reads = ReadSet::new();
reads.insert(
"test.count".into(),
ReadEntry {
id: TableId(3),
ty: TableType::of::<Count>(),
optional,
producer: Some("s".into()),
},
);
reads
}
#[test]
fn pieces_absorb_in_the_order_given_and_install_once() {
let stage: StageName = "s".into();
let writes = writes();
let mut first = StageOut::new(&stage, &writes);
first.table_singleton::<Count>().unwrap().0 = 1;
let mut second = StageOut::new(&stage, &writes);
second.table_singleton::<Count>().unwrap().0 = 2;
let mut store = Computed::new();
let mut diags = FlmDiagnostics::new();
fold_outs(&stage, &writes, vec![first, second], FoldTarget::Main, &mut store, &mut diags)
.unwrap();
assert_eq!(store.get_as::<Count>(TableId(3)).unwrap().0, 3);
let empty = StageOut::new(&stage, &writes);
let error =
fold_outs(&stage, &writes, vec![empty], FoldTarget::Main, &mut store, &mut diags)
.unwrap_err();
assert_eq!(error, StoreError::SecondWriter { table: TableId(3) });
}
#[test]
fn a_declared_write_without_a_piece_installs_empty() {
let stage: StageName = "s".into();
let writes = writes();
let mut store = Computed::new();
let mut diags = FlmDiagnostics::new();
fold_outs(&stage, &writes, Vec::new(), FoldTarget::Main, &mut store, &mut diags).unwrap();
assert_eq!(store.get_as::<Count>(TableId(3)).unwrap().0, 0);
}
#[test]
fn an_undeclared_write_is_a_typed_error_naming_stage_and_table() {
let stage: StageName = "s".into();
let writes = WriteSet::new();
let mut out = StageOut::new(&stage, &writes);
let error = out.table_singleton::<Count>().unwrap_err();
assert!(
matches!(error, AccessError::UndeclaredWrite { ref table, .. } if table == "test.count")
);
}
#[test]
fn an_undeclared_read_is_a_typed_error_never_a_silent_none() {
let stage: StageName = "s".into();
let reads = ReadSet::new();
let store = Computed::new();
let view = ComputedView::new(&stage, &reads, &store);
let error = view.get_singleton::<Count>().unwrap_err();
assert!(
matches!(error, AccessError::UndeclaredRead { ref table, .. } if table == "test.count")
);
}
#[test]
fn a_declared_read_of_an_absent_table_is_none() {
let stage: StageName = "s".into();
let reads = reads(true);
let store = Computed::new();
let view = ComputedView::new(&stage, &reads, &store);
assert!(view.get_singleton::<Count>().unwrap().is_none());
}
#[test]
fn the_overlay_is_read_before_the_main_store() {
let stage: StageName = "s".into();
let reads = reads(false);
let mut main = Computed::new();
main.install(TableId(3), Arc::new(Count(1))).unwrap();
let mut scratch = Computed::new();
scratch.install(TableId(3), Arc::new(Count(7))).unwrap();
let plain = ComputedView::new(&stage, &reads, &main);
assert_eq!(plain.get_singleton::<Count>().unwrap().unwrap().0, 1);
assert_eq!(plain.with_overlay(&scratch).get_singleton::<Count>().unwrap().unwrap().0, 7);
}
#[test]
fn a_document_fact_piece_is_refused_in_scratch() {
let stage: StageName = "s".into();
let writes = writes();
let mut out = StageOut::new(&stage, &writes);
out.table_singleton::<Count>().unwrap().0 = 1;
let mut scratch = Computed::new();
let mut diags = FlmDiagnostics::new();
let error =
fold_outs(&stage, &writes, vec![out], FoldTarget::Scratch, &mut scratch, &mut diags)
.unwrap_err();
assert!(
matches!(
error,
StoreError::DocumentFactInValue { ref table, .. } if table == "test.count"
)
);
}
#[test]
fn a_cloned_version_shares_its_tables() {
let mut store = Computed::new();
store.install(TableId(0), Arc::new(Count(4))).unwrap();
let version = store.clone();
assert!(Arc::ptr_eq(
store.get_erased(TableId(0)).unwrap(),
version.get_erased(TableId(0)).unwrap()
));
}
}