use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;
use super::{AggregateModel, Measure, Measured, Owed};
use crate::{
emit::{framework, leading},
model::RecordModel,
};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone)]
pub struct Mounted {
pub record: RecordModel,
pub aggregate: AggregateModel,
}
impl Mounted {
#[must_use]
pub fn emit(&self) -> TokenStream {
let record = self.record.emit();
let fold = self.aggregate.fold();
quote! {
#record
#fold
}
}
}
impl AggregateModel {
pub(crate) fn fold(&self) -> TokenStream {
let (aggregate, vis) = (&self.aggregate, &self.vis);
let upstream = &self.upstream;
let measure = framework(&self.krate, &["measure"], "Measure");
let held = quote!(::std::vec::Vec<&#upstream>);
let key_types = self.groups.iter().map(|grouped| &grouped.ty);
let key_reads = self
.groups
.iter()
.map(|grouped| read(upstream, &grouped.from));
let key_binds: Vec<&syn::Ident> = self.groups.iter().map(|grouped| &grouped.field).collect();
let filled = self
.measures
.iter()
.map(|measured| self.measured(measured, &measure));
let doc = leading(&format!(
"Fold every row `{upstream}` holds into one [`{aggregate}`] per group.",
upstream = path_text(upstream),
));
let whole = leading(
"The recompute's ARITHMETIC, and the recompute is WHOLE: it consumes the upstream's rows as a \
TABLE rather than as messages, so running it twice over one table state writes the same rows \
to the same addresses, and a row the upstream no longer holds simply stops being counted. \
Duplicate delivery cannot reach it and deletion needs no retraction — both fall out of the \
shape rather than being checked.",
);
let ends = leading(&format!(
"The two ENDS are the record machinery's, reached rather than restated: read the upstream's \
table with its own `find_<db>(…).fetch()`, hand the rows here, and write each answer back \
through [`{aggregate}`]'s `upsert_<db>`, whose KEYED REPLACE is what makes running this on \
every tick safe."
));
let ordering = leading(
"The rows come back in FIRST-SEEN group order — the order the upstream's rows presented the \
groups in — which is not a sort and is not promised to be one: a caller that wants an order \
reads the table back through the query lane, where an order is written.",
);
quote! {
impl #aggregate {
#[doc = #doc]
#[doc = ""]
#[doc = #whole]
#[doc = ""]
#[doc = #ends]
#[doc = ""]
#[doc = #ordering]
#[must_use]
#[allow(clippy::clone_on_copy)]
#vis fn fold(__ig_rows: &[#upstream]) -> ::std::vec::Vec<Self> {
let mut __ig_groups: ::std::vec::Vec<((#(#key_types,)*), #held)> =
::std::vec::Vec::new();
for __ig_row in __ig_rows {
let __ig_key = (#(#key_reads,)*);
match __ig_groups
.iter_mut()
.find(|(__ig_seen, _)| *__ig_seen == __ig_key)
{
::core::option::Option::Some((_, __ig_held)) => __ig_held.push(__ig_row),
::core::option::Option::None => {
let mut __ig_first: #held = ::std::vec::Vec::new();
__ig_first.push(__ig_row);
__ig_groups.push((__ig_key, __ig_first));
}
}
}
__ig_groups
.into_iter()
.map(|((#(#key_binds,)*), __ig_held)| Self {
#(#key_binds,)*
#(#filled)*
})
.collect()
}
}
}
}
fn measured(&self, measured: &Measured, measure: &TokenStream) -> TokenStream {
let field = &measured.field;
let at = field.span();
let fold = self.citizen(&measured.by);
let built = quote_spanned!(at=> <#fold as ::core::default::Default>::default());
let upstream = &self.upstream;
let value = match (measured.by.owed(), measured.from.as_ref()) {
(Owed::Column | Owed::Theirs, Some(from)) => {
let read = read(upstream, from);
quote_spanned! {from.span()=>
{
let __ig_column: ::std::vec::Vec<_> = __ig_held
.iter()
.map(|__ig_row| #read)
.collect();
<#fold as #measure<_>>::fold(&#built, &__ig_column)
}
}
}
(Owed::Nothing | Owed::Theirs, _) => {
quote_spanned!(at=> <#fold as #measure<&#upstream>>::fold(&#built, &__ig_held))
}
(Owed::Column, None) => {
quote_spanned!(at=> <#fold as #measure<&#upstream>>::fold(&#built, &__ig_held))
}
};
quote_spanned!(at=> #field: #value,)
}
fn citizen(&self, by: &Measure) -> TokenStream {
match by {
Measure::Counting => framework(&self.krate, &["measure"], "Counting"),
Measure::Summing => framework(&self.krate, &["measure"], "Summing"),
Measure::Declared(path) => quote_spanned!(path.span()=> #path),
}
}
}
fn read(upstream: &syn::Path, from: &syn::Ident) -> TokenStream {
let reader = format_ident!("{from}_ref", span = from.span());
quote_spanned!(from.span()=> ::core::clone::Clone::clone(#upstream::#reader(__ig_row)))
}
fn path_text(path: &syn::Path) -> String {
path
.segments
.iter()
.map(|segment| segment.ident.to_string())
.collect::<Vec<_>>()
.join("::")
}