use std::collections::BTreeMap;
use ingraph_codegen::graph::{
FusedMember, GenerationsSeat, GraphModel, InterfaceMount, OriginMount, RetiredLedger,
};
use ingraph_codegen::{
catalog::{RESERVED_MOUNT, ResourceField},
engine::{EngineBinding, EngineKind},
model::DatabaseKind,
options::{RESERVED_GENERATIONS_MOUNT, RESERVED_REGISTRY_MOUNT, RESERVED_RETIRED_MOUNT},
};
use crate::{
attribute::{self, named},
errors::Errors,
value,
};
mod resource;
#[cfg(test)]
mod dedup;
#[cfg(test)]
mod engines;
#[cfg(test)]
mod tests;
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
) -> syn::Result<GraphModel> {
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let Options {
krate,
engines,
retired,
generations,
} = options(arguments, &mut errors);
concrete(&input.generics, &mut errors);
let Members {
nodes,
mounts,
queried,
interfaces,
fused,
origins,
resources,
} = match members(input, &mut errors) {
Ok(list) => list,
Err(terminal) => return Err(errors.seal(terminal)),
};
an_origin_needs_a_node_to_feed(&origins, &nodes, &mut errors);
errors.into_result(GraphModel {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
vis: input.vis.clone(),
name: input.ident.clone(),
nodes,
mounts,
queried,
interfaces,
fused,
origins,
resources,
engines,
retired,
generations,
})
}
struct Options {
krate: Option<syn::Path>,
engines: Vec<EngineBinding>,
retired: Option<RetiredLedger>,
generations: Option<GenerationsSeat>,
}
fn an_origin_needs_a_node_to_feed(
origins: &[OriginMount],
nodes: &[syn::Type],
errors: &mut Errors,
) {
if origins.is_empty() || !nodes.is_empty() {
return;
}
for origin in origins {
errors.push(syn::Error::new_spanned(
&origin.ty,
"this origin can have no consumer — a root mounting NO NODE has nothing that could subscribe \
to it, and an origin's one out-edge IS its feed. Only the node tier declares upstreams: an \
`interface` is a contract, a `resource` is a citizen the launch hands out, and a `fuse` \
member owns a corpus. Add the node that names this origin in its own \
`subscribe(upstream(node = \"…\"))`, or take the origin off a root that runs nothing",
));
}
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut krate: Option<syn::Path> = None;
let mut engines: Vec<EngineBinding> = Vec::new();
let mut block: Option<syn::Path> = None;
let mut retired: Option<RetiredLedger> = None;
let mut ledger: Option<syn::Path> = None;
let mut generations: Option<GenerationsSeat> = None;
let mut seat: Option<syn::Path> = None;
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::parse_literal::<syn::Path>(
&meta,
"`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
) {
Ok(path) => {
if krate.replace(path).is_some() {
errors.push(syn::Error::new_spanned(
&meta.path,
"`crate` is declared more than once — one declaration names one crate",
));
}
}
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident(ENGINES) {
return attribute::block(
&meta,
&mut block,
"`engines(…)` is declared more than once — one root, one engine table, and two blocks would \
be two places for one word to be bound",
errors,
|inner, errors| {
engine_binding(&inner, &mut engines, errors);
Ok(())
},
);
}
if meta.path.is_ident(RETIRED) {
return attribute::block(
&meta,
&mut ledger,
"`retired(…)` is declared more than once — one root, one ledger, and two blocks would be \
two places a deployment's retirees could be written down",
errors,
|inner, errors| {
retired_engine(&inner, &mut retired, errors);
Ok(())
},
);
}
if meta.path.is_ident(GENERATIONS) {
return attribute::block(
&meta,
&mut seat,
"`generations(…)` is declared more than once — one root, one seat, and two blocks would be \
two places a deployment's current pointers could be written down",
errors,
|inner, errors| {
generations_engine(&inner, &mut generations, errors);
Ok(())
},
);
}
if meta.path.is_ident(DEDUP) {
errors.push(syn::Error::new_spanned(&meta.path, DEDUP_IS_A_RECIPES));
attribute::skip_entry(&meta);
return Ok(());
}
errors.push(attribute::unknown(
&meta,
"unknown entry in `#[ingraph(…)]` on a graph root — it takes `crate = \"…\"`, \
`engines(<word> = \"path::To::Engine\")`, `retired(<engine>)` and `generations(<engine>)`, \
and nothing else: a graph's content is the list its fields are, plus what the words on those \
fields' declarations MEAN and where its retirees and its current pointers are written down",
&["crate", ENGINES, RETIRED, GENERATIONS],
));
Ok(())
});
Options {
krate,
engines,
retired,
generations,
}
}
const ENGINES: &str = "engines";
const RETIRED: &str = "retired";
const GENERATIONS: &str = "generations";
const DEDUP: &str = "dedup";
fn retired_engine(
inner: &syn::meta::ParseNestedMeta<'_>,
retired: &mut Option<RetiredLedger>,
errors: &mut Errors,
) {
let Some(word) = inner.path.get_ident().map(ToString::to_string) else {
errors.push(attribute::unknown(
inner,
"the engine inside `retired(…)` is ONE word — `retired(sqlite)` — and a path with several \
segments is not one",
&RETIRED_ENGINES,
));
return;
};
let Some(engine) = DatabaseKind::ALL
.into_iter()
.find(|kind| kind.as_str() == word)
else {
let refusal = format!(
"`{word}` is not an engine the retired ledger builds — it takes `sqlite`, `postgres`, \
`mysql` or `mongo`, the same four words a record's own `persist(…)` takes. A key-value store \
and a store of your own are FUTURE words on the same seam: implement \
`ingraph::RetiredStore` and hand it to `Keeper::new`, which needs no word here at all"
);
errors.push(attribute::unknown(inner, &refusal, &RETIRED_ENGINES));
attribute::skip_entry(inner);
return;
};
if attribute::has_value(inner) || attribute::has_block(inner) {
errors.push(attribute::named(
inner,
format!(
"`{word}` is a bare word — it names WHICH engine this root's retired ledger runs on, and \
WHERE on that engine is the deployment's, which reaches the framework through the \
`[retired]` section (`dsn = \"…\"`) rather than through this attribute"
),
));
attribute::skip_entry(inner);
return;
}
if let Some(first) = retired.as_ref() {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`retired(…)` already named `{first}` — one root, one ledger. A deployment's retirees are \
the truth about which root keys are out, and two engines holding that truth is two \
answers to one question",
first = first.engine.as_str(),
),
));
return;
}
*retired = Some(RetiredLedger { engine });
}
const RETIRED_ENGINES: [&str; 4] = ["sqlite", "postgres", "mysql", "mongo"];
const GENERATIONS_ENGINES: [&str; 3] = ["sqlite", "postgres", "mysql"];
fn generations_engine(
inner: &syn::meta::ParseNestedMeta<'_>,
generations: &mut Option<GenerationsSeat>,
errors: &mut Errors,
) {
let Some(word) = inner.path.get_ident().map(ToString::to_string) else {
errors.push(attribute::unknown(
inner,
"the engine inside `generations(…)` is ONE word — `generations(sqlite)` — and a path with \
several segments is not one",
&GENERATIONS_ENGINES,
));
return;
};
let engine = DatabaseKind::ALL
.into_iter()
.find(|kind| kind.as_str() == word)
.filter(|kind| kind.generations_arm().is_some());
let Some(engine) = engine else {
let refusal = format!(
"`{word}` is not an engine the generations seat builds — it takes `sqlite`, `postgres` or \
`mysql`. A document store is not a word here: its retention duty is a MEMBERSHIP sweep \
rather than the anchored `DELETE` these three share, so it arrives as \
`ingraph::GenerationsStore` implemented and handed to `Curator::new`"
);
errors.push(attribute::unknown(inner, &refusal, &GENERATIONS_ENGINES));
attribute::skip_entry(inner);
return;
};
if attribute::has_value(inner) || attribute::has_block(inner) {
errors.push(attribute::named(
inner,
format!(
"`{word}` is a bare word — it names WHICH engine this root's current pointers run on, and \
WHERE on that engine and HOW DEEP its history goes are the deployment's, which reach the \
framework through the `[generations]` section (`dsn = \"…\"`, `keep = <n>`) rather than \
through this attribute"
),
));
attribute::skip_entry(inner);
return;
}
if let Some(first) = generations.as_ref() {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`generations(…)` already named `{first}` — one root, one seat. The pointer table is the \
truth about which generation each closure is reading, and two engines holding that truth \
is two answers to one question",
first = first.engine.as_str(),
),
));
return;
}
*generations = Some(GenerationsSeat { engine });
}
const DEDUP_IS_A_RECIPES: &str = "`dedup(…)` is a RECIPE's word — it chooses the join a FUSED read tells two roots apart with, and \
a root mints no fused door. Write it on the declaration that does: \
`#[ingraph::search(dedup(hash))]`, beside the members that recipe fuses. A root's own words are \
`crate = \"…\"` and `engines(<word> = \"path::To::Engine\")`";
fn engine_binding(
inner: &syn::meta::ParseNestedMeta<'_>,
engines: &mut Vec<EngineBinding>,
errors: &mut Errors,
) {
let Some(word) = inner.path.get_ident().cloned() else {
errors.push(attribute::unknown(
inner,
"an engine word is ONE word — the entry's own name is the word a declaration writes on a \
field — and a path with several segments is not one. The PATH goes on the right: \
`<word> = \"path::To::Engine\"`",
&[],
));
return;
};
if let Some(shipped) = EngineKind::of(&word) {
errors.push(named(
inner,
format!(
"`{word}` is an engine `ingraph` ships, so it BINDS ITSELF — under `feature = \"{word}\"`, \
the way a database word does. A deployment says only whether it compiled it, and rebinding \
it here would give one word two meanings in one program. A third-party engine takes a word \
of its own, and `{word}` holds {serves}",
serves = shipped.serves().plural(),
),
));
return;
}
if let Some(first) = engines.iter().find(|bound| bound.word == word) {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{first}` is bound more than once — one word names one engine, and a second entry would \
leave every field that wrote the word pointing at whichever binding the reader reached \
first",
first = first.word,
),
));
attribute::skip_entry(inner);
return;
}
match value::parse_literal::<syn::Path>(
inner,
&format!(
"`{word} = \"…\"` names the engine this word means, as a type path in a string literal — a \
word that points at something written elsewhere is quoted"
),
) {
Ok(engine) => engines.push(EngineBinding { word, engine }),
Err(e) => {
errors.push(e);
attribute::skip_entry(inner);
}
}
}
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
if generics.params.is_empty() {
return;
}
errors.push(syn::Error::new_spanned(
&generics.params,
"a graph root takes no generic parameter — its fields ARE the node list, and a parameter is \
not a node until it is substituted, so a generic root would name a different graph per \
instantiation",
));
}
struct Members {
nodes: Vec<syn::Type>,
mounts: Vec<syn::Ident>,
queried: Vec<syn::Type>,
interfaces: Vec<InterfaceMount>,
fused: Vec<FusedMember>,
origins: Vec<OriginMount>,
resources: Vec<ResourceField>,
}
fn members(input: &syn::DeriveInput, errors: &mut Errors) -> Result<Members, syn::Error> {
let syn::Data::Struct(data) = &input.data else {
return Err(syn::Error::new_spanned(
&input.ident,
"a graph root is a STRUCT whose fields are the nodes — an enum declares alternatives, and \
a graph holds all of its nodes at once",
));
};
let syn::Fields::Named(fields) = &data.fields else {
return Err(syn::Error::new_spanned(
&input.ident,
"a graph root's fields are NAMED — a field's name is what the query surface mounts the \
node under, so a positional one would leave the mount unnamed",
));
};
if fields.named.is_empty() {
return Err(syn::Error::new_spanned(
&input.ident,
"a graph root with no field declares no node, and a walk over nothing is a walk nobody \
needs",
));
}
let mut seen: BTreeMap<String, (&syn::Field, bool)> = BTreeMap::new();
let mut nodes = Vec::with_capacity(fields.named.len());
let mut mounts = Vec::with_capacity(fields.named.len());
let mut queried = Vec::new();
let mut interfaces = Vec::new();
let mut fused = Vec::new();
let mut origins = Vec::new();
let mut resources = Vec::new();
for field in &fields.named {
reserve_the_grouping_key(field, errors);
reserve_the_registry_seat(field, errors);
reserve_the_retired_seat(field, errors);
reserve_the_generations_seat(field, errors);
let resource::Words {
resource: declared,
interface,
query,
fuse,
origin,
} = resource::words(field, errors);
let spelling = quote::ToTokens::to_token_stream(&field.ty).to_string();
if let Some((first, was_resource)) = seen.insert(spelling, (field, declared.is_some())) {
let first = first
.ident
.as_ref()
.map_or_else(String::new, ToString::to_string);
let message = if was_resource || declared.is_some() {
format!(
"this type is already in the graph, as `{first}` — a root lists each member ONCE, and \
two fields naming one resource would declare it twice under two mounts"
)
} else {
format!(
"this node is already in the graph, as `{first}` — a graph lists each node ONCE, \
and a second field naming one mounts the same storage under two names"
)
};
errors.push(syn::Error::new_spanned(&field.ty, message));
continue;
}
let Some(mount) = field.ident.clone() else {
continue;
};
match declared {
Some(resource::Declaration { source, teardown }) => resources.push(ResourceField {
mount,
ty: field.ty.clone(),
source,
teardown,
}),
None if interface => interfaces.push(InterfaceMount {
mount,
ty: field.ty.clone(),
queried: query,
}),
None if fuse => fused.push(FusedMember {
mount,
ty: field.ty.clone(),
queried: query,
}),
None if origin => origins.push(OriginMount {
mount,
ty: field.ty.clone(),
}),
None => {
if query {
queried.push(field.ty.clone());
}
nodes.push(field.ty.clone());
mounts.push(mount);
}
}
}
Ok(Members {
nodes,
mounts,
queried,
interfaces,
fused,
origins,
resources,
})
}
fn reserve_the_grouping_key(field: &syn::Field, errors: &mut Errors) {
let Some(mount) = &field.ident else {
return;
};
if mount != RESERVED_MOUNT {
return;
}
errors.push(syn::Error::new_spanned(
mount,
format!(
"`{RESERVED_MOUNT}` is a RESERVED mount on a graph root — the emitted options spine groups \
every resource's section under it (`[{RESERVED_MOUNT}.<field>]`), so a member of that name \
would be a second meaning for one document key; rename the field"
),
));
}
fn reserve_the_registry_seat(field: &syn::Field, errors: &mut Errors) {
let Some(mount) = &field.ident else {
return;
};
if mount != RESERVED_REGISTRY_MOUNT {
return;
}
errors.push(syn::Error::new_spanned(
mount,
format!(
"`{RESERVED_REGISTRY_MOUNT}` is a RESERVED mount on a graph root — the emitted options \
spine holds the root-key registry's own timing under it (`[{RESERVED_REGISTRY_MOUNT}]`, \
`[{RESERVED_REGISTRY_MOUNT}.<family>]`), so a member of that name would be a second meaning \
for one document key; rename the field"
),
));
}
fn reserve_the_retired_seat(field: &syn::Field, errors: &mut Errors) {
let Some(mount) = &field.ident else {
return;
};
if mount != RESERVED_RETIRED_MOUNT {
return;
}
errors.push(syn::Error::new_spanned(
mount,
format!(
"`{RESERVED_RETIRED_MOUNT}` is a RESERVED mount on a graph root — the emitted options spine \
holds the retired ledger's own connection under it (`[{RESERVED_RETIRED_MOUNT}]`), so a \
member of that name would be a second meaning for one document key; rename the field"
),
));
}
fn reserve_the_generations_seat(field: &syn::Field, errors: &mut Errors) {
let Some(mount) = &field.ident else {
return;
};
if mount != RESERVED_GENERATIONS_MOUNT {
return;
}
errors.push(syn::Error::new_spanned(
mount,
format!(
"`{RESERVED_GENERATIONS_MOUNT}` is a RESERVED mount on a graph root — the emitted options \
spine holds the generations seat's own connection and retention under it \
(`[{RESERVED_GENERATIONS_MOUNT}]`), so a member of that name would be a second meaning for \
one document key; rename the field"
),
));
}