use ingraph_codegen::{
aggregate::{AggregateModel, GROUP, Grouped, MEASURE, Measure, Measured, Mounted, Owed},
model::{DatabaseKind, NodeKind, Projection, borrowed_key},
prefix::EmissionPrefix,
};
use crate::{
alias,
attribute::{self, named, set_once},
column,
errors::Errors,
parse::{database_kind, owns_one_storage, shipped},
suggest, value,
};
#[cfg(test)]
mod tests;
const KIND: NodeKind = NodeKind::Aggregate;
const UPSTREAM: &str = "upstream";
const NODE: &str = "node";
const FOLD: &str = "fold";
const FROM: &str = "from";
const POLL: &str = "poll";
const GRAPHQL: &str = "graphql";
const TABLE: &str = "table";
const RENAME: &str = "rename";
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
) -> syn::Result<AggregateModel> {
let aggregate = &input.ident;
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let head = options(arguments, &mut errors);
concrete(&input.generics, &mut errors);
let fields = match named_fields(input) {
Ok(fields) => fields,
Err(terminal) => return Err(errors.seal(terminal)),
};
if fields.named.is_empty() {
errors.push(syn::Error::new_spanned(aggregate, NO_FIELDS));
}
let mut columns: Vec<Field> = Vec::new();
for field in &fields.named {
let Some(name) = field.ident.clone() else {
continue;
};
if name == borrowed_key(&EmissionPrefix::default()) {
errors.push(syn::Error::new_spanned(
&name,
format!(
"this declaration already carries a storage macro's injected key, so a second storage \
macro is being asked to fold a row that has one. {}",
owns_one_storage(KIND),
),
));
continue;
}
column::refuse_framework_namespace(&alias::Fence::default(), &name, &mut errors);
if name == FOLD {
errors.push(syn::Error::new_spanned(&name, mints_a_fold()));
}
let (projection, role, role_spoken) = markers(&field.attrs, &name, &mut errors);
columns.push(Field {
role,
role_spoken,
projection,
ty: field.ty.clone(),
name,
});
}
let Some(at) = head.upstream_at else {
return Err(match head.whole {
true => errors.seal(syn::Error::new_spanned(aggregate, NO_UPSTREAM)),
false => errors.stopped(syn::Error::new_spanned(aggregate, UNREADABLE_HEAD)),
});
};
let groups = grouped(
&head.groups,
head.group_at.as_ref(),
head.whole,
&columns,
aggregate,
&mut errors,
);
let measures = measured(
&head.measures,
head.measure_at.as_ref(),
head.whole,
&columns,
aggregate,
&mut errors,
);
unmatched(
&columns,
&head.group_spoken,
&head.measure_spoken,
head.whole,
&mut errors,
);
if head.whole && !head.polled {
errors.push(syn::Error::new_spanned(aggregate, NO_TRIGGER));
}
let Some(node) = head.node else {
return Err(match head.whole {
true => errors.seal(syn::Error::new_spanned(&at, UPSTREAM_TAKES_A_NODE)),
false => errors.stopped(syn::Error::new_spanned(aggregate, UNREADABLE_HEAD)),
});
};
errors.into_result(AggregateModel {
aggregate: aggregate.clone(),
vis: input.vis.clone(),
krate: head.krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
krate_spelled: head.krate_spelled,
upstream: node,
groups,
measures,
triggers: head.triggers,
stores: head.stores,
graphql: head.graphql,
})
}
pub(crate) fn mount(input: &syn::DeriveInput, aggregate: AggregateModel) -> syn::Result<Mounted> {
let host = mounted(input, &aggregate);
let record = crate::parse::parse(&host, &[record_options(&aggregate)], KIND)?;
Ok(Mounted { record, aggregate })
}
fn mounted(input: &syn::DeriveInput, model: &AggregateModel) -> syn::DeriveInput {
let key = model.groups.last().map(|grouped| &grouped.field);
let mut host = input.clone();
host.attrs.retain(|attr| !attr.path().is_ident("ingraph"));
let syn::Data::Struct(data) = &mut host.data else {
return host;
};
for field in &mut data.fields {
field.attrs.retain(|attr| !attr.path().is_ident("ingraph"));
let Some(name) = field.ident.clone() else {
continue;
};
let mut words: Vec<syn::Ident> = Vec::new();
if key == Some(&name) {
words.push(syn::Ident::new("id", name.span()));
}
if let Some(word) = projection_word(model, &name) {
words.push(syn::Ident::new(word, name.span()));
}
if !words.is_empty() {
field.attrs.push(syn::parse_quote!(#[ingraph(#(#words),*)]));
}
}
host
}
fn projection_word(model: &AggregateModel, field: &syn::Ident) -> Option<&'static str> {
let projection = model
.groups
.iter()
.map(|grouped| (&grouped.field, grouped.projection))
.chain(
model
.measures
.iter()
.map(|measured| (&measured.field, measured.projection)),
)
.find_map(|(name, projection)| (name == field).then_some(projection))?;
match projection {
Projection::Borrowed => None,
Projection::Copied => Some("copy"),
Projection::Repeated => Some("repeated"),
Projection::Optional => Some("optional"),
}
}
fn record_options(model: &AggregateModel) -> syn::Attribute {
let mut written: Vec<proc_macro2::TokenStream> = Vec::new();
if let Some((_, steps)) = model
.groups
.split_last()
.filter(|(_, steps)| !steps.is_empty())
{
let steps = steps.iter().map(|grouped| &grouped.field);
written.push(quote::quote!(lineage(fields(#(#steps),*))));
}
if let Some(spelled) = &model.krate_spelled {
written.push(quote::quote!(crate = #spelled));
}
for carried in [&model.triggers, &model.stores] {
if !carried.is_empty() {
written.push(carried.clone());
}
}
if let Some(graphql) = &model.graphql {
written.push(graphql.clone());
}
syn::parse_quote!(#[ingraph(#(#written),*)])
}
pub(crate) fn wrong_kind(word: &str, kind: NodeKind, written: Written) -> String {
let what = if word == GROUP {
"which column a folded row is keyed by"
} else {
"how a group's rows are folded into one column"
};
let position = match written {
Written::AtTheHead => format!("`{word}(…)` says"),
Written::OnAField => format!("`{word}` marks this column as the one that says"),
};
format!(
"{position} {what}, and {article} {noun} folds nothing — it holds whatever it is given, row for \
row, so it has no group for a column to be about. The word is the `aggregate` kind's own, and \
an aggregate is its OWN node: declare it with `#[ingraph::aggregate(…)]`, on a type whose \
`upstream(…)` names this {noun}. Its rows are the folded ones and its key is the group columns \
it projects, so it borrows nothing from this declaration's",
article = kind.article(),
noun = kind.noun(),
)
}
#[derive(Clone, Copy)]
pub(crate) enum Written {
AtTheHead,
OnAField,
}
struct Field {
name: syn::Ident,
ty: syn::Type,
projection: ingraph_codegen::prelude::Projection,
role: Option<(Role, syn::Path)>,
role_spoken: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
Group,
Measure,
}
impl Role {
const fn word(self) -> &'static str {
match self {
Self::Group => GROUP,
Self::Measure => MEASURE,
}
}
const fn what(self) -> &'static str {
match self {
Self::Group => "a column the folded row is keyed by",
Self::Measure => "a column the fold fills",
}
}
}
struct Head {
krate: Option<syn::Path>,
krate_spelled: Option<syn::LitStr>,
node: Option<syn::Path>,
upstream_at: Option<syn::Path>,
groups: Vec<Entry<syn::Ident>>,
group_at: Option<syn::Path>,
group_spoken: Vec<syn::Ident>,
measures: Vec<Entry<Folded>>,
measure_at: Option<syn::Path>,
measure_spoken: Vec<syn::Ident>,
triggers: proc_macro2::TokenStream,
polled: bool,
stores: proc_macro2::TokenStream,
graphql: Option<proc_macro2::TokenStream>,
whole: bool,
}
impl Default for Head {
fn default() -> Self {
Self {
krate: None,
krate_spelled: None,
node: None,
upstream_at: None,
groups: Vec::new(),
group_at: None,
group_spoken: Vec::new(),
measures: Vec::new(),
measure_at: None,
measure_spoken: Vec::new(),
triggers: proc_macro2::TokenStream::new(),
polled: false,
stores: proc_macro2::TokenStream::new(),
graphql: None,
whole: true,
}
}
}
struct Entry<T> {
field: syn::Ident,
value: T,
}
struct Folded {
by: Measure,
from: Option<syn::Ident>,
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Head {
let mut head = Head::default();
let mut upstream_seen: Option<syn::Path> = None;
let mut group_seen: Option<syn::Path> = None;
let mut measure_seen: Option<syn::Path> = None;
let mut graphql_seen: Option<syn::Path> = None;
head.whole = attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::literal(&meta, CRATE_PATH)
.and_then(|spelled| Ok((spelled.parse::<syn::Path>()?, spelled)))
{
Ok((path, spelled)) => {
set_once(&mut head.krate, path, &meta.path, CRATE_ONCE, errors);
head.krate_spelled.get_or_insert(spelled);
}
Err(e) => errors.push(syn::Error::new(e.span(), CRATE_PATH)),
}
return Ok(());
}
if meta.path.is_ident(UPSTREAM) {
let at = meta.path.clone();
head.upstream_at.get_or_insert_with(|| at.clone());
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
errors.push(named(&meta, UPSTREAM_TAKES_A_NODE.to_owned()));
return Ok(());
}
if upstream_seen.is_some() {
errors.push(named(&meta, UPSTREAM_ONCE.to_owned()));
return Ok(());
}
upstream_seen = Some(at);
return meta.parse_nested_meta(|inner| upstream_entry(&inner, &mut head.node, errors));
}
if meta.path.is_ident(GROUP) {
let at = meta.path.clone();
head.group_at.get_or_insert_with(|| at.clone());
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
errors.push(named(&meta, no_group()));
return Ok(());
}
if group_seen.is_some() {
errors.push(named(&meta, GROUP_ONCE.to_owned()));
return Ok(());
}
group_seen = Some(at);
return meta.parse_nested_meta(|inner| {
group_entry(&inner, &mut head.groups, &mut head.group_spoken, errors)
});
}
if meta.path.is_ident(MEASURE) {
let at = meta.path.clone();
head.measure_at.get_or_insert_with(|| at.clone());
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
errors.push(named(&meta, no_measure()));
return Ok(());
}
if measure_seen.is_some() {
errors.push(named(&meta, MEASURE_ONCE.to_owned()));
return Ok(());
}
measure_seen = Some(at);
return meta.parse_nested_meta(|inner| {
measure_entry(&inner, &mut head.measures, &mut head.measure_spoken, errors)
});
}
if meta.path.is_ident(POLL) {
head.polled = true;
attribute::carry(&meta, &mut head.triggers);
return Ok(());
}
if meta.path.is_ident(GRAPHQL) {
let mut carried = proc_macro2::TokenStream::new();
attribute::carry(&meta, &mut carried);
set_once(
&mut graphql_seen,
meta.path.clone(),
&meta.path,
GRAPHQL_ONCE,
errors,
);
head.graphql.get_or_insert(carried);
return Ok(());
}
if database_kind(&meta.path).is_some()
|| meta.path.is_ident(TABLE)
|| meta.path.is_ident(RENAME)
{
attribute::carry(&meta, &mut head.stores);
return Ok(());
}
if meta.path.is_ident("persist") {
errors.push(named(&meta, PERSIST_UNWRAPPED.to_owned()));
return Ok(());
}
for (word, instead) in DECIDED {
if meta.path.is_ident(word) {
errors.push(named(
&meta,
format!(
"`{word}` decides something an aggregate's own grammar has already decided: {instead}"
),
));
return Ok(());
}
}
for other in [NodeKind::Fulltext, NodeKind::Vector, NodeKind::Blob] {
if meta.path.is_ident(other.as_str()) {
errors.push(named(
&meta,
format!(
"an aggregate owns no {held} — one is its OWN node, declared with the `{other}` macro \
over the same upstream. {law}",
held = other.noun(),
other = other.as_str(),
law = owns_one_storage(KIND),
),
));
return Ok(());
}
}
errors.push(attribute::unknown(
&meta,
&unknown_head(),
&head_vocabulary(),
));
Ok(())
});
head
}
fn upstream_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
node: &mut Option<syn::Path>,
errors: &mut Errors,
) -> syn::Result<()> {
if inner.path.is_ident(NODE) {
match value::parse_literal::<syn::Path>(inner, NODE_IS_A_PATH) {
Ok(path) => set_once(node, path, &inner.path, NODE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(named(inner, projection_belongs_to_group(&inner.path)));
Ok(())
}
fn group_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
entries: &mut Vec<Entry<syn::Ident>>,
spoken: &mut Vec<syn::Ident>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(field) = inner.path.get_ident().cloned() else {
errors.push(attribute::unknown(inner, ENTRY_NAMES_A_FIELD, &[]));
return Ok(());
};
spoken.push(field.clone());
let shape = group_entry_shape(&field);
let from = match value::literal(inner, &shape).and_then(|spelled| {
value::named_field(&spelled, &shape).map_err(|e| syn::Error::new(e.span(), shape.clone()))
}) {
Ok(from) => from,
Err(e) => {
errors.push(e);
return Ok(());
}
};
if entries.iter().any(|entry| entry.field == field) {
errors.push(syn::Error::new_spanned(&inner.path, once(GROUP, &field)));
return Ok(());
}
entries.push(Entry { field, value: from });
Ok(())
}
fn measure_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
entries: &mut Vec<Entry<Folded>>,
spoken: &mut Vec<syn::Ident>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(field) = inner.path.get_ident().cloned() else {
errors.push(attribute::unknown(inner, ENTRY_NAMES_A_FIELD, &[]));
return Ok(());
};
spoken.push(field.clone());
let read = match attribute::has_block(inner) {
true => full_form(inner, &field, errors)?,
false => sugar(inner, &field, errors),
};
let Some(folded) = read else {
return Ok(());
};
if entries.iter().any(|entry| entry.field == field) {
errors.push(syn::Error::new_spanned(&inner.path, once(MEASURE, &field)));
return Ok(());
}
entries.push(Entry {
field,
value: folded,
});
Ok(())
}
fn sugar(
inner: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
errors: &mut Errors,
) -> Option<Folded> {
let by = fold_value(inner, field, errors)?;
if by.owed() == Owed::Column {
errors.push(syn::Error::new_spanned(
&inner.path,
sugar_omits_the_column(field, &by.as_written()),
));
attribute::skip_entry(inner);
return None;
}
if !value_was_the_whole_entry(inner) {
errors.push(syn::Error::new_spanned(
&inner.path,
measure_entry_shape(field),
));
attribute::skip_entry(inner);
return None;
}
Some(Folded { by, from: None })
}
fn full_form(
inner: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
errors: &mut Errors,
) -> syn::Result<Option<Folded>> {
if attribute::empty_group(inner) {
errors.push(named(inner, empty_entry(field)));
return Ok(None);
}
let mut written = FullForm::default();
inner.parse_nested_meta(|property| {
match MEASURE_PROPERTIES
.iter()
.find(|known| property.path.is_ident(known.word))
{
Some(known) => (known.read)(&property, &mut written, field, errors),
None => {
written.refused = true;
errors.push(attribute::unknown(
&property,
&unknown_property(field),
&property_words(),
));
}
}
Ok(())
})?;
Ok(settled(written, inner, field, errors))
}
struct MeasureProperty {
word: &'static str,
read: fn(&syn::meta::ParseNestedMeta<'_>, &mut FullForm, &syn::Ident, &mut Errors),
}
const MEASURE_PROPERTIES: &[MeasureProperty] = &[
MeasureProperty {
word: FOLD,
read: read_fold,
},
MeasureProperty {
word: FROM,
read: read_from,
},
];
#[derive(Default)]
struct FullForm {
by: Option<(Measure, syn::Path)>,
fold_spoken: bool,
from: Option<(syn::Ident, syn::Path)>,
from_spoken: bool,
refused: bool,
}
fn read_fold(
property: &syn::meta::ParseNestedMeta<'_>,
written: &mut FullForm,
field: &syn::Ident,
errors: &mut Errors,
) {
if written.fold_spoken {
errors.push(named(property, property_once(FOLD, field)));
return;
}
written.fold_spoken = true;
let Some(by) = fold_value(property, field, errors) else {
return;
};
if !value_was_the_whole_entry(property) {
errors.push(syn::Error::new_spanned(
&property.path,
measure_entry_shape(field),
));
attribute::skip_entry(property);
return;
}
written.by = Some((by, property.path.clone()));
}
fn read_from(
property: &syn::meta::ParseNestedMeta<'_>,
written: &mut FullForm,
field: &syn::Ident,
errors: &mut Errors,
) {
if written.from_spoken {
errors.push(named(property, property_once(FROM, field)));
return;
}
written.from_spoken = true;
let shape = from_shape(field);
match value::literal(property, &shape).and_then(|spelled| {
value::named_field(&spelled, &shape).map_err(|e| syn::Error::new(e.span(), shape.clone()))
}) {
Ok(column) => written.from = Some((column, property.path.clone())),
Err(e) => errors.push(e),
}
}
fn settled(
written: FullForm,
at: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
errors: &mut Errors,
) -> Option<Folded> {
let Some((by, fold_at)) = written.by else {
if !written.fold_spoken && !written.refused {
errors.push(syn::Error::new_spanned(&at.path, names_no_fold(field)));
}
return None;
};
match (by.owed(), written.from) {
(Owed::Column, None) => {
if !written.from_spoken && !written.refused {
errors.push(syn::Error::new_spanned(
&fold_at,
fold_owes_a_column(field, &by.as_written()),
));
}
None
}
(Owed::Nothing, Some((_, from_at))) => {
errors.push(syn::Error::new_spanned(
&from_at,
fold_reads_no_column(field, &by.as_written()),
));
None
}
(_, from) => Some(Folded {
by,
from: from.map(|(column, _)| column),
}),
}
}
fn fold_value(
entry: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
errors: &mut Errors,
) -> Option<Measure> {
let Ok(stream) = entry.value() else {
errors.push(named(entry, measure_entry_shape(field)));
return None;
};
if stream.peek(syn::LitStr) {
return match stream
.parse::<syn::LitStr>()
.and_then(|spelled| spelled.parse::<syn::Path>())
{
Ok(path) => Some(Measure::Declared(path)),
Err(e) => {
errors.push(syn::Error::new(e.span(), DECLARED_IS_A_PATH));
attribute::skip_entry(entry);
None
}
};
}
if stream.peek(syn::Ident) {
let Ok(word) = stream.parse::<syn::Ident>() else {
errors.push(named(entry, measure_entry_shape(field)));
return None;
};
return match Measure::shipped(&word.to_string()) {
Some(shipped) => Some(shipped),
None => {
errors.push(syn::Error::new_spanned(&word, unknown_fold(&word)));
attribute::skip_entry(entry);
None
}
};
}
errors.push(named(entry, measure_entry_shape(field)));
None
}
fn value_was_the_whole_entry(entry: &syn::meta::ParseNestedMeta<'_>) -> bool {
entry.input.is_empty() || entry.input.peek(syn::Token![,])
}
fn markers(
attrs: &[syn::Attribute],
field: &syn::Ident,
errors: &mut Errors,
) -> (
ingraph_codegen::prelude::Projection,
Option<(Role, syn::Path)>,
bool,
) {
let mut role: Option<(Role, syn::Path)> = None;
let mut spoken = false;
let projection = column::projection_markers(attrs, field, errors, |meta, errors| {
if meta.path.is_ident("id") {
return column::Claim::Refused(syn::Error::new_spanned(
&meta.path,
mints_its_own_key(field),
));
}
for owner in [NodeKind::Vector, NodeKind::Fulltext] {
let Some(word) = owner.election() else {
continue;
};
if meta.path.is_ident(word) {
return column::Claim::Refused(syn::Error::new_spanned(
&meta.path,
election_is_another_kinds(word, owner, field),
));
}
}
for this in [Role::Group, Role::Measure] {
if !meta.path.is_ident(this.word()) {
continue;
}
spoken = true;
if attribute::has_block(meta) || attribute::has_value(meta) {
return column::Claim::Refused(named(meta, role_is_bare(this, field)));
}
match &role {
Some((seen, _)) if *seen == this => errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{word}` is declared more than once on `{field}` — one marker, one field",
word = this.word(),
),
)),
Some((seen, _)) => errors.push(syn::Error::new_spanned(
&meta.path,
two_roles(*seen, this, field),
)),
None => role = Some((this, meta.path.clone())),
}
return column::Claim::Taken;
}
column::Claim::Refused(attribute::unknown(
meta,
&unknown_field(field),
&field_vocabulary(),
))
});
(projection, role, spoken)
}
fn grouped(
entries: &[Entry<syn::Ident>],
at: Option<&syn::Path>,
whole: bool,
columns: &[Field],
aggregate: &syn::Ident,
errors: &mut Errors,
) -> Vec<Grouped> {
if whole && entries.is_empty() && at.is_none() {
errors.push(syn::Error::new_spanned(aggregate, no_group()));
}
entries
.iter()
.filter_map(|entry| {
let column = matched(entry, Role::Group, columns, aggregate, errors)?;
Some(Grouped {
field: entry.field.clone(),
from: entry.value.clone(),
ty: column.ty.clone(),
projection: column.projection,
})
})
.collect()
}
fn measured(
entries: &[Entry<Folded>],
at: Option<&syn::Path>,
whole: bool,
columns: &[Field],
aggregate: &syn::Ident,
errors: &mut Errors,
) -> Vec<Measured> {
if whole && entries.is_empty() && at.is_none() {
errors.push(syn::Error::new_spanned(aggregate, no_measure()));
}
entries
.iter()
.filter_map(|entry| {
let column = matched(entry, Role::Measure, columns, aggregate, errors)?;
cardinality(&entry.value.by, column, errors);
Some(Measured {
field: entry.field.clone(),
by: entry.value.by.clone(),
from: entry.value.from.clone(),
ty: column.ty.clone(),
projection: column.projection,
})
})
.collect()
}
fn cardinality(by: &Measure, column: &Field, errors: &mut Errors) {
if !matches!(by, Measure::Counting) {
return;
}
let syn::Type::Path(path) = &column.ty else {
return;
};
let Some(last) = path.path.segments.last() else {
return;
};
if !NARROWINGS.iter().any(|word| last.ident == word) {
return;
}
errors.push(syn::Error::new_spanned(
&column.ty,
counting_is_wide(&column.name),
));
}
const NARROWINGS: [&str; 16] = [
"u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32",
"f64", "bool", "char",
];
fn mints_a_fold() -> String {
format!(
"`{FOLD}` is the method an aggregate's expansion MINTS — `<Aggregate>::{FOLD}(rows)` is the \
recompute's arithmetic, every row of the upstream in and one row per group out — so a column \
of that name would be two definitions of one name on one type, which rustc reports inside the \
expansion rather than here. Rename the column: the word is already this grammar's, at \
`measure(<field>({FOLD} = …))`, where it says what folds a group rather than naming one of the \
folded columns"
)
}
fn counting_is_wide(field: &syn::Ident) -> String {
format!(
"`{field}` is filled by `counting`, which answers HOW MANY ROWS a group holds — a CARDINALITY, \
and this framework carries every cardinality at `ingraph::Count`. So the column's type is \
`Count` and not this one: the fold's answer is the citizen's own fact rather than the \
declaration's, and a column of another type would be the emission asking rustc to reshape a \
count it has already made. Write `{field}: ingraph::Count`, or fold this column with a measure \
whose answer is the type you want — a fold is a TYPE in this grammar, so one of your own is \
`measure({field} = \"path::To::Fold\")` and needs no word admitted to any vocabulary. `Count` \
is a `u64` that knows it counts rows that EXIST, which is what lets it store on SQLite and \
PostgreSQL where a bare `u64` has no column at all"
)
}
fn matched<'a, T>(
entry: &Entry<T>,
role: Role,
columns: &'a [Field],
aggregate: &syn::Ident,
errors: &mut Errors,
) -> Option<&'a Field> {
let Some(column) = columns.iter().find(|column| column.name == entry.field) else {
errors.push(syn::Error::new_spanned(
&entry.field,
format!(
"`{block}(…)`'s entries name THIS declaration's fields, and `{field}` is not one of \
`{aggregate}`'s",
block = role.word(),
field = entry.field,
),
));
return None;
};
match &column.role {
Some((worn, _)) if *worn == role => Some(column),
Some((worn, at)) => {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{field}` is named in `{block}(…)` and wears `#[ingraph({worn})]` — the head entry says \
this column is {what}, and the marker says it is {other}, and a column is one of them. \
The two words are written twice on purpose so that a disagreement is caught here instead \
of becoming a row whose shape depends on which half was read",
field = entry.field,
block = role.word(),
worn = worn.word(),
what = role.what(),
other = worn.what(),
),
));
None
}
None => None,
}
}
fn unmatched(
columns: &[Field],
groups: &[syn::Ident],
measures: &[syn::Ident],
whole: bool,
errors: &mut Errors,
) {
for column in columns {
let name = &column.name;
let Some((role, at)) = &column.role else {
if !column.role_spoken {
errors.push(syn::Error::new_spanned(name, wears_no_role(name)));
}
continue;
};
let named_at_the_head = match role {
Role::Group => groups.contains(name),
Role::Measure => measures.contains(name),
};
if !whole || named_at_the_head {
continue;
}
let missing = match role {
Role::Group => {
format!("`{name} = \"<upstream field>\"`, naming the upstream field it is read out of")
}
Role::Measure => format!(
"`{name}({FOLD} = <fold>, {FROM} = \"<upstream column>\")`, naming what folds a group into \
it and the column that fold reads — a fold is one of {folds}, or `\"path::to::Fold\"` for \
one of your own — or the sugar `{name} = <fold>` where the fold reads no column",
folds = shipped(Measure::SHIPPED.into_iter()),
),
};
errors.push(syn::Error::new_spanned(
at,
format!(
"`{name}` wears `#[ingraph({word})]` and `{word}(…)` has no entry for it — the marker says \
WHAT the column is and the head entry says the rest, so a marked field with no entry is \
half a declaration. Write {missing}",
word = role.word(),
),
));
}
}
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
let why = "generic aggregates are not supported — the declaration must be concrete, because a \
key column's type is read straight off it";
if !generics.params.is_empty() {
errors.push(syn::Error::new_spanned(generics, why));
} else if let Some(clause) = &generics.where_clause {
errors.push(syn::Error::new_spanned(clause, why));
}
}
fn named_fields(input: &syn::DeriveInput) -> syn::Result<&syn::FieldsNamed> {
match &input.data {
syn::Data::Struct(data) => match &data.fields {
syn::Fields::Named(named) => Ok(named),
syn::Fields::Unnamed(_) | syn::Fields::Unit => Err(syn::Error::new_spanned(
&input.ident,
"an aggregate must be a struct with named fields — `group(…)` and `measure(…)` each fill a \
field BY NAME, and a positional one has none to be filled by",
)),
},
syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
&input.ident,
"`#[ingraph::aggregate]` supports structs only",
)),
}
}
const NO_FIELDS: &str = "an aggregate with no fields folds nothing into nothing — its row is its \
group columns and its measures, and a row with neither is a table with no \
columns. Declare at least one `#[ingraph(group)]` field and one \
`#[ingraph(measure)]` field";
const NO_UPSTREAM: &str = "an aggregate folds the rows of ONE upstream, and `upstream(…)` is where \
it names one — `upstream(node = \"path::To::Upstream\")`. It is not \
optional: an aggregate reads its upstream's TABLE rather than its \
messages, so without an upstream there is no table to read and nothing \
to group";
const NO_TRIGGER: &str = "an aggregate needs a `poll(…)` clock — it recomputes WHOLE on every \
trigger, and the trigger is the only thing that ever writes its rows, so \
a declaration with no clock mounts a table that stays empty and answers \
nothing forever. Write one: `poll(<name>, every = \"10m\", light)`, in \
the framework's own clock grammar. A notify edge used as an ALARM is the \
recorded freshness upgrade and is not built, so the clock is the one \
trigger there is";
fn wears_no_role(field: &syn::Ident) -> String {
format!(
"`{field}` wears neither `#[ingraph({GROUP})]` nor `#[ingraph({MEASURE})]` — an aggregate's row \
is its group columns and its measures, and every field is one or the other: a group column is \
read out of the upstream's rows and keys the folded row, a measure is what a fold fills. There \
is no third thing for a column of one to be, so a field with no role is a column the emission \
has nothing to put in"
)
}
fn two_roles(first: Role, second: Role, field: &syn::Ident) -> String {
format!(
"`{field}` wears both `#[ingraph({first})]` and `#[ingraph({second})]`, and each names a \
different column: a group column is READ out of the upstream's rows and keys the folded row, a \
measure is what a fold FILLS. A column is one of them — a field that were both would be part \
of the key that decides which rows it is folded from",
first = first.word(),
second = second.word(),
)
}
fn role_is_bare(role: Role, field: &syn::Ident) -> String {
format!(
"`{word}` is a BARE marker — its presence says `{field}` is {what}, which is the whole of what \
the role declares. What that column is read from, or what folds it, is the head's `{word}(…)` \
entry, because it is a fact about the upstream rather than about this field",
word = role.word(),
what = role.what(),
)
}
fn mints_its_own_key(field: &syn::Ident) -> String {
format!(
"`{field}` cannot be an aggregate's id, because an aggregate mints its key from its GROUP \
COLUMNS — one row per group, addressed by the group it is about, so the key is `group(…)` and \
there is no seat left for a declared id. A node that mints an id of its own is an `operator` \
or a `record`"
)
}
fn election_is_another_kinds(word: &str, owner: NodeKind, field: &syn::Ident) -> String {
format!(
"`{word}` elects `{field}` into a query an aggregate runs none of — an aggregate FOLDS its \
upstream's rows into one row per group and is read as the record it is, so no field of one is \
run over by a ranking at all. The marker is the `{owner}` kind's own, and an index over these \
rows is its OWN node: declare it with the `{owner}` macro, on a type whose `upstream(…)` names \
this aggregate. {law}",
owner = owner.as_str(),
law = owns_one_storage(KIND),
)
}
fn projection_belongs_to_group(path: &syn::Path) -> String {
let word = suggest::word(path).unwrap_or_else(|| "that entry".to_owned());
format!(
"`upstream(…)` names the EDGE on an aggregate and takes `{NODE} = \"…\"` alone — the projection \
is `{GROUP}(…)`, because only the group columns are read out of the upstream's rows and a \
measure's column is FOLDED into being, so a projection here would claim a totality this kind \
does not have. A derived index's `upstream(…)` carries both, and that is the difference. Write \
`{GROUP}({word} = \"<upstream field>\")`"
)
}
fn unknown_fold(word: &syn::Ident) -> String {
format!(
"`{word}` is no fold this framework ships — the shipped ones are {shipped}, written BARE \
because they are the framework's own, and every other fold there is arrives QUOTED as the type \
that implements it: `\"path::to::Fold\"`. The bare vocabulary is closed because a word is a \
promise this crate can write the whole binding; the quoted form is the open half and needs no \
admission{near}",
shipped = shipped(Measure::SHIPPED.into_iter()),
near = suggest::did_you_mean(&word.to_string(), Measure::SHIPPED),
)
}
fn group_entry_shape(field: &syn::Ident) -> String {
format!(
"`{field} = \"<upstream field>\"` names the upstream field this group column is read out of, in \
a string literal — the entry's own name is the field being filled, and its value is where the \
value comes from"
)
}
fn measure_entry_shape(field: &syn::Ident) -> String {
format!(
"`{field}` is one measure column, and it is written in its FULL FORM — `{field}({FOLD} = \
<fold>, {FROM} = \"<upstream column>\")`, every property of the column by name — or in the \
sugar `{field} = <fold>`, which is that same entry where the fold reads no column and so \
nothing is left out. A FOLD is one of the framework's own, written bare ({shipped}), or one of \
yours, written QUOTED as the type that implements it (`\"path::to::Fold\"`)",
shipped = shipped(Measure::SHIPPED.into_iter()),
)
}
fn sugar_omits_the_column(field: &syn::Ident, fold: &str) -> String {
format!(
"`{field} = {fold}` leaves out the column `{fold}` folds — the sugar spends its ONE position on \
the fold and has no seat for anything else, so it is the spelling for entries with nothing \
else to say. Write the FULL FORM, where every property of the column has a name: \
`{field}({FOLD} = {fold}, {FROM} = \"<upstream column>\")`. The short spelling stays exactly \
where it omits nothing — `{counting}` counts the group's ROWS and reads no column, so \
`<field> = {counting}` is a whole entry",
counting = Measure::SHIPPED[0],
)
}
fn fold_owes_a_column(field: &syn::Ident, fold: &str) -> String {
format!(
"`{fold}` folds an upstream COLUMN and `{field}(…)` names none — write `{FROM} = \"<upstream \
column>\"` beside the fold: `{field}({FOLD} = {fold}, {FROM} = \"<upstream column>\")`. It is \
not filled in from `{field}`: a measure's own name belongs to this declaration and the column \
belongs to the upstream, so a grammar that assumed the two agree would fold the wrong column \
wherever they did not — and say nothing. `{GROUP}(…)` spells both out for the same reason even \
when they match"
)
}
fn fold_reads_no_column(field: &syn::Ident, fold: &str) -> String {
format!(
"`{FROM}` names the upstream column a fold READS, and `{fold}` reads none — it answers how many \
rows the group holds, whatever those rows are, so there is no column for this entry to name. \
Drop the property: `{field}({FOLD} = {fold})` is the entry entire, and `{field} = {fold}` is \
that same entry in the sugar, which omits nothing here"
)
}
fn names_no_fold(field: &syn::Ident) -> String {
format!(
"`{field}(…)` names no fold, and a measure column is what a FOLD fills — `{FROM}` alone says \
which column is read and nothing about what becomes of it. Write `{FOLD} = <fold>` in the \
entry: `{field}({FOLD} = <fold>, {FROM} = \"<upstream column>\")`, with the fold one of \
{shipped} or a `\"path::to::Fold\"` of your own",
shipped = shipped(Measure::SHIPPED.into_iter()),
)
}
fn empty_entry(field: &syn::Ident) -> String {
format!(
"`{field}()` says nothing, which is not a measure — {}",
measure_entry_shape(field)
)
}
fn property_once(word: &str, field: &syn::Ident) -> String {
format!(
"`{word}` is declared more than once in `{field}(…)` — one entry answers each property once, \
and a second answer to one question is not a second measure: a column of its own takes an \
entry of its own"
)
}
fn unknown_property(field: &syn::Ident) -> String {
format!(
"unknown property in `{field}(…)` — {roster}. What a measure column IS comes from its `#[ingraph({MEASURE})]` \
marker and its declared type, so what is left for the entry to say is what folds the group and \
which column that fold reads",
roster = property_roster(),
)
}
fn property_words() -> Vec<&'static str> {
MEASURE_PROPERTIES
.iter()
.map(|property| property.word)
.collect()
}
fn property_roster() -> String {
format!(
"a measure entry knows {}",
shipped(MEASURE_PROPERTIES.iter().map(|property| property.word))
)
}
fn from_shape(field: &syn::Ident) -> String {
format!(
"`{FROM} = \"<upstream column>\"` names the upstream column `{field}`'s fold reads, in a string \
literal — the column belongs to the upstream rather than to this declaration, which is why it \
is quoted here exactly as it is in `{GROUP}(…)`"
)
}
fn once(block: &str, field: &syn::Ident) -> String {
format!("`{field}` is named more than once in `{block}(…)` — one field, one entry")
}
fn no_group() -> String {
format!(
"an aggregate needs at least one `{GROUP}(…)` entry — it holds ONE ROW PER GROUP and mints its \
key from the group columns, so a declaration with none has no key to address a row by and no \
shape for the one keyless row it would hold. Write `{GROUP}(<field> = \"<upstream field>\")` \
for each column the rows are grouped by"
)
}
fn no_measure() -> String {
format!(
"an aggregate needs at least one `{MEASURE}(…)` entry — folding is what the kind IS, and a \
declaration that folds nothing is a list of the upstream's distinct groups, which a query over \
the upstream already answers. Write `{MEASURE}(<field>({FOLD} = <fold>, {FROM} = \"<upstream \
column>\"))` for each column a fold fills"
)
}
const UNREADABLE_HEAD: &str = "this aggregate's head could not be read to the end";
const ENTRY_NAMES_A_FIELD: &str = "an entry names ONE of this declaration's fields, so the entry's \
own name is that field's name — a path with several segments \
names no field of anything";
const NODE_IS_A_PATH: &str =
"`node = \"…\"` names the upstream node, as a type path in a string literal";
const NODE_ONCE: &str =
"`node` is declared more than once in `upstream(…)` — one entry names one upstream";
const UPSTREAM_ONCE: &str = "`upstream` is declared more than once — an aggregate folds ONE \
upstream's rows. Folding two together needs a by-key intake across two \
tables, which is a seat this framework has not built, so v1 is \
single-upstream by ruling rather than by omission";
const UPSTREAM_TAKES_A_NODE: &str = "`upstream(…)` needs `node = \"path::To::Upstream\"` — naming \
the node whose rows are folded is the only thing it does on an \
aggregate, the projection being `group(…)`'s";
const GROUP_ONCE: &str =
"`group` is declared more than once — one block carries every column the rows are grouped by";
const MEASURE_ONCE: &str =
"`measure` is declared more than once — one block carries every column a fold fills";
const GRAPHQL_ONCE: &str =
"`graphql` is declared more than once — one declaration has one wire face";
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";
const CRATE_PATH: &str = "`#[ingraph::aggregate(crate = \"…\")]` must be a path to the `ingraph` \
crate, in a string literal";
const DECLARED_IS_A_PATH: &str = "a fold of your own is named as a TYPE PATH in a string literal — \
`\"app::Median\"`. Nothing here resolves it: the path is emitted \
and the compiler resolves it where it lands";
const PERSIST_UNWRAPPED: &str = "`persist(…)` is gone — an aggregate holds rows and names its \
stores BARE at the head, so write \
`#[ingraph::aggregate(…, sqlite)]` and keep every word that was \
inside each database's own block. Storage is the essence of a \
thing that holds rows, and an essence does not wrap; `graphql(…)`, \
which is OPTIONAL, still does";
const DECIDED: [(&str, &str); 3] = [
(
"lineage",
"the path is the GROUP columns, which `group(…)` already names — an aggregate's row is about a \
group, and the group is what addresses it",
),
(
"key",
"the key is the group columns, which `key = lineage ⊕ id` already spells over them — and there \
is no id beside them, an aggregate minting no id of its own",
),
(
"subscribe",
"an aggregate reads its upstream's TABLE rather than its messages, which is what makes it \
immune to the duplicate delivery every edge in this framework permits — so its edge is \
`upstream(node = \"…\")` and it takes no message feed at all",
),
];
fn unknown_head() -> String {
format!(
"unknown `ingraph` aggregate attribute — an aggregate takes `{UPSTREAM}(node = \"…\")`, \
`{GROUP}(<field> = \"<upstream field>\", …)`, `{MEASURE}(<field>({FOLD} = <fold>, {FROM} = \
\"<upstream column>\"), …)`, `{POLL}(…)`, its STORE WORDS bare ({stores}, with `{TABLE} = \
\"…\"` and `{RENAME} = \"…\"` beside them), `{GRAPHQL}(…)` and `crate = \"…\"`, and nothing \
else",
stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
)
}
pub(crate) fn head_vocabulary() -> Vec<&'static str> {
[
UPSTREAM, GROUP, MEASURE, POLL, GRAPHQL, TABLE, RENAME, "crate",
]
.into_iter()
.chain(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str))
.collect()
}
fn unknown_field(field: &syn::Ident) -> String {
format!(
"unknown `ingraph` field attribute — a field of an aggregate takes its ROLE (`{GROUP}` or \
`{MEASURE}`, exactly one) and the projection words ({projections}), and nothing else. \
`{field}`'s storage is the row table's, which the declaration names at its head, so a \
per-database word here would be configuring a column of a row this declaration does not write \
by hand",
projections = shipped(column::PROJECTIONS.into_iter()),
)
}
pub(crate) fn field_vocabulary() -> Vec<&'static str> {
[GROUP, MEASURE]
.into_iter()
.chain(column::PROJECTIONS)
.collect()
}