use ingraph_codegen::prelude::*;
use quote::{ToTokens as _, format_ident};
use syn::ext::IdentExt as _;
use crate::{
alias,
attribute::{self, named, set_once},
column,
errors::Errors,
suggest, value, wire,
};
pub(crate) fn parse(
input: &syn::DeriveInput,
options: &[syn::Attribute],
kind: NodeKind,
) -> syn::Result<RecordModel> {
let record = &input.ident;
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let Options {
krate,
key_rename,
lineage: lineage_block,
persist: persist_block,
graphql: graphql_block,
derived: derived_block,
locate: locate_block,
implements,
subscribe,
subscribe_at,
subscriptions,
products,
polls,
teardown,
asynchronous,
streaming,
autonomous,
attributed,
options: options_type,
remote,
construction,
upstreams,
errors: mut declared_errors,
tracing,
receipt,
} = record_options(options, kind, &mut errors);
concrete(&input.generics, kind, &mut errors);
if remote.is_some() {
crate::remote::refuse_a_representation(&input.attrs, &mut errors);
}
let key_name = key_rename
.clone()
.unwrap_or_else(|| default_key_name(record));
let lineage_rename = lineage_block
.as_ref()
.and_then(|block| block.rename.clone());
let lineage_name = lineage_block.as_ref().map(|_| {
lineage_rename
.clone()
.unwrap_or_else(|| default_lineage_name(record))
});
let fields = match named_fields(input, kind) {
Ok(fields) => fields,
Err(terminal) => return Err(errors.seal(terminal)),
};
let mut marked: Vec<(&syn::Field, Markers)> = Vec::new();
let mut id: Option<&syn::Field> = None;
for field in &fields.named {
if field.ident.is_none() {
continue;
}
let markers = field_markers(&field.attrs, kind, &mut errors);
if remote.is_some() {
crate::remote::refuse_an_unplaceable_attribute(field, &mut errors);
}
if markers.id.is_some() {
match id {
Some(first) => errors.push(syn::Error::new_spanned(
field.ident.as_ref().expect("a named field"),
format!(
"{article} {noun} needs exactly one `#[ingraph(id)]` field; `{}` already carries it",
first.ident.as_ref().expect("a named field"),
article = kind.article(),
noun = kind.noun(),
),
)),
None => id = Some(field),
}
}
marked.push((field, markers));
}
let of = |name: &syn::Ident| {
marked
.iter()
.find(|(field, _)| field.ident.as_ref() == Some(name))
};
let parent = key_parent(record, kind, &upstreams, subscribe_at.as_ref(), &mut errors);
let subscriptions = fan_in(record, subscriptions, &mut errors);
let products = declared_products(record, products, &mut errors);
let polls = poll_sources(record, polls, &mut errors);
streaming_word(kind, streaming.as_ref(), polls.as_ref(), &mut errors);
autonomous_word(kind, autonomous.as_ref(), streaming.as_ref(), &mut errors);
let mut path: Vec<(&syn::Field, syn::Ident)> = Vec::new();
for LineageField { name, from } in lineage_block.into_iter().flat_map(|block| block.fields) {
if from.is_some() && parent.is_none() {
errors.push(syn::Error::new_spanned(
&name,
format!(
"`{name}(source = \"…\")` maps a column onto a field of the PARENT's key, and {article} \
{noun} that does not fuse has no designated parent to map onto — its lineage is its own \
columns. The designation is `upstream(node = \"path::To::Upstream\", key)`",
article = kind.article(),
noun = kind.noun(),
),
));
}
if id.is_some_and(|field| field.ident.as_ref() == Some(&name)) {
errors.push(syn::Error::new_spanned(
&name,
format!(
"the `#[ingraph(id)]` field `{name}` cannot also be a lineage field — a key is \
lineage ⊕ the id, and the id is already its last column"
),
));
} else if path
.iter()
.any(|(field, _)| field.ident.as_ref() == Some(&name))
{
errors.push(syn::Error::new_spanned(
&name,
format!("`{name}` is named twice in `lineage(fields(…))` — a lineage field is one column"),
));
} else if let Some((field, _)) = of(&name) {
path.push((field, from.unwrap_or(name)));
} else {
errors.push(syn::Error::new_spanned(
&name,
format!("`lineage(fields(…))` names fields of this struct — `{name}` is not one"),
));
}
}
let steps: Vec<&syn::Ident> = path
.iter()
.map(|(field, _)| field.ident.as_ref().expect("a named field"))
.collect();
let mut address: Vec<syn::Ident> = Vec::new();
for (field, markers) in &marked {
let name = field.ident.as_ref().expect("a named field");
let in_key = id.is_some_and(|id| id.ident.as_ref() == Some(name)) || steps.contains(&name);
if in_key {
address.push(name.clone());
}
let in_lineage = steps.contains(&name);
if let Some(rename) = &markers.key
&& !in_key
{
errors.push(no_subject(
&rename.at,
name,
"key",
"the `#[ingraph(id)]` field and the fields named in `lineage(fields(…))`",
));
}
if let Some(rename) = &markers.lineage
&& !in_lineage
{
errors.push(no_subject(
&rename.at,
name,
"lineage",
"the fields named in `lineage(fields(…))`",
));
}
if let (Some(label), true) = (&markers.label, in_key) {
errors.push(label.refuse(key_side_label(name)));
}
refuse_a_storage_word_no_label_can_order(markers, in_key, &mut errors);
refuse_a_skip_the_record_cannot_survive(markers, name, in_key, in_lineage, &mut errors);
}
let projections: Vec<(syn::Ident, Projection)> = marked
.iter()
.map(|(field, markers)| {
let name = field.ident.clone().expect("a named field");
let projection = markers.projection(&name, &mut errors);
(name, projection)
})
.collect();
let projection = |name: &syn::Ident| {
projections
.iter()
.find(|(marked, _)| marked == name)
.map_or(Projection::Borrowed, |(_, projection)| *projection)
};
let column = |field: &syn::Field, scope: Scope| {
let source = field.ident.clone().expect("a named field");
let markers = of(&source).map(|(_, markers)| markers);
let rename = markers.and_then(|markers| match scope {
Scope::Key => markers.key.as_ref(),
Scope::Lineage => markers.lineage.as_ref(),
});
Column {
name: rename.map_or_else(|| source.clone(), |rename| rename.name.clone()),
project: projection(&source),
ty: field.ty.clone(),
source,
}
};
let key_path: Vec<Column> = path
.iter()
.map(|(field, _)| column(field, Scope::Key))
.collect();
let lineage_columns: Vec<Column> = path
.iter()
.map(|(field, _)| column(field, Scope::Lineage))
.collect();
let key_id = id.map(|field| column(field, Scope::Key));
let mirrors: Vec<Mirror> = lineage_columns
.iter()
.zip(&path)
.map(|(column, (_, from))| Mirror {
column: column.name.clone(),
from: from.clone(),
})
.collect();
let fence = alias::Fence::over(
persist_block
.iter()
.flat_map(|block| block.databases.iter())
.map(|db| db.aliases.prefix.as_deref()),
);
for (type_name, columns) in [
(key_name.to_string(), key_path.iter().chain(key_id.as_ref())),
(
lineage_name
.as_ref()
.map_or_else(String::new, ToString::to_string),
lineage_columns.iter().chain(None),
),
] {
if type_name.is_empty() {
continue;
}
let mut taken: Vec<&syn::Ident> = Vec::new();
for column in columns {
column::refuse_framework_namespace(&fence, &column.name, &mut errors);
if taken.contains(&&column.name) {
errors.push(syn::Error::new_spanned(
&column.name,
format!(
"`{type_name}` would have two columns called `{}` — a rename is scoped to one type, \
and within it every column needs its own name",
column.name
),
));
}
taken.push(&column.name);
}
}
let (Some(id), Some(key_id)) = (id, key_id) else {
return Err(errors.seal(syn::Error::new_spanned(
record,
format!(
"{article} {noun} needs exactly one `#[ingraph(id)]` field; this struct declares none",
article = kind.article(),
noun = kind.noun(),
),
)));
};
let id_name = id.ident.clone().expect("a named field");
let upstreams = match parent {
Some(Mode::Fused { parent, others }) if mirrors.is_empty() => {
errors.push(syn::Error::new_spanned(
record,
format!(
"{article} {noun} that designates a key parent has no lineage to check against — its \
lineage IS that parent's key, mirrored column by column, so the block naming the columns \
is `lineage(fields(…))` and a fusion writes one. Where a column's name differs from the \
parent's, `<field>(source = \"…\")` maps it",
article = kind.article(),
noun = kind.noun(),
),
));
let _ = (parent, others);
None
}
Some(Mode::Fused { parent, others }) => Some(Upstreams::Fused(Fusion {
parent,
others,
mirrors,
})),
Some(Mode::Fanned(fanned)) => {
if !mirrors.is_empty() {
errors.push(syn::Error::new_spanned(
record,
format!(
"{article} {noun} drawing from several upstreams with none designated `key` has its \
ancestry decided per ROW — each row descends from whichever upstream produced it — so \
its lineage is a CHOICE among them and `lineage(fields(…))` names a path it does not \
have. Designate one upstream with `key` to make the upstreams JOIN, whose lineage is \
that parent's key and is spelled by that block",
article = kind.article(),
noun = kind.noun(),
),
));
}
Some(Upstreams::Fanned(fanned))
}
None => None,
};
let own = marked
.iter()
.map(|(field, markers)| {
let name = field.ident.clone().expect("a named field");
let identity = name == id_name || steps.contains(&&name);
if identity {
crate::attribute::refuse_a_conditional_identity(field, &mut errors);
}
if markers.reference().is_some() {
crate::attribute::refuse_a_conditional_reference(field, &mut errors);
}
Field {
column: Column {
project: projection(&name),
ty: field.ty.clone(),
source: name.clone(),
name,
},
identity,
marker: markers.label.as_ref().map(Written::marker),
sortable: markers.storage.sortable.is_some(),
indexed: markers.storage.indexed.is_some(),
reference: markers.reference(),
skip: markers.skip.as_ref().map(SkipField::fill),
docs: if remote.is_some() {
crate::remote::docs(field)
} else {
Vec::new()
},
condition: crate::attribute::condition(field, remote.is_some(), &mut errors),
build: markers.build.clone().unwrap_or_default(),
}
})
.collect();
crate::construct::refuse_without_a_remote(
remote.as_ref(),
construction
.as_ref()
.and_then(|written| written.at.as_ref()),
marked
.iter()
.filter_map(|(_, markers)| markers.build.as_ref()?.at.clone()),
kind.noun(),
&mut errors,
);
let construction = construction.unwrap_or_default();
let described: Vec<(syn::Ident, Build)> = marked
.iter()
.filter_map(|(field, markers)| {
Some((
field.ident.clone().expect("a named field"),
markers.build.clone()?,
))
})
.collect();
crate::construct::refuse_a_homeless_argument(&construction, &described, &mut errors);
for database in persist_block.iter().flat_map(|block| &block.databases) {
for (leg, cell) in [
(Crossing::PersistRead, database.into.cell.clone()),
(Crossing::PersistWrite, database.from.cell.clone()),
] {
if let Some(path) = cell {
declared_errors.push(BackendError {
crossing: leg,
kind: database.kind,
path,
});
}
}
}
let persist = persist_model(
record,
kind,
persist_block,
&fence,
&marked,
&address,
&mut errors,
);
if upstreams.as_ref().and_then(Upstreams::fanned).is_some() && persist.is_some() {
errors.push(syn::Error::new_spanned(
record,
format!(
"{article} {noun} drawing from several independent upstreams stores its rows in the SPLIT \
LAYOUT — one common table holding the id, the discriminant and the uniform payload, and \
one provenance table per upstream holding that variant's ancestors — and the READ that \
raises a common row back into a {noun} has not arrived. Its ancestry is a CHOICE among the \
upstreams, and a choice has no empty state to decode into: a collection's row starts out \
empty and a second statement fills it, where this one has nothing to start out as, so the \
provenance read is what makes the row constructible rather than a way to make it complete. \
Designate one upstream with `key` to make the upstreams JOIN, whose lineage is columns of \
the row itself and ships today",
article = kind.article(),
noun = kind.noun(),
),
));
}
let progress = progress_model(persist.as_ref());
let order_by = order_by_name(record, graphql_block.as_ref());
let key_argument_at = graphql_block
.as_ref()
.and_then(|block| block.key_argument.clone());
let graphql = graphql_model(
record,
kind,
graphql_block,
persist.as_ref(),
&marked,
&mut errors,
);
let derived = derived_model(derived_block, &marked, &mut errors);
let artifacts = locate_model(locate_block, &marked, &derived, &mut errors);
let (lineage, key_path) = match upstreams.as_ref().and_then(Upstreams::fanned) {
Some(fanned) => {
let name = lineage_rename
.clone()
.unwrap_or_else(|| default_lineage_name(record));
let column = Column {
name: fanned_lineage_column(),
source: fanned_lineage(&EmissionPrefix::default()),
ty: syn::parse_quote!(#name),
project: Projection::Borrowed,
};
if key_path
.iter()
.chain([&key_id])
.any(|taken| taken.name == column.name)
{
errors.push(syn::Error::new_spanned(
record,
format!(
"`{key_name}` would have two columns called `{}` — one is this {noun}'s ancestry, which \
is a CHOICE among the upstreams it draws from and takes that name in every key. Rename \
the other, or the type through `key(rename = \"…\")`",
column.name,
noun = kind.noun(),
),
));
}
(
Some(Lineage {
name,
shape: Shape::Kinds(fanned.kinds.clone()),
}),
vec![column],
)
}
None => (
lineage_name.map(|name| Lineage {
name,
shape: Shape::Path(lineage_columns),
}),
key_path,
),
};
if remote.is_some() && upstreams.as_ref().and_then(Upstreams::fanned).is_some() {
errors.push(syn::Error::new_spanned(
record,
format!(
"{article} {noun} that WRAPS a foreign type cannot also draw from several independent \
upstreams — a fan-in's ancestry is a CHOICE among them, carried in a field this macro \
mints, and a transparent wrapper's one position is the wrapped type. Designate one \
upstream with `key`, whose lineage is columns the manifest already names",
article = kind.article(),
noun = kind.noun(),
),
));
}
let model = RecordModel {
prefix: EmissionPrefix::default(),
record: record.clone(),
kind,
vis: input.vis.clone(),
krate,
remote,
construction,
key: Key {
name: key_name,
path: key_path,
id: key_id,
},
lineage,
fields: own,
persist,
order_by,
progress,
graphql,
derived,
artifacts,
implements,
subscribe,
subscriptions,
products,
polls,
teardown,
asynchronous,
streaming,
autonomous,
attributed,
options: options_type,
upstreams,
errors: declared_errors,
tracing,
receipt,
};
emitted_names(&model, &mut errors);
emitted_methods(&model, &mut errors);
derived_plural(&model, &mut errors);
key_faces(&model, key_argument_at.as_ref(), &mut errors);
errors.into_result(model)
}
fn streaming_word(
kind: NodeKind,
streaming: Option<&syn::Path>,
polls: Option<&Polls>,
errors: &mut Errors,
) {
let Some(word) = streaming else {
return;
};
if !matches!(kind, NodeKind::Operator) {
errors.push(syn::Error::new_spanned(
word,
format!(
"`stream` is an `operator`'s word, and {article} {noun} may not write it. The streaming \
pair is the COMPUTE seam's other pair — a body whose per-item fan-out GROWS WITH THE \
INPUT, streamed out through a bounded `Feed` over one delivery's whole life — and what \
drives one is a lane holding a warm set and a downstream set, with no write lane in it. \
Declare the streaming half as an `operator` and let {article} {noun} subscribe to what it \
emits",
article = kind.article(),
noun = kind.noun(),
),
));
}
if let Some(polls) = polls {
for clock in &polls.entries {
errors.push(syn::Error::new_spanned(
&clock.name,
"`poll(…)` is the BUFFERED pair's word and cannot stand beside `stream`. A tick is one \
call against the node's own value, which the driver LENDS for that call — and a \
stream-faced node has no value to lend: its bodies are the lane's warm set, and each one \
is owned by a delivery's run for that delivery's whole life. The face is chosen by the \
FAN-OUT one delivered item produces, so a node that both streams and wakes on a clock is \
two nodes: drop `stream` here, or move the clock onto a node of its own"
.to_owned(),
));
}
}
}
fn autonomous_word(
kind: NodeKind,
autonomous: Option<&syn::Path>,
streaming: Option<&syn::Path>,
errors: &mut Errors,
) {
let Some(word) = autonomous else {
return;
};
if !matches!(kind, NodeKind::Operator) {
errors.push(syn::Error::new_spanned(
word,
format!(
"`autonomous` is an `operator`'s word, and {article} {noun} may not write it. The \
autonomous kind is the COMPUTE seam's third one — a body that owns its own loop over its \
inbound edges, its downstream set and its stop — and what mounts one is a thread with no \
write lane in it. Declare the autonomous half as an `operator` and let {article} {noun} \
subscribe to what it emits",
article = kind.article(),
noun = kind.noun(),
),
));
}
if let Some(stream) = streaming {
errors.push(syn::Error::new_spanned(
stream,
"`stream` and `autonomous` are values of ONE axis, and a declaration wears exactly one kind. \
`stream` is the face where one delivery is one whole life and the per-delivery parallelism \
AND the fate bookkeeping are the FRAMEWORK's — a demux, whose lane holds the warm set, the \
admission bound and the dead-letter. `autonomous` is take-the-wheel-keep-the-books: the \
node owns its select order, its arm priority, its intake gating, its ack timing and its own \
workers. Write whichever one this body is, and put `async` beside it where the body awaits"
.to_owned(),
));
}
}
fn key_faces(model: &RecordModel, argument: Option<&syn::LitStr>, errors: &mut Errors) {
let Some(written) = argument else {
return;
};
if model.key.compound() {
return;
}
errors.push(syn::Error::new_spanned(
written,
format!(
"`input` names the object a client SENDS this address in, and `{record}` is a ROOT: its \
address is its id alone, so it crosses inward as that id's own wire form and no `KeyInput` \
type is minted for a word to move. What a client sends is `{record_lower}(id: …)`, whose \
argument type is the id column's own. The word opens where the record has a LINEAGE — a \
compound address is a product a client has to name — and `output(rename = \"…\")` beside it \
names the object an address is READ back in, which every record has",
record = model.record,
record_lower = {
use heck::ToLowerCamelCase as _;
model.record.to_string().to_lower_camel_case()
},
),
));
}
#[derive(Clone, Copy)]
enum Scope {
Key,
Lineage,
}
enum Mode {
Fused {
parent: syn::Path,
others: Vec<syn::Path>,
},
Fanned(FanIn),
}
fn key_parent(
record: &syn::Ident,
kind: NodeKind,
upstreams: &[UpstreamBlock],
subscribe: Option<&syn::Path>,
errors: &mut Errors,
) -> Option<Mode> {
if upstreams.is_empty() {
return None;
}
if let Some(subscribe) = subscribe {
errors.push(syn::Error::new_spanned(
subscribe,
format!(
"`{record}` names its upstreams twice — `upstream(…)` beside `subscribe`. One node \
has one spelling of its edge: `subscribe` names the fan-in, in the short form for a node \
driven by one upstream or in the container form for a node drawing from several, and \
`upstream(…)` at the top level is the form that also designates which upstream this \
{noun}'s identity comes from",
noun = kind.noun(),
),
));
}
let mut designated: Option<&UpstreamBlock> = None;
for source in upstreams {
if source.node.is_none() {
errors.push(syn::Error::new_spanned(
&source.at,
"`upstream(…)` needs `node = \"path::To::Upstream\"` — an entry with no upstream names \
nothing, and `key` beside it would designate nothing",
));
}
let Some(key) = &source.key else { continue };
match designated {
Some(first) => errors.push(syn::Error::new_spanned(
key,
format!(
"two upstreams are designated `key`, and {article} {noun} descends from ONE — its \
lineage is that upstream's key, and a lineage cannot be two paths at once. `{}` already \
carries the designation; the other upstream's provenance is an ordinary `ref = \"…\"` \
field, which is opt-in and says which column holds it",
first
.node
.as_ref()
.map_or_else(|| "the entry above".to_owned(), path_text),
article = kind.article(),
noun = kind.noun(),
),
)),
None => designated = Some(source),
}
}
let Some(source) = designated else {
return fanned(record, upstreams, errors).map(Mode::Fanned);
};
Some(Mode::Fused {
parent: source.node.clone()?,
others: upstreams
.iter()
.filter(|other| !core::ptr::eq(*other, source))
.filter_map(|other| other.node.clone())
.collect(),
})
}
fn fanned(record: &syn::Ident, upstreams: &[UpstreamBlock], errors: &mut Errors) -> Option<FanIn> {
let mut kinds: Vec<Kind> = Vec::new();
for source in upstreams {
let Some(node) = source.node.clone() else {
continue;
};
let variant = node
.segments
.last()
.expect("a path has at least one segment")
.ident
.clone();
if let Some(first) = kinds.iter().find(|kind| kind.variant == variant) {
errors.push(syn::Error::new_spanned(
&source.at,
format!(
"`{record}` draws from two upstreams whose names agree — `{}` and `{}` both end in \
`{variant}`, and that word is what names the variant this one's rows descend from. It is \
read off the path rather than declared, so a reader of a stored address can find the \
upstream it came from; two upstreams cannot share it",
path_text(&first.node),
path_text(&node),
),
));
continue;
}
kinds.push(Kind { node, variant });
}
(!kinds.is_empty()).then_some(FanIn { kinds })
}
fn path_text(path: &syn::Path) -> String {
path
.segments
.iter()
.map(|segment| segment.ident.to_string())
.collect::<Vec<_>>()
.join("::")
}
fn no_subject(at: &syn::Path, field: &syn::Ident, scope: &str, reaches: &str) -> syn::Error {
syn::Error::new_spanned(
at,
format!(
"`{scope}(rename = \"…\")` names `{field}`'s column in the `{scope}` type, and `{field}` \
has none there — only {reaches} reach it. A data column's rename will be its own scope \
once the persisted row is emitted; it is not this one."
),
)
}
struct Options {
krate: syn::Path,
key_rename: Option<syn::Ident>,
lineage: Option<LineageBlock>,
persist: Option<PersistBlock>,
graphql: Option<GraphqlBlock>,
derived: Option<DerivedBlock>,
locate: Option<LocateBlock>,
implements: Vec<syn::Path>,
subscribe: Option<syn::Path>,
subscribe_at: Option<syn::Path>,
subscriptions: Option<SubscribeBlock>,
products: Option<EmitsWord>,
polls: Vec<PollBlock>,
teardown: bool,
asynchronous: Option<syn::Path>,
streaming: Option<syn::Path>,
autonomous: Option<syn::Path>,
attributed: bool,
options: Option<syn::Path>,
remote: Option<syn::Path>,
construction: Option<Construction>,
upstreams: Vec<UpstreamBlock>,
errors: Vec<BackendError>,
tracing: Option<TracingLevel>,
receipt: Option<syn::Path>,
}
struct DerivedBlock {
entries: Vec<DerivedEntry>,
at: syn::Path,
}
struct DerivedEntry {
name: syn::Ident,
source: syn::Path,
field: Option<syn::LitStr>,
}
struct LocateBlock {
entries: Vec<LocateEntry>,
at: syn::Path,
}
struct LocateEntry {
name: syn::Ident,
family: syn::Path,
data: Option<LocateData>,
required: bool,
}
struct LocateData {
at: syn::Path,
rename: Option<syn::LitStr>,
required: bool,
}
struct GraphqlBlock {
backends: Vec<BackendBlock>,
output: Option<syn::Ident>,
key: Option<syn::Ident>,
key_object: Option<syn::LitStr>,
key_argument: Option<syn::LitStr>,
filter: Option<syn::Ident>,
order_by: Option<syn::Ident>,
connection: Option<syn::LitStr>,
edge: Option<syn::LitStr>,
rename: Option<syn::Ident>,
plural: Option<syn::LitStr>,
at: syn::Path,
}
struct BackendBlock {
kind: GraphqlKind,
rename: Option<syn::Ident>,
attrs: Option<proc_macro2::TokenStream>,
}
struct WireField {
at: syn::Path,
rename: Option<syn::LitStr>,
ty: Option<syn::Type>,
output: Vec<WireLeg>,
comparison: Vec<WireLeg>,
skip: Option<syn::Path>,
per_backend: Vec<FieldBackend>,
}
impl WireField {
fn unrefined(field: &syn::Ident) -> Self {
Self {
at: syn::Path::from(field.clone()),
rename: None,
ty: None,
output: Vec::new(),
comparison: Vec::new(),
skip: None,
per_backend: Vec::new(),
}
}
}
fn wire_legs(
inner: &syn::meta::ParseNestedMeta<'_>,
legs: &mut Vec<WireLeg>,
scope: &str,
direction: Direction,
errors: &mut Errors,
) -> syn::Result<()> {
attribute::options(inner, |db| {
let Some(kind) = database_kind(&db.path) else {
if db.path.is_ident("field") {
errors.push(named(
&db,
format!(
"`field` names the OUTPUT OBJECT's accessor for a field, and this block is the \
row-to-wire CROSSING — write `graphql(<backend>(output(field = \"…\")))`. `{scope}`'s \
own entries are per database, because a crossing has a row on one side of it."
),
));
return Ok(());
}
errors.push(attribute::unknown(
&db,
&format!(
"unknown entry in `{scope}` — a leg opens the DATABASE's block whose row it crosses, \
because a row is one database's: {list}",
list = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
),
&DatabaseKind::ALL.map(DatabaseKind::as_str),
));
return Ok(());
};
if legs.iter().any(|leg| leg.kind == kind) {
errors.push(syn::Error::new_spanned(
&db.path,
format!(
"`{kind}` is declared more than once in `{scope}` — one leg per database",
kind = kind.as_str()
),
));
}
let (mut builds, mut leaves) = (ConversionSpec::default(), ConversionSpec::default());
let walked = attribute::options(&db, |option| {
let wrong = if direction.plain == "from" {
[("into", "try_into")]
} else {
[("from", "try_from")]
};
for (plain, fallible) in wrong {
if option.path.is_ident(plain) || option.path.is_ident(fallible) {
errors.push(named(
&option,
format!(
"`{scope}` takes `{}`/`{}` — `from` BUILDS the projection its block is about and \
`into` LEAVES it, so an output leg is written with `from` and an input one with \
`into`",
direction.plain, direction.fallible
),
));
return Ok(());
}
}
if conversion(
&option,
&mut builds,
&mut leaves,
scope,
Cells::Elsewhere,
errors,
) {
return Ok(());
}
errors.push(attribute::unknown(
&option,
&format!(
"unknown entry in `{scope}`'s `{kind}` block — a leg is the conversion and nothing else: \
`{}`/`{}`, in the short form or the structured one",
direction.plain,
direction.fallible,
kind = kind.as_str()
),
&[direction.plain, direction.fallible],
));
Ok(())
});
let spec = if direction.plain == "from" {
&builds
} else {
&leaves
};
let conversion = spec.resolve(
&format!("`{scope}`'s `{}` leg", kind.as_str()),
direction,
errors,
);
if matches!(conversion, Conversion::Default) {
errors.push(syn::Error::new_spanned(
&db.path,
format!(
"`{kind}` names no conversion in `{scope}` — a leg exists to REPLACE the default chain, \
so an empty one says nothing the absence of the block does not already say",
kind = kind.as_str()
),
));
} else {
legs.push(WireLeg { kind, conversion });
}
walked
})
}
fn label_shape() -> String {
format!(
"a field's label is the interpretation its type is read under — write {list}, a collection's \
element inside it (`list(string)`), or any other marker's path in a string literal",
list = shipped(Label::ALL.into_iter().map(Label::as_str)),
)
}
fn marker_is_the_older_spelling(meta: &syn::meta::ParseNestedMeta<'_>) -> String {
let Some(write) = written_instead(meta) else {
return format!(
"`marker` is not an option — a field's label is its own word, at the TOP level beside \
`persist` and `graphql`: {list}, a collection's element inside it (`list(string)`), or \
`label = \"a::marker::Path\"`",
list = shipped(Label::ALL.into_iter().map(Label::as_str)),
);
};
format!(
"`marker` is not an option — a field's label is its own word, at the TOP level: write \
`{write}` beside `persist` and `graphql`, where this went inside `graphql(…)`. A label is a \
fact about the field's KIND rather than about one of its faces, and it feeds storage as surely \
as it feeds the filter."
)
}
fn written_instead(meta: &syn::meta::ParseNestedMeta<'_>) -> Option<String> {
let fork = meta.input.fork();
fork.parse::<syn::Token![=]>().ok()?;
if fork.peek(syn::LitStr) {
let path = fork.parse::<syn::LitStr>().ok()?;
return Some(format!("label = {:?}", path.value()));
}
let word = syn::Ident::parse_any(&fork).ok()?.unraw();
let label = Label::ALL
.into_iter()
.find(|label| word == label.as_str())?;
Some(if label.collection() {
format!("{word}(<the element's own word>)")
} else {
word.to_string()
})
}
fn unknown_element(word: &syn::Ident) -> String {
format!(
"`{word}` is not an interpretation this framework names — a collection's element is one of \
{list}, and an element-level custom marker is reserved",
list = shipped(Label::ALL.into_iter().map(Label::as_str)),
)
}
const LABEL: &str = "label";
const REFERS: &str = "ref";
const REF_SHAPE: &str = "`ref` names the record a field refers to — write \
`ref = \"path::to::Type\"`, or `ref(type = \"path::to::Type\")` where the \
relation needs more than a target. The path is a TYPE PATH in a string \
literal, and it resolves in the declaring scope.";
const REF_TYPE: &str = "`type` names the record this field refers to, as a type path in a string \
literal";
const DERIVED_SHAPE: &str = "a reverse position is `<name> = \"path::to::Source\"`, or \
`<name>(type = \"path::to::Source\", field = \"…\")` where the source \
refers to this record through more than one field. The NAME is what \
this record calls the position; the path is the record that points \
back.";
const LOCATE_SHAPE: &str = "an artifact position is `<name> = \"path::to::Family\"`, or \
`<name>(family = \"path::to::Family\", data)` where the position also \
asks for the bytes. The NAME is the word this record answers the \
address under; the path is the `#[ingraph::blob]` node that holds the \
artifacts — the TYPE, not a field inside it.";
const LOCATE_FAMILY_MISSING: &str = "an artifact position's full form names the family it addresses \
— write `family = \"path::to::Family\"` inside it. A position \
that asks for nothing else is spelled `<name> = \
\"path::to::Family\"`.";
const LOCATE_FAMILY: &str = "`family` names the `#[ingraph::blob]` node this position addresses, as \
a type path in a string literal";
const LOCATE_OPTIONS: &str = "unknown entry in an artifact position — it takes `family = \"…\"`, \
the `data` ask, and `required`, which publishes the ADDRESS as \
`BlobLocation!`. There is no word for the nullable form: it is what \
you get by leaving `required` out";
const LOCATE_WORDS: [&str; 3] = ["family", "data", REQUIRED];
const LOCATE_SIBLINGS_WORDS: &str = "`type` and `field` are `derived(…)`'s option words. An \
artifact position names its family with `family = \
\"path::to::Family\"`, and it is derived from ONE upstream — \
so there is no second `ref` column for a `field` to select.";
const LOCATE_DATA_SHAPE: &str = "the `data` ask is written bare, `data = \"thumbBytes\"` to name \
the wire field, or `data(rename = \"…\", required)` to say both. \
The default name is `<name>Data`, off this position's own word.";
const LOCATE_DATA_RENAME: &str = "`rename` names the wire field, in a string literal — \
`data(rename = \"thumbBytes\")`";
const LOCATE_DATA_OPTIONS: &str = "unknown entry in a `data(…)` ask — it takes `rename = \"…\"`, \
which names the wire field, and `required`, which makes it \
`String!`. There is no word for the nullable form: it is what \
you get by leaving `required` out";
const LOCATE_DATA_WORDS: [&str; 2] = ["rename", REQUIRED];
const REQUIRED: &str = "required";
const LOCATE_REQUIRED_IS_BARE: &str = "`required` is a BARE word — write it and the field is \
non-null, leave it out and it is nullable. There is nothing \
for it to carry, and there is no inverse word either: \
nullable is what not writing this one means";
const LOCATE_MINTS_ITS_OWN_WORD: &str = "the left side of an artifact position is a WORD this \
record mints — `thumb`, `cover`, `poster` — and a path \
has nowhere to be minted from. The TYPE goes on the \
right, in a string literal: `cover = \
\"path::to::Family\"`.";
const MAP: &str = "map";
const MAP_RESERVED: &str = "`map` is RESERVED with the map family — this framework ships no map \
filter for a label to name, so the word arrives with the filter rather \
than before it";
const ELEMENT_CUSTOM: &str = "an element-level custom marker is RESERVED — a collection's element \
is one of the framework's words, and \
`label = \"a::marker::Path\"` is the FIELD's escape";
const NESTED_COLLECTION: &str = "no backend carries a collection of collections — a nested \
collection is a filter-face composition only";
pub(crate) const SORTABLE: &str = "sortable";
pub(crate) const INDEXED: &str = "indexed";
const INDEXED_NEEDS_A_COLLECTION_WORD: &str = "`indexed` at the FIELD is a COLLECTION's word — it puts a second index on the elements' own \
table, leading on the VALUE where the derived one leads on the key, so that *which rows hold \
this element* is a seek rather than a scan. A single column's index is a PER-DATABASE choice and \
is written in that database's own block, as `#[ingraph(sqlite(indexed))]`: nothing about one is \
visible to a client, so a declaration may want it in one store and not the next. Write a \
collection word here (`#[ingraph(list(scalar), indexed)]`), or move this one into a block.";
const INDEXED_READS_NO_PATH: &str = "`label = \"…\"` names a marker this grammar cannot classify — a path is a name here, not a family \
— and `indexed` is a COLLECTION's word, so nothing on this field says there are elements for a \
second index to lead on. A collection declares itself with `list(…)` or `set(…)`; a single \
column's index is its database's own block, as `#[ingraph(sqlite(indexed))]`";
const INDEXED_ONCE: &str = "`indexed` is declared more than once on this field — one word, one \
access path";
const DERIVED_COLUMN: &str = "derived";
const DERIVED_COLUMN_AT_A_RECORD: &str = "`derived(…)` at a RECORD's field is grammar this round and teeth the next. A column the write \
computes joins a layout, and a fragment has ONE layout to join — `ColumnKind::SEGMENTS`, carrying \
no dialect — while a record has one per database, plus the ordinal bind, the raise, the order-by \
vocabulary and the cursor slots that all walk the record's own FIELD list, where a column that is \
no field has no entry to occupy. Write the value as a `#[ingraph::fields(record(…))]` fragment \
and derive the column there, where the layout is one list and the position is the source field's \
own; the record then stores the fragment and gets the derived column with it";
const WRITE_TRANSFORM: &str = "write";
const READ_TRANSFORM: &str = "read";
const TRANSFORM_AT_A_RECORD: &str = "the transform seats are the FRAGMENT tier's, and at a record \
the two halves are already spelled: `#[ingraph(<db>(type = \"…\", into = \"…\", from = \"…\"))]` \
is the stored form and its crossings per database, and \
`#[ingraph::record(graphql(input(comparison(<db>(into = \"…\")))))]` converts the query operand \
that has to agree with the bind. A dialect-free `write`/`read` beside those would be a third \
spelling of one question, so it is not read here. The tier that HAS no per-dialect rendering \
word is where the pair lands: write the value as a `#[ingraph::fields(record(…))]` fragment and \
store the fragment — `record(write = \"…\")` on a FIELD there is a `fn(&T) -> T` over that \
column's type, and the same word at the fragment's HEAD is a `fn(&Self) -> Self` over the whole \
value, which is what a canonical form that reads several columns at once needs";
const SORTABLE_MOVED_INTO_PERSIST: &str = "`sortable` is the FIELD's own word now, not the label's \
— write `#[ingraph(list(scalar), sortable)]`. A label \
says what a column is READ AS and this says what the \
STORAGE does with one: the companion column is a fact \
about how the collection persists, so it is seated with \
the other storage words and composes with a database's \
own block as `#[ingraph(sortable, postgres(edge))]`.";
fn sortable_takes_a_collection(label: Label) -> String {
format!(
"`{word}` names a VALUE family and `sortable` orders a COLLECTION — a stored scalar is \
orderable because it is stored, so there is nothing for the word to add",
word = label.as_str(),
)
}
const SORTABLE_IS_A_LISTS_WORD: &str = "`set` declares that ORDER carries no meaning in this \
collection, and `sortable` is an order — the word belongs \
to a `list(…)`, whose elements have positions. A set \
ordered by its stored sequence would be ordered by \
something the declaration says is not there.";
const SORTABLE_NEEDS_A_COLLECTION_WORD: &str = "`sortable` orders a COLLECTION and a KEY-SIDE \
column declares no label at all — its vocabulary is \
the sealed `Id` trait, and an identity is one \
value. The word belongs on a data field carrying a \
collection's own word, as \
`#[ingraph(list(scalar), sortable)]`";
const SORTABLE_NEEDS_A_COLLECTION_WORD_HERE: &str = "`sortable` orders a COLLECTION and this column \
names no family at all — the word says the \
stored order is kept, and only a declaration \
can say a column IS a collection, a macro \
holding tokens being unable to read it out of \
a type. Write the collection's own word beside \
it, as \
`#[ingraph(list(scalar), sortable)]`";
const SORTABLE_READS_NO_PATH: &str = "`label = \"…\"` names a marker this grammar cannot classify — \
a path is a name here, not a family — and `sortable` orders a \
COLLECTION, so the two cannot be written together. A \
declaring crate that wants the companion column writes the \
collection's own word and names its element.";
const SORTABLE_ONCE: &str = "`sortable` is declared more than once on this field — one word, one \
collection";
const ONE_ELEMENT: &str = "a collection's label names ONE element — `list(string)`, never a list of \
labels";
const BARE_WORD: &str = "a family label is a bare WORD — write it alone, as in `string`; a marker \
this framework ships no word for goes in `label = \"a::marker::Path\"`";
const ONE_LABEL: &str = "a family label is declared more than once on this field — one label, one \
field";
pub(crate) struct Word {
label: Label,
at: syn::Ident,
}
pub(crate) struct Nested {
label: Label,
at: syn::Ident,
element: Box<Written>,
}
pub(crate) struct Custom {
path: syn::Path,
at: syn::Path,
}
pub(crate) enum Written {
Word(Word),
Nested(Nested),
Custom(Custom),
}
impl Written {
const fn collection(&self) -> bool {
match self {
Self::Word(Word { label, .. }) | Self::Nested(Nested { label, .. }) => label.collection(),
Self::Custom(_) => false,
}
}
const fn word(&self) -> Option<Label> {
match self {
Self::Word(Word { label, .. }) | Self::Nested(Nested { label, .. }) => Some(*label),
Self::Custom(_) => None,
}
}
pub(crate) fn marker(&self) -> Marker {
match self {
Self::Word(word) => Marker::Framework(FrameworkMarker {
label: word.label,
element: None,
}),
Self::Nested(nested) => Marker::Framework(FrameworkMarker {
label: nested.label,
element: match *nested.element {
Self::Word(Word { label, .. }) => Some(label),
Self::Nested(_) | Self::Custom(_) => None,
},
}),
Self::Custom(custom) => Marker::Path(custom.path.clone()),
}
}
pub(crate) fn refuse(&self, message: String) -> syn::Error {
match self {
Self::Word(Word { at, .. }) | Self::Nested(Nested { at, .. }) => {
syn::Error::new_spanned(at, message)
}
Self::Custom(custom) => syn::Error::new_spanned(&custom.at, message),
}
}
}
pub(crate) fn begins_a_label(path: &syn::Path) -> bool {
path.is_ident(LABEL) || path.is_ident(MAP) || family_word(path).is_some()
}
pub(crate) fn label(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> Option<Written> {
let declared = written(meta, errors)?;
shape(&declared, 0, errors);
Some(declared)
}
pub(crate) fn label_words() -> Vec<&'static str> {
Label::ALL
.into_iter()
.map(Label::as_str)
.chain(core::iter::once(LABEL))
.collect()
}
pub(crate) fn label_vocabulary() -> String {
format!(
"its interpretation WORD: {list}, a collection's element inside it (`list(string)`), or \
`label = \"a::marker::Path\"`",
list = shipped(Label::ALL.into_iter().map(Label::as_str)),
)
}
fn family_word(path: &syn::Path) -> Option<Label> {
let word = path.get_ident()?.unraw();
Label::ALL.into_iter().find(|label| word == label.as_str())
}
fn written(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> Option<Written> {
if meta.path.is_ident(LABEL) {
return match value::parse_literal::<syn::Path>(meta, &label_shape()) {
Ok(path) => Some(Written::Custom(Custom {
path,
at: meta.path.clone(),
})),
Err(e) => {
errors.push(e);
None
}
};
}
if meta.path.is_ident(MAP) {
errors.push(attribute::unknown(meta, MAP_RESERVED, &[]));
return None;
}
let Some(label) = family_word(&meta.path) else {
let spelled = meta.path.get_ident().cloned();
let message = spelled
.as_ref()
.map_or_else(label_shape, |spelled| unknown_element(&spelled.unraw()));
errors.push(attribute::unknown(
meta,
&message,
&Label::ALL
.into_iter()
.map(Label::as_str)
.chain(core::iter::once(SORTABLE))
.collect::<Vec<_>>(),
));
return None;
};
let at = meta
.path
.get_ident()
.cloned()
.expect("a family word is one ident");
if attribute::has_value(meta) {
errors.push(attribute::unknown(meta, BARE_WORD, &[]));
return None;
}
if !attribute::has_block(meta) || attribute::empty_group(meta) {
attribute::skip_entry(meta);
return Some(Written::Word(Word { label, at }));
}
let mut element: Option<Written> = None;
let mut extra = false;
let walked = meta.parse_nested_meta(|inner| {
if inner.path.is_ident(SORTABLE) {
errors.push(attribute::named(
&inner,
SORTABLE_MOVED_INTO_PERSIST.to_owned(),
));
return Ok(());
}
match (written(&inner, errors), &element) {
(Some(read), None) => element = Some(read),
(Some(_), Some(_)) => extra = true,
(None, _) => {}
}
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
if extra {
errors.push(syn::Error::new_spanned(&at, ONE_ELEMENT));
}
element.map(|element| {
Written::Nested(Nested {
label,
at,
element: Box::new(element),
})
})
}
fn shape(written: &Written, depth: usize, errors: &mut Errors) {
match written {
Written::Custom(_) => {
if depth > 0 {
errors.push(written.refuse(ELEMENT_CUSTOM.to_owned()));
}
}
Written::Word(word) => {
if word.label.collection() {
errors.push(written.refuse(bare_collection(word.label)));
}
}
Written::Nested(nested) => {
if !nested.label.collection() {
errors.push(written.refuse(value_takes_no_element(nested.label)));
} else if nested.element.collection() {
errors.push(written.refuse(NESTED_COLLECTION.to_owned()));
return;
}
shape(&nested.element, depth + 1, errors);
}
}
}
fn bare_collection(label: Label) -> String {
format!(
"`{word}` names a COLLECTION and a collection has elements — write the element's own label \
inside it, as in `{word}(string)`. Every level of a label names its family.",
word = label.as_str(),
)
}
fn value_takes_no_element(label: Label) -> String {
format!(
"`{word}` names a VALUE family and a value has no elements — an element label belongs to \
`list(…)` and `set(…)`",
word = label.as_str(),
)
}
fn refuse_a_storage_word_no_label_can_order(markers: &Markers, in_key: bool, errors: &mut Errors) {
if let Some(at) = markers.storage.sortable.as_ref() {
let refusal = match markers.label.as_ref() {
None if markers.label_refused => None,
None if in_key => Some(SORTABLE_NEEDS_A_COLLECTION_WORD.to_owned()),
None => Some(SORTABLE_NEEDS_A_COLLECTION_WORD_HERE.to_owned()),
Some(declared) => match declared.word() {
None => Some(SORTABLE_READS_NO_PATH.to_owned()),
Some(Label::Set) => Some(SORTABLE_IS_A_LISTS_WORD.to_owned()),
Some(Label::List) => None,
Some(word) => Some(sortable_takes_a_collection(word)),
},
};
if let Some(refusal) = refusal {
errors.push(syn::Error::new_spanned(at, refusal));
}
}
refuse_an_access_word_no_label_can_seek(markers, errors);
}
fn refuse_an_access_word_no_label_can_seek(markers: &Markers, errors: &mut Errors) {
let Some(at) = markers.storage.indexed.as_ref() else {
return;
};
let refusal = match markers.label.as_ref() {
None if markers.label_refused => return,
None => INDEXED_NEEDS_A_COLLECTION_WORD.to_owned(),
Some(declared) => match declared.word() {
None => INDEXED_READS_NO_PATH.to_owned(),
Some(Label::List | Label::Set) => return,
Some(_) => INDEXED_NEEDS_A_COLLECTION_WORD.to_owned(),
},
};
errors.push(syn::Error::new_spanned(at, refusal));
}
fn refuse_a_skip_the_record_cannot_survive(
markers: &Markers,
name: &syn::Ident,
in_key: bool,
in_lineage: bool,
errors: &mut Errors,
) {
if in_key {
let bearing = if in_lineage {
"is a step of the record's LINEAGE"
} else {
"is the record's `id`"
};
let storage = format!(
"`{name}` {bearing}, and `skip` says a field is not there — an address whose step is missing \
addresses nothing: no statement reaches the row, no key is rebuilt from it, and a fill would \
INVENT an identity rather than recover one. Identity is unskippable on both axes."
);
let wire = format!(
"`{name}` {bearing}, and `skip` withholds a field from the schema — the address is what a hit \
answers with, so a published key missing a step names no row a client can ask for again. \
Identity is unskippable on both axes."
);
if let Some(skip) = &markers.skip {
errors.push(syn::Error::new_spanned(&skip.at, storage));
}
if let Some(at) = markers
.graphql
.as_ref()
.and_then(|wired| wired.skip.as_ref())
{
errors.push(syn::Error::new_spanned(at, wire.clone()));
}
for per in markers
.graphql
.iter()
.flat_map(|wired| &wired.per_backend)
.filter_map(|backend| backend.skip.as_ref())
{
errors.push(syn::Error::new_spanned(per, wire.clone()));
}
let narrowed = markers
.storage
.per_db
.iter()
.filter(|per| per.bare || per.skip.is_some());
for per in narrowed {
errors.push(syn::Error::new_spanned(
&per.at,
format!(
"`{name}` {bearing}, and this word makes it a column of some of the record's databases \
and not the others — an address is `lineage ⊕ id` and every step of it is what a \
statement reaches the row BY, so a store that narrowed a step away addresses nothing and \
a fill there would INVENT an identity rather than recover one. It is also what a page \
resumes from. An address step is a column of every database the record declares."
),
));
}
}
if let (Some(skip), Some(at)) = (&markers.skip, markers.storage.at()) {
let word = at
.get_ident()
.map_or_else(|| "a storage word".to_owned(), |word| format!("`{word}`"));
errors.push(syn::Error::new_spanned(
&skip.at,
format!(
"`{name}` carries `skip` and {word} — one says the field is a column in NO database and the \
other describes the column it would be. Drop whichever is not meant: a field absent from \
SOME of the record's databases writes that database's own \
`#[ingraph(<db>(skip(default = \"…\")))]`, and one absent from all of them writes this \
word alone."
),
));
}
}
fn key_side_label(field: &syn::Ident) -> String {
format!(
"`{field}` is a key-side column and carries a family label — a key's vocabulary is the sealed \
`Id` trait, which is stronger than any word, so a key column writes none"
)
}
struct FieldBackend {
kind: GraphqlKind,
at: syn::Path,
input: Option<FaceBlock>,
output: Option<FaceBlock>,
skip: Option<syn::Path>,
}
pub(crate) fn graphql_kind(path: &syn::Path) -> Option<GraphqlKind> {
GraphqlKind::ALL
.into_iter()
.find(|kind| path.is_ident(kind.as_str()))
}
pub(crate) const PLURAL_WORD: &str = "`plural` is the entity's plural as a WORD, in a string literal — write \
`plural = \"corpora\"`";
const QUERYABILITY: &[&str] = &["filterable", "orderable"];
fn queryability(option: &syn::meta::ParseNestedMeta<'_>) -> Option<syn::Error> {
let name = QUERYABILITY
.iter()
.find(|name| option.path.is_ident(name))?;
Some(named(
option,
format!(
"`{name}` is not an option — a field carrying `persist` is filterable and orderable BECAUSE it \
is stored, and a field that is not stored has nothing to query"
),
))
}
struct LineageBlock {
fields: Vec<LineageField>,
rename: Option<syn::Ident>,
}
struct LineageField {
name: syn::Ident,
from: Option<syn::Ident>,
}
struct UpstreamBlock {
node: Option<syn::Path>,
key: Option<syn::Path>,
at: syn::Path,
}
struct SubscribeBlock {
entries: Vec<SubscribeEntry>,
}
struct SubscribeEntry {
node: Option<syn::Path>,
key: Option<syn::Path>,
out: Option<syn::Ident>,
channel: Option<ChannelOptions>,
changes: Option<ChangesFeed>,
notify: Option<syn::Path>,
at: syn::Path,
}
struct EmitsWord {
products: Vec<syn::Path>,
at: syn::Path,
}
#[derive(Default)]
struct PersistBlock {
databases: Vec<DatabaseBlock>,
table: Option<syn::LitStr>,
rename: Option<syn::Ident>,
}
struct DatabaseBlock {
kind: DatabaseKind,
uniques: Vec<CompositeUniqueWord>,
rename: Option<syn::Ident>,
comparison: Option<syn::Ident>,
table: Option<syn::LitStr>,
schema: Option<syn::LitStr>,
from: ConversionSpec,
into: ConversionSpec,
aliases: AliasOptions,
}
struct CompositeUniqueWord {
entries: Vec<syn::Ident>,
at: syn::Path,
}
#[derive(Default)]
pub(crate) struct ConversionSpec {
infallible: Option<Named>,
fallible: Option<Named>,
cell: Option<syn::Path>,
}
struct Named {
path: syn::Path,
escape: Option<syn::Path>,
at: syn::Path,
}
#[derive(Clone, Copy)]
pub(crate) struct Direction {
plain: &'static str,
fallible: &'static str,
what: &'static str,
}
pub(crate) const BUILDS: Direction = Direction {
plain: "from",
fallible: "try_from",
what: "a write",
};
const LEAVES: Direction = Direction {
plain: "into",
fallible: "try_into",
what: "a read",
};
impl Named {
fn declared(&self) -> FallibleConversion {
FallibleConversion {
path: self.path.clone(),
escape: self.escape.clone(),
}
}
}
impl ConversionSpec {
pub(crate) const fn written(&self) -> bool {
self.infallible.is_some() || self.fallible.is_some()
}
fn set(
&mut self,
fallible: bool,
named: Named,
scope: &str,
direction: Direction,
errors: &mut Errors,
) {
let (slot, name) = if fallible {
(&mut self.fallible, direction.fallible)
} else {
(&mut self.infallible, direction.plain)
};
let at = named.at.clone();
set_once(
slot,
named,
&at,
&format!("`{name}` is declared more than once in {scope} — one option, one value"),
errors,
);
}
pub(crate) fn resolve(
&self,
subject: &str,
direction: Direction,
errors: &mut Errors,
) -> Conversion {
match (&self.infallible, &self.fallible) {
(Some(_), Some(fallible)) => {
errors.push(syn::Error::new_spanned(
&fallible.at,
format!(
"`{plain}` and `{try}` are both declared for {subject} — {what} either can fail or it \
cannot, and there is no third answer. Keep `{try}` if it can, `{plain}` if it cannot.",
plain = direction.plain,
try = direction.fallible,
what = direction.what,
),
));
Conversion::Fallible(fallible.declared())
}
(None, Some(fallible)) => Conversion::Fallible(fallible.declared()),
(Some(infallible), None) => Conversion::Infallible(infallible.path.clone()),
(None, None) => Conversion::Default,
}
}
pub(crate) const fn declared(&self) -> bool {
self.infallible.is_some() || self.fallible.is_some()
}
}
const PER_DATABASE: &[&str] = &[
"unique",
"copy",
"edge",
"type",
"schema",
"collection",
"from",
"try_from",
"into",
"try_into",
];
const NULLABILITY: &[&str] = &["required", "nullable"];
const fn no_strategy_to_choose(kind: DatabaseKind) -> Option<&'static str> {
match kind {
DatabaseKind::Postgres => None,
DatabaseKind::Sqlite | DatabaseKind::Mysql => Some(
"with no array type and no JSON form an index can seek, every collection it stores is \
already an edge table",
),
DatabaseKind::Mongo => Some("a document holds its own array, and there is no second table"),
}
}
pub(crate) fn database_kind(path: &syn::Path) -> Option<DatabaseKind> {
DatabaseKind::ALL
.into_iter()
.find(|kind| path.is_ident(kind.as_str()))
}
pub(crate) fn shipped(named: impl Iterator<Item = &'static str>) -> String {
let quoted: Vec<String> = named.map(|name| format!("`{name}`")).collect();
match quoted.split_last() {
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
None => String::new(),
}
}
const DERIVED: [(&str, &str); 1] = [(
"progress",
"A ledger's control tables live in the ROW engine's own pool, so its hosts are the databases the \
store words name, and what it certifies is the unit's close — which every stored record has, so \
there is nothing to opt into. A block could only restate that or contradict it.",
)];
fn misplaced(
inner: &syn::meta::ParseNestedMeta<'_>,
takes: &str,
vocabulary: &[&str],
) -> syn::Error {
if let Some(name) = NULLABILITY.iter().find(|name| inner.path.is_ident(name)) {
let error = syn::Error::new_spanned(
inner.path.to_token_stream(),
format!(
"`{name}` is not an option — a column's nullability follows the `optional` MARKER on the \
field and is not overridable: `#[ingraph(optional)]` is nullable and a field without it is \
`NOT NULL`. A domain/column disagreement fails loudly in both directions already, so an \
override would only hide the schema bug it reconciles."
),
);
attribute::skip_entry(inner);
return error;
}
if let Some(name) = PER_DATABASE.iter().find(|name| inner.path.is_ident(name)) {
let error = syn::Error::new_spanned(
inner.path.to_token_stream(),
format!(
"`{name}` is a PER-DATABASE option and this seat speaks to every database at once — \
write it inside the database's own block, as in `#[ingraph(postgres({name}))]`. A word is \
dialect-free only when every database has it."
),
);
attribute::skip_entry(inner);
return error;
}
attribute::unknown(inner, takes, vocabulary)
}
fn subscribe_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
entry: &mut SubscribeEntry,
errors: &mut Errors,
) -> syn::Result<()> {
if inner.path.is_ident("node") {
match value::parse_literal::<syn::Path>(
inner,
"`node = \"…\"` names the upstream node, as a type path in a string literal",
) {
Ok(path) => set_once(
&mut entry.node,
path,
&inner.path,
"`node` is declared more than once in `upstream(…)` — one entry names one upstream",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("key") {
if attribute::has_value(inner) || attribute::has_block(inner) {
errors.push(named(
inner,
"`key` is written bare — it says this upstream is JOINED by key, and the entry it sits on \
is the upstream being joined, so there is nothing beside it left to name"
.to_owned(),
));
return Ok(());
}
set_once(
&mut entry.key,
inner.path.clone(),
&inner.path,
"`key` is written twice in one `upstream(…)` — one entry joins the group once",
errors,
);
return Ok(());
}
if inner.path.is_ident("out") {
match value::parse_literal::<syn::Ident>(inner, OUT_IS_QUOTED) {
Ok(variant) => set_once(
&mut entry.out,
variant,
&inner.path,
"`out` is declared more than once in `upstream(…)` — one edge carries one product",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("channel") {
match channel_word(inner) {
Ok(spec) => set_once(
&mut entry.channel,
spec,
&inner.path,
"`channel` is declared more than once in one `upstream(…)` — one edge is opened one way",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("notify") {
if attribute::has_value(inner) || attribute::has_block(inner) {
errors.push(named(
inner,
"`notify` is written bare — it says this edge carries the landed entity's KEY instead of \
the entity, and the key's TYPE is the upstream's own answer rather than a word this \
declaration could name. What the payload is is the upstream's to say; what arrives is this \
entry's to choose"
.to_owned(),
));
return Ok(());
}
set_once(
&mut entry.notify,
inner.path.clone(),
&inner.path,
"`notify` is written twice in one `upstream(…)` — one edge carries one receipt",
errors,
);
return Ok(());
}
if inner.path.is_ident("changes") {
match changes_word(inner) {
Ok(feed) => set_once(
&mut entry.changes,
feed,
&inner.path,
"`changes` is declared more than once in one `upstream(…)` — one edge is fed one way, and two \
databases' feeds are two upstreams",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
inner,
"unknown entry in `upstream(…)` — inside `subscribe(…)` it takes `node = \"…\"`, the bare words \
`key` and `notify`, `out = \"<Variant>\"`, `channel = bounded(…) | unbounded` and \
`changes(<db>)` where the edge takes the store's own feed",
&["node", "key", "notify", "out", "channel", "changes"],
));
Ok(())
}
const CHANGES_NAMES_ITS_DATABASE: &str = "`changes(<db>)` names WHICH store's feed this edge takes \
— `changes(sqlite)`, `changes(postgres)`. Bare `changes` \
would have to read the upstream's own store words to \
know, and two declarations cannot see each other, so the \
database is named here or nowhere";
const CHANGES_TAKES_EXTERNAL: &str = "the only word inside a `changes(<db>(…))` block is `external`, \
which says the hand that fills the watched store is OUTSIDE \
this process. Everything else a feed needs is the backend's, \
and everything else this edge needs is beside the block";
fn changes_word(inner: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<ChangesFeed> {
if !attribute::has_block(inner) {
return Err(syn::Error::new_spanned(
inner.path.to_token_stream(),
CHANGES_NAMES_ITS_DATABASE,
));
}
let mut feed: Option<ChangesFeed> = None;
let mut refusal: Option<syn::Error> = None;
inner.parse_nested_meta(|database| {
let Some(kind) = database_kind(&database.path) else {
let sentence = if database.path.is_ident("external") {
"`external` is a per-database word, so it lives INSIDE the database's own block — \
`changes(sqlite(external))`. Written where the database belongs it would be a store called \
`external`, and the feed is a backend's before it is anybody's hand"
.to_owned()
} else {
CHANGES_NAMES_ITS_DATABASE.to_owned()
};
refusal.get_or_insert_with(|| {
syn::Error::new_spanned(database.path.to_token_stream(), sentence)
});
attribute::skip_entry(&database);
return Ok(());
};
if feed.is_some() {
refusal.get_or_insert_with(|| {
syn::Error::new_spanned(
database.path.to_token_stream(),
"`changes(…)` names ONE database — one edge is one store's feed, and a node watching two \
stores draws two edges",
)
});
attribute::skip_entry(&database);
return Ok(());
}
let mut external = false;
if attribute::has_block(&database) {
database.parse_nested_meta(|word| {
if word.path.is_ident("external") {
external = true;
return Ok(());
}
refusal.get_or_insert_with(|| {
syn::Error::new_spanned(word.path.to_token_stream(), CHANGES_TAKES_EXTERNAL)
});
attribute::skip_entry(&word);
Ok(())
})?;
} else if attribute::has_value(&database) {
refusal.get_or_insert_with(|| {
syn::Error::new_spanned(database.path.to_token_stream(), CHANGES_TAKES_EXTERNAL)
});
attribute::skip_entry(&database);
return Ok(());
}
feed = Some(ChangesFeed {
database: kind,
external,
});
Ok(())
})?;
if let Some(refusal) = refusal {
return Err(refusal);
}
feed.ok_or_else(|| {
syn::Error::new_spanned(inner.path.to_token_stream(), CHANGES_NAMES_ITS_DATABASE)
})
}
const CHANNEL_IS_ONE_OF_TWO: &str = "`channel = bounded(512)` and `channel = unbounded` are the two \
shapes an edge has — a depth its sender blocks at, or no bound \
at all. The words are written bare, being the framework's own \
vocabulary rather than a name this declaration refers to";
const BOUNDED_NAMES_ITS_DEPTH: &str = "`bounded` is a depth — write `bounded(512)`. A bound with no \
number is the one thing the word cannot mean, and the kind \
that needs no number is `unbounded`";
const UNBOUNDED_TAKES_NOTHING: &str = "`unbounded` takes nothing — a queue nothing bounds has no \
depth to name. A number belongs to `bounded(…)`";
fn channel_word(inner: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<ChannelOptions> {
let value = inner
.value()
.map_err(|e| syn::Error::new(e.span(), CHANNEL_IS_ONE_OF_TWO))?;
let written = value
.parse::<syn::Expr>()
.map_err(|e| syn::Error::new(e.span(), CHANNEL_IS_ONE_OF_TWO))?;
match &written {
syn::Expr::Path(spelled) if spelled.path.is_ident("unbounded") => Ok(ChannelOptions::Unbounded),
syn::Expr::Path(spelled) if spelled.path.is_ident("bounded") => {
Err(syn::Error::new_spanned(&written, BOUNDED_NAMES_ITS_DEPTH))
}
syn::Expr::Call(call) => match (&*call.func, call.args.len()) {
(syn::Expr::Path(spelled), 1) if spelled.path.is_ident("bounded") => {
match call.args.first().expect("a call of one argument has one") {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(depth),
..
}) => depth.base10_parse::<usize>().map(ChannelOptions::Bounded),
other => Err(syn::Error::new_spanned(other, BOUNDED_NAMES_ITS_DEPTH)),
}
}
(syn::Expr::Path(spelled), _) if spelled.path.is_ident("bounded") => {
Err(syn::Error::new_spanned(&written, BOUNDED_NAMES_ITS_DEPTH))
}
(syn::Expr::Path(spelled), _) if spelled.path.is_ident("unbounded") => {
Err(syn::Error::new_spanned(&written, UNBOUNDED_TAKES_NOTHING))
}
_ => Err(syn::Error::new_spanned(&written, CHANNEL_IS_ONE_OF_TWO)),
},
other => Err(syn::Error::new_spanned(other, CHANNEL_IS_ONE_OF_TWO)),
}
}
const OUT_IS_QUOTED: &str = "`out = \"<Variant>\"` names one arm of the upstream's product \
vocabulary, QUOTED — a bare `out = <Variant>` is the older spelling. \
The arm is a name the upstream minted and this declaration refers to, \
and a reference is written in a string literal here as `node = \"…\"` \
is";
fn fan_in(
record: &syn::Ident,
block: Option<SubscribeBlock>,
errors: &mut Errors,
) -> Option<Subscription> {
let block = block?;
let block_has_a_group = block.entries.iter().any(|entry| entry.key.is_some());
let mut upstreams: Vec<Upstream> = Vec::new();
for entry in block.entries {
let Some(node) = entry.node else {
errors.push(syn::Error::new_spanned(
&entry.at,
"`upstream(…)` needs `node = \"path::To::Upstream\"` — an entry with no upstream names \
nothing, and the words beside it would qualify nothing",
));
continue;
};
let variant = entry.out.clone().unwrap_or_else(|| {
node
.segments
.last()
.expect("a path has at least one segment")
.ident
.clone()
});
if entry.key.is_none() && variant == PAIRED && block_has_a_group {
errors.push(syn::Error::new_spanned(
&entry.at,
format!(
"`{record}` draws from `{PAIRED}` beside a keyed group, and `{PAIRED}` is the variant \
that group takes in this node's fan-in — one word cannot name both. A `name = \"…\"` \
word will settle it; until it exists, the two cannot meet in one container"
),
));
continue;
}
if let Some(first) = upstreams
.iter()
.find(|earlier: &&Upstream| earlier.variant == variant)
{
errors.push(syn::Error::new_spanned(
&entry.at,
format!(
"`{record}` draws two edges that would take the same name — `{}` and `{}` both come out \
as `{variant}`, and that word is the variant this node's fan-in reads them under. It is \
read off the declaration rather than declared, so two edges cannot share it: a `name = \
\"…\"` word will settle a genuine collision, and until it exists the edge that needs it \
has no spelling",
upstream_text(first),
upstream_text(&Upstream {
node: node.clone(),
keyed: entry.key.is_some(),
out: entry.out.clone(),
variant: variant.clone(),
channel: entry.channel,
changes: entry.changes,
notify: entry.notify.is_some(),
}),
),
));
continue;
}
if let Some(first) = upstreams
.iter()
.find(|earlier: &&Upstream| shelf_name(&earlier.variant) == shelf_name(&variant))
{
errors.push(syn::Error::new_spanned(
&entry.at,
format!(
"`{record}` draws two edges whose CHANNEL SHELF names would collide — `{}` and `{}` both \
come out as `{}` in this node's `[node.channels]` block, which is one field written \
twice. The names are read off the declaration rather than declared, so a `name = \"…\"` \
word will settle a genuine collision, and until it exists the edge that needs it has no \
spelling",
first.variant,
variant,
shelf_name(&variant),
),
));
continue;
}
upstreams.push(Upstream {
node,
keyed: entry.key.is_some(),
out: entry.out,
variant,
channel: entry.channel,
changes: entry.changes,
notify: entry.notify.is_some(),
});
}
(!upstreams.is_empty()).then_some(Subscription { upstreams })
}
fn upstream_text(source: &Upstream) -> String {
match &source.out {
Some(out) => format!("{}'s `{out}`", path_text(&source.node)),
None => path_text(&source.node),
}
}
struct PollBlock {
name: Option<syn::Ident>,
every: Option<(syn::LitStr, std::time::Duration)>,
cron: Option<syn::LitStr>,
zone: Option<syn::LitStr>,
write: Option<Vec<syn::Path>>,
handler: Option<syn::Path>,
light: Option<syn::Path>,
body_spoken: bool,
mode: Option<(PollMode, syn::Path)>,
concurrent: Option<syn::Path>,
spoken: bool,
at: syn::Path,
}
const POLL_TAKES_A_NAME: &str = "`poll(<name>, every = \"10m\")` opens with the NAME this entry is \
minting — the word a tick arrives under, and the variant it takes \
in this node's emitted `…Due`. A clock nobody can name is a clock \
whose ticks a body cannot tell apart";
const EVERY_IS_A_DURATION: &str = "`every = \"…\"` is an INTERVAL, in the framework's one duration \
grammar — `\"10m\"`, `\"1h 30m\"`, `\"PT1H\"`, `\"1d\"`";
const CRON_IS_AN_EXPRESSION: &str = "`cron = \"…\"` is a calendar expression in the classic five \
fields — `\"0 3 * * *\"`";
fn poll_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
block: &mut PollBlock,
errors: &mut Errors,
) -> syn::Result<()> {
if inner.path.is_ident("every") {
match value::literal(inner, EVERY_IS_A_DURATION) {
Ok(text) => match interval(&text) {
Ok(interval) => set_once(
&mut block.every,
(text, interval),
&inner.path,
"`every` is declared more than once in one `poll(…)` — one entry runs on one clock",
errors,
),
Err(refusal) => errors.push(refusal),
},
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("cron") {
match value::literal(inner, CRON_IS_AN_EXPRESSION) {
Ok(text) => set_once(
&mut block.cron,
text,
&inner.path,
"`cron` is declared more than once in one `poll(…)` — one entry runs on one clock",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("tz") {
match value::literal(
inner,
"`tz = \"…\"` names the zone a calendar expression is read in, as an IANA name — \
`\"America/New_York\"`",
) {
Ok(text) => set_once(
&mut block.zone,
text,
&inner.path,
"`tz` is declared more than once in one `poll(…)` — one entry keeps one clock's time",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("write") {
let at = inner.path.clone();
if attribute::has_block(inner) {
errors.push(named(inner, WRITE_IS_QUOTED.to_owned()));
return Ok(());
}
let literals = match value::literals(inner, WRITE_IS_QUOTED) {
Ok(literals) => literals,
Err(e) => {
errors.push(e);
return Ok(());
}
};
let mut declared: Vec<syn::Path> = Vec::new();
for literal in literals {
match literal.parse::<syn::Path>() {
Ok(node) => declared.push(node),
Err(_) => errors.push(syn::Error::new_spanned(
&literal,
"`write` names NODES, so each value is a type path — an expression or an empty string \
is not one",
)),
}
}
if declared.is_empty() {
errors.push(syn::Error::new_spanned(
&at,
"`write` grants at least one store — a clock that writes into nobody else's store is \
spelled by omitting the word",
));
return Ok(());
}
set_once(
&mut block.write,
declared,
&at,
"`write` is declared more than once in one `poll(…)` — one word names every store this clock \
may write, and a second list would be a second answer to the same question. Put the extra \
stores in the one list",
errors,
);
return Ok(());
}
if inner.path.is_ident("handler") {
let at = inner.path.clone();
block.body_spoken = true;
if attribute::has_block(inner) {
errors.push(named(inner, HANDLER_IS_QUOTED.to_owned()));
return Ok(());
}
match value::parse_literal::<syn::Path>(inner, HANDLER_IS_QUOTED) {
Ok(mounted) => set_once(
&mut block.handler,
mounted,
&at,
"`handler` is declared more than once in one `poll(…)` — one clock runs ONE body, and a \
second mount would be a second answer to the same question. Two bodies are two entries",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("light") {
block.body_spoken = true;
if attribute::has_block(inner) || attribute::has_value(inner) {
errors.push(named(inner, LIGHT_IS_BARE.to_owned()));
return Ok(());
}
set_once(
&mut block.light,
inner.path.clone(),
&inner.path,
"`light` is declared more than once in one `poll(…)` — the word is presence, so a second one \
says what the first already said",
errors,
);
return Ok(());
}
if let Some(mode) = bare_mode(&inner.path) {
block.spoken = true;
if attribute::has_block(inner) || attribute::has_value(inner) {
errors.push(named(inner, mode_carries_nothing(mode)));
return Ok(());
}
set_once(
&mut block.mode,
(mode, inner.path.clone()),
&inner.path,
ONE_WORLD,
errors,
);
return Ok(());
}
if inner.path.is_ident("async") {
let at = inner.path.clone();
block.spoken = true;
if !attribute::has_block(inner) || attribute::empty_group(inner) {
errors.push(named(inner, ASYNC_NAMES_ITS_ROAD.to_owned()));
return Ok(());
}
let mut named_road: Option<PollMode> = None;
let walked = inner.parse_nested_meta(|road| {
let picked = if road.path.is_ident("inline") {
PollMode::AsyncInline
} else if road.path.is_ident("spawn") {
PollMode::AsyncSpawn
} else {
errors.push(attribute::unknown(
&road,
ASYNC_NAMES_ITS_ROAD,
&["inline", "spawn"],
));
return Ok(());
};
set_once(
&mut named_road,
picked,
&road.path,
"`async(…)` names ONE road — `inline` awaits the tick in the driver's loop and `spawn` \
detaches it as a task, and an entry cannot do both",
errors,
);
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
if let Some(road) = named_road {
set_once(&mut block.mode, (road, at.clone()), &at, ONE_WORLD, errors);
}
return Ok(());
}
if inner.path.is_ident("concurrent") {
if attribute::has_block(inner) || attribute::has_value(inner) {
errors.push(named(inner, CONCURRENT_IS_BARE.to_owned()));
return Ok(());
}
set_once(
&mut block.concurrent,
inner.path.clone(),
&inner.path,
"`concurrent` is declared more than once in one `poll(…)` — the word is presence, so a \
second one says what the first already said",
errors,
);
return Ok(());
}
if inner.path.is_ident("channel") {
errors.push(named(
inner,
"a poll entry has NO channel: a tick is a wake and not a message, so there is no queue \
between two parties to bound or leave unbounded. The word belongs to a `upstream(…)` entry \
inside `subscribe(…)`, which is where messages travel — and a clock's own coalescing is the \
runtime's, one cell per upstream, never a depth a declaration names"
.to_owned(),
));
return Ok(());
}
if inner.path.is_ident("notify") {
errors.push(named(
inner,
"a poll entry has NO receipt to choose: a tick is a wake and not a message, so nothing arrives \
whose payload could be an entity or that entity's key. The word belongs to a `upstream(…)` \
entry inside `subscribe(…)`, which is where messages travel — a polled node reads through \
its held handles instead, and what it reads is its own"
.to_owned(),
));
return Ok(());
}
if inner.path.is_ident("ack") {
errors.push(named(
inner,
"a poll inbound carries NO ack, structurally — a tick is a wake and not data, so there is no \
producer window to release and no cursor to advance. What an ack buys elsewhere this side \
already has: the NEXT TICK over an idempotent scan is the retry, the lifecycle taps are the \
observation, and the clock itself is the throttle. A unit that PUBLISHES downstream keeps \
the whole ack protocol as a sender — acklessness is a property of this edge, not of the node"
.to_owned(),
));
return Ok(());
}
if !attribute::has_value(inner) && !attribute::has_block(inner) {
let Some(name) = inner.path.get_ident().cloned() else {
errors.push(attribute::unknown(
inner,
"a poll entry MINTS one name, so the word is a plain identifier — a path with several \
segments refers to something instead, and this word refers to nothing",
&[],
));
return Ok(());
};
if block.name.is_some() {
let near = suggest::word(&inner.path)
.map(|written| suggest::did_you_mean(&written, BARE_POLL_WORDS))
.unwrap_or_default();
errors.push(named(
inner,
format!(
"a `poll(…)` entry mints ONE name — a second bare word would be a second clock, which is \
a second entry{near}"
),
));
return Ok(());
}
block.name = Some(name);
return Ok(());
}
errors.push(attribute::unknown(
inner,
"unknown entry in `poll(…)` — it opens with the bare name it mints, carries exactly one of \
`every = \"…\"` or `cron = \"…\"`, names its body with `handler = \"…\"` or `light`, and says \
WHERE it runs with one of `block`, `spawn`, `rayon`, `async(inline)` or `async(spawn)`. \
Beside those: `tz = \"…\"` on a calendar one, `write = \"…\"` where this clock's ticks are \
granted a store, and `concurrent` where a sync-detached clock may overlap itself",
&["every", "cron", "tz", "write", "handler", "light", "async"],
));
Ok(())
}
pub(crate) const BARE_POLL_WORDS: [&str; 5] = ["light", "block", "spawn", "rayon", "concurrent"];
fn bare_mode(path: &syn::Path) -> Option<PollMode> {
if path.is_ident("block") {
Some(PollMode::Block)
} else if path.is_ident("spawn") {
Some(PollMode::Spawn)
} else if path.is_ident("rayon") {
Some(PollMode::Rayon)
} else {
None
}
}
fn mode_carries_nothing(mode: PollMode) -> String {
format!(
"`{}` is a BARE word — it says where this clock's tick runs and carries nothing. The word with \
options is `async(…)`, and its options are the two async roads",
mode.as_str()
)
}
const ONE_WORLD: &str = "a `poll(…)` entry runs in ONE world — `block`, `spawn`, `rayon`, \
`async(inline)` and `async(spawn)` are five answers to the same question, \
and nothing decides between two of them. A clock that wants both is two \
clocks";
const ASYNC_NAMES_ITS_ROAD: &str = "`async(…)` names WHICH async road — `async(inline)` awaits the \
tick in the driver's own loop, and `async(spawn)` detaches it \
as a task on the executor the deployment installed. The word \
alone says the world and not the place, and the place is the \
half that changes what runs where";
const HANDLER_IS_QUOTED: &str = "`handler = \"app::PromScraper\"` mounts the CITIZEN this clock's \
ticks run — quoted, as `write = \"…\"` and `node = \"…\"` are, \
because the word names a TYPE this declaration cannot resolve and \
the compiler resolves where the expansion lands";
const LIGHT_IS_BARE: &str = "`light` is a BARE word — its presence is the whole answer. Writing it \
says this clock's ticks run the node's OWN sweep method, on the \
operator the driver lends for the call. The word that carries a value \
is `handler = \"…\"`, which mounts a citizen instead";
const CONCURRENT_IS_BARE: &str = "`concurrent` is a BARE word — its presence is the whole answer. \
Writing it says this clock's detached ticks may overlap; leaving \
it out is at most one in flight, which is the default a thread \
per tick has to have";
fn interval(text: &syn::LitStr) -> Result<std::time::Duration, syn::Error> {
let written = text.value();
let span = ingraph_codegen::duration::parse(&written).map_err(|refusal| {
syn::Error::new_spanned(
text,
format!("`every = \"{written}\"` is not a duration this grammar reads — {refusal}"),
)
})?;
if !span.is_positive() {
return Err(syn::Error::new_spanned(
text,
format!(
"`every = \"{written}\"` is not a schedule — a poll that fires as fast as the machine \
allows is a SPIN, and an interval that is not positive is one. A node that wants to look \
as often as it can is written with the shortest interval it actually means"
),
));
}
let seconds = u64::try_from(span.as_secs()).map_err(|_| {
syn::Error::new_spanned(text, format!("`every = \"{written}\"` is not a schedule"))
})?;
let nanoseconds = u32::try_from(span.subsec_nanos()).map_err(|_| {
syn::Error::new_spanned(text, format!("`every = \"{written}\"` is not a schedule"))
})?;
Ok(std::time::Duration::new(seconds, nanoseconds))
}
fn poll_sources(record: &syn::Ident, blocks: Vec<PollBlock>, errors: &mut Errors) -> Option<Polls> {
use heck::ToUpperCamelCase as _;
let mut entries: Vec<PollEntry> = Vec::new();
for block in blocks {
let Some(name) = block.name else {
let taken = if block.light.is_some() {
" — and `light` is this position's own word for the node's own body, so an entry cannot \
also mint a clock called that"
} else {
""
};
errors.push(syn::Error::new_spanned(
&block.at,
format!("{POLL_TAKES_A_NAME}{taken}"),
));
continue;
};
let cadence = match (block.every, block.cron) {
(Some(_), Some(cron)) => {
errors.push(syn::Error::new_spanned(
&cron,
format!(
"`{name}` names both `every` and `cron`, and an entry runs on ONE clock — an interval \
and a calendar are two answers to when, and nothing decides between them. Two clocks \
are two entries"
),
));
continue;
}
(None, None) => {
errors.push(syn::Error::new_spanned(
&block.at,
format!(
"`{name}` says nothing about when it is due — a poll entry carries exactly one of \
`every = \"10m\"` or `cron = \"0 3 * * *\"`. A clock with no cadence never fires, \
which is spelled by writing no entry"
),
));
continue;
}
(Some((text, interval)), None) => {
if let Some(zone) = &block.zone {
errors.push(syn::Error::new_spanned(
zone,
format!(
"`{name}` runs on an interval, and `tz` has nothing to qualify there — an interval \
counts elapsed time from its last tick and never asks what o'clock it is. The word \
belongs beside `cron = \"…\"`, which is wall-clock and therefore has a zone"
),
));
}
let _ = text;
PollCadence::Every(interval)
}
(None, Some(text)) => {
let expression = text.value();
let zone = block.zone.as_ref().map(syn::LitStr::value);
if let Err(refusal) = ingraph_codegen::cron::check(&expression, zone.as_deref()) {
errors.push(syn::Error::new_spanned(
&text,
format!("`cron = \"{expression}\"` is not a schedule this grammar reads — {refusal}"),
));
continue;
}
PollCadence::Calendar { expression, zone }
}
};
let variant = format_ident!("{}", name.to_string().to_upper_camel_case());
if let Some(first) = entries.iter().find(|entry| entry.variant == variant) {
errors.push(syn::Error::new_spanned(
&name,
format!(
"`{record}` mints two poll entries that would take the same word — `{}` and `{name}` \
both come out as `{variant}`, and that word is the variant a tick from either arrives \
under. It is read off the name rather than declared, so two entries cannot share it",
first.name,
),
));
continue;
}
let Some((mode, at)) = block.mode else {
if block.spoken {
continue;
}
errors.push(syn::Error::new_spanned(
&block.at,
format!(
"`{name}` does not say WHERE it runs — a poll entry carries exactly one of {}. There is \
no default, because a role is DECLARED rather than inferred: what a tick costs the \
driver is the difference between a body it awaits, a body it blocks on, and a body it \
hands to an executor, and none of the three is the obvious one. Today's behaviour is \
`async(inline)`",
offered()
),
));
continue;
};
match (&block.handler, &block.light) {
(None, None) => {
if !block.body_spoken {
errors.push(syn::Error::new_spanned(
&block.at,
body_is_named(&name, record),
));
}
continue;
}
(Some(_), Some(word)) => {
errors.push(syn::Error::new_spanned(
word,
format!(
"`{name}` names both `handler = \"…\"` and `light`, and one clock runs ONE body — a \
mounted citizen and this node's own sweep method are two answers to who runs the \
tick, and nothing decides between them. Two bodies are two entries"
),
));
continue;
}
(None, Some(_)) if mode.detached() => {
errors.push(syn::Error::new_spanned(
&at,
format!(
"`{name}` is `light` and runs `{}`, which DETACHES the tick — and a light body is not \
a thing that can be detached. It is a `{record}Sweeps` method on the node's own \
value, which the driver lends for the call and takes back: a borrow cannot be handed \
to another thread, and a copy of it would mutate state nothing reads. Mount a citizen \
with `handler = \"…\"` — the deployment builds that value, so a clone of it per tick \
is a thing that can be reasoned about — or run this clock in place with `block` or \
`async(inline)`",
mode.as_str()
),
));
continue;
}
(Some(_), None) | (None, Some(_)) => {}
}
let body = match block.handler {
Some(mounted) => PollBody::Citizen(mounted),
None => PollBody::Light,
};
let concurrent = match (block.concurrent, mode) {
(None, _) => false,
(Some(_), mode) if mode.lapses() => true,
(Some(word), PollMode::AsyncSpawn) => {
errors.push(syn::Error::new_spanned(
&word,
format!(
"`{name}` runs `async(spawn)`, which is ALREADY concurrent — every tick fires, the \
tasks are cheap and the runtime multiplexes them, so there is no at-most-one default \
here for the word to lift. `concurrent` belongs to `spawn` and `rayon`, where a tick \
costs a thread and the pile-up is the failure mode a default has to stand against"
),
));
continue;
}
(Some(word), mode) => {
errors.push(syn::Error::new_spanned(
&word,
format!(
"`{name}` runs `{}`, which is INLINE — the driver awaits or blocks on the tick before \
it takes the next one, so two of this clock's ticks cannot be in flight at once and \
there is nothing for the word to allow. `concurrent` belongs to `spawn` and `rayon`, \
the modes that detach",
mode.as_str()
),
));
continue;
}
};
let grants = block
.write
.and_then(|granted| entry_grants(record, &name, granted, errors));
entries.push(PollEntry {
name,
variant,
cadence,
grants,
body,
mode,
concurrent,
});
}
(!entries.is_empty()).then_some(Polls { entries })
}
fn body_is_named(name: &syn::Ident, record: &syn::Ident) -> String {
format!(
"`{name}` does not say WHO runs it — a poll entry names its body with exactly one of `handler \
= \"…\"`, which mounts a citizen the deployment built, or `light`, which runs this node's own \
`{record}Sweeps` method on the operator the driver lends. There is no default, because the \
two are different things and not two spellings of one: a citizen is a value with its own \
state, reusable across declarations and testable without a resident, and a light body is a \
method over this node's own. Today's behaviour is `light`"
)
}
fn offered() -> String {
PollMode::ALL
.iter()
.map(|mode| format!("`{}`", mode.as_str()))
.collect::<Vec<_>>()
.join(", ")
}
const EMITS_IS_QUOTED: &str = "`emits = \"…\"` names this node's ONE product and `emits = [\"…\", \
\"…\"]` names several — quoted, and the container `emits(A, B)` is \
the older spelling. The word names MESSAGE TYPES, and a type path is \
written in a string literal here as `subscribe = \"…\"` and `node = \
\"…\"` are";
fn declared_products(
record: &syn::Ident,
word: Option<EmitsWord>,
errors: &mut Errors,
) -> Option<Products> {
let word = word?;
let mut products: Vec<Product> = Vec::new();
for ty in word.products {
let variant = ty
.segments
.last()
.expect("a path has at least one segment")
.ident
.clone();
if let Some(first) = products
.iter()
.find(|earlier: &&Product| earlier.variant == variant)
{
errors.push(syn::Error::new_spanned(
&ty,
format!(
"`{record}` declares two products whose names agree — `{}` and `{}` both end in \
`{variant}`, and that word is the variant naming this product everywhere it is spelled. \
It is read off the declaration rather than declared, so two products cannot share it: a \
`name = \"…\"` word will settle a genuine collision, and until it exists the second \
product has no spelling",
path_text(&first.ty),
path_text(&ty),
),
));
continue;
}
products.push(Product { ty, variant });
}
if products.len() > CONNECTED_CEILING {
errors.push(syn::Error::new_spanned(
&word.at,
format!(
"`{record}` declares {} products, and {CONNECTED_CEILING} is the ceiling — the connection \
state a body reads is one bit per product, so a product past the {CONNECTED_CEILING}th \
would read as wanted by nobody forever. Refused by name rather than answered wrongly",
products.len(),
),
));
}
(!products.is_empty()).then_some(Products { products })
}
const WRITE_IS_QUOTED: &str = "`write = \"…\"` grants this clock the right to write into ONE other \
node's store and `write = [\"…\", \"…\"]` grants several — quoted, \
because the word names NODES and a type path is written in a string \
literal here as `subscribe = \"…\"` and `emits = \"…\"` are";
const WRITE_SITS_IN_THE_POLL: &str = "`write` is a word INSIDE a `poll(…)` entry, not beside them — \
`poll(nightly, cron = \"0 3 * * *\", write = \"media::Media\", light, async(inline))`. A \
permission is spent BY A TICK, so it is seated at the clock whose ticks spend it: the emission \
mints one grants context per clock, and a tick reaching for a store another clock was granted \
is an unsatisfied bound at the line that reached. Two clocks that share a store write the word \
twice — explicit repetition rather than one list nobody can read a clock's reach off";
fn entry_grants(
record: &syn::Ident,
name: &syn::Ident,
granted: Vec<syn::Path>,
errors: &mut Errors,
) -> Option<Grants> {
let mut grants: Vec<Grant> = Vec::new();
for node in granted {
let segment = node
.segments
.last()
.expect("a path has at least one segment")
.ident
.clone();
let mount = shelf_name(&segment);
if let Some(first) = grants
.iter()
.find(|earlier: &&Grant| earlier.mount.safe() == mount.safe())
{
errors.push(syn::Error::new_spanned(
&node,
format!(
"`{record}`'s `{name}` clock grants two writes whose mounts agree — `{}` and `{}` both \
fold to `{mount}`, and that word is the granted node's mount name everywhere it is \
spelled, so this clock's context would hold one handle under it twice. It is read off \
the declaration rather than declared, so two grants cannot share it: name the second \
store by a path whose last segment differs, or drop the duplicate. Two DIFFERENT clocks \
granting one store is a different thing and is legal — two entries, two contexts",
path_text(&first.node),
path_text(&node),
mount = mount.safe(),
),
));
continue;
}
grants.push(Grant { node, mount });
}
(!grants.is_empty()).then_some(Grants { grants })
}
const CONNECTED_CEILING: usize = u64::BITS as usize;
fn fusion_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
node: &mut Option<syn::Path>,
key: &mut Option<syn::Path>,
kind: NodeKind,
errors: &mut Errors,
) -> syn::Result<()> {
if inner.path.is_ident("node") {
match value::parse_literal::<syn::Path>(
inner,
"`node = \"…\"` names the upstream node, as a type path in a string literal",
) {
Ok(path) => set_once(
node,
path,
&inner.path,
"`node` is declared more than once in `upstream(…)` — one entry names one upstream",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("key") {
if attribute::has_value(inner) || attribute::has_block(inner) {
errors.push(named(
inner,
"`key` is a DESIGNATION and is written bare — the entry it sits on is the upstream being \
designated, so there is nothing beside it left to name"
.to_owned(),
));
return Ok(());
}
set_once(
key,
inner.path.clone(),
&inner.path,
"`key` is written twice in one `upstream(…)` — one entry designates one upstream",
errors,
);
return Ok(());
}
errors.push(named(
inner,
format!(
"`upstream(…)` on {article} {noun} names ONE upstream of a fusion — `node = \"…\"`, and `key` \
on the one this node's identity descends from. It projects nothing: a fusing node computes \
its fields from the messages it joins, so no field of it is READ OUT OF a named upstream \
field. A node whose every field is read out of one message is a derived index, declared \
with the `fulltext`, `vector` or `blob` macro",
article = kind.article(),
noun = kind.noun(),
),
));
Ok(())
}
fn mirrored_field(
field: &syn::meta::ParseNestedMeta<'_>,
name: &syn::Ident,
errors: &mut Errors,
) -> Option<syn::Ident> {
if attribute::has_value(field) {
errors.push(named(
field,
format!(
"`{name}` names a lineage field, and the parent key's field it mirrors is written inside \
it — `{name}(source = \"…\")`. A bare `=` here would read as renaming the column, which \
is `lineage(rename = \"…\")`'s scope and not this one"
),
));
return None;
}
let mut from = None;
let walked = attribute::options(field, |option| {
if option.path.is_ident("source") {
match value::literal(
&option,
"`source = \"…\"` names ONE field of the designated parent's key, in a string literal",
) {
Ok(literal) => match value::named_field(
&literal,
"`source = \"…\"` names ONE field of the parent's key, so its value is a field name — a \
path, an expression or an empty string is not one",
) {
Ok(parsed) => set_once(
&mut from,
parsed,
&option.path,
"`source` is declared more than once — one column mirrors one field of the parent's key",
errors,
),
Err(e) => errors.push(e),
},
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
"unknown entry on a lineage field — it takes `source = \"…\"`, naming the field of the \
designated parent's key this column equals",
&["source"],
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
from
}
fn record_options(attrs: &[syn::Attribute], node: NodeKind, errors: &mut Errors) -> Options {
let mut construction: Option<Construction> = None;
let mut krate = None;
let mut key_rename = None;
let mut key_seen = None;
let mut lineage = None;
let mut lineage_seen = None;
let mut persist_block: Option<PersistBlock> = None;
let mut graphql_block: Option<GraphqlBlock> = None;
let mut derived_block: Option<DerivedBlock> = None;
let mut locate_block: Option<LocateBlock> = None;
let mut memberships: Vec<syn::Path> = Vec::new();
let mut implements_seen: Option<syn::Path> = None;
let mut subscribe: Option<syn::Path> = None;
let mut subscribe_seen: Option<syn::Path> = None;
let mut subscriptions: Option<SubscribeBlock> = None;
let mut emits_seen: Option<syn::Path> = None;
let mut products: Option<EmitsWord> = None;
let mut polls: Vec<PollBlock> = Vec::new();
let mut teardown: Option<syn::Path> = None;
let mut asynchronous: Option<syn::Path> = None;
let mut streaming: Option<syn::Path> = None;
let mut autonomous: Option<syn::Path> = None;
let mut attributed: Option<syn::Path> = None;
let mut options_type: Option<syn::Path> = None;
let mut remote: Option<syn::Path> = None;
let mut upstreams: Vec<UpstreamBlock> = Vec::new();
let mut declared_errors: Vec<BackendError> = Vec::new();
let mut tracing: Option<TracingLevel> = None;
let mut tracing_seen: Option<syn::Path> = None;
let mut receipt: 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) => set_once(
&mut krate,
path,
&meta.path,
"`crate` is declared more than once — one declaration names one crate",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("options") {
match value::parse_literal::<syn::Path>(
&meta,
"`options = \"…\"` must be a path to this node's options type, in a string literal",
) {
Ok(path) => set_once(
&mut options_type,
path,
&meta.path,
"`options` is declared more than once — one node is configured by one type",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("receipt") {
if !node.mints_a_message() {
errors.push(named(&meta, receipt_is_the_messages_word(node)));
return Ok(());
}
match value::parse_literal::<syn::Path>(
&meta,
"`receipt = \"…\"` must be a path to the type a consumer answers this message with, in a \
string literal",
) {
Ok(path) => set_once(
&mut receipt,
path,
&meta.path,
"`receipt` is declared more than once — one message is answered with one type",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("remote") {
if !node.dressable() {
errors.push(named(&meta, remote_is_a_published_rung(node)));
return Ok(());
}
match value::parse_literal::<syn::Path>(
&meta,
"`remote = \"…\"` names the type this declaration wraps, as a type path in a string literal",
) {
Ok(path) => set_once(
&mut remote,
path,
&meta.path,
"`remote` is declared more than once — one declaration wraps one type",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident(crate::construct::WORD) {
return crate::construct::container(&meta, &mut construction, errors);
}
if meta.path.is_ident("subscribe") {
set_once(
&mut subscribe_seen,
meta.path.clone(),
&meta.path,
"`subscribe` is declared more than once — one node has one fan-in. `subscribe = \"…\"` \
names the one upstream a node is driven by, and `subscribe(upstream(…), …)` names them all",
errors,
);
if attribute::has_value(&meta) {
match value::parse_literal::<syn::Path>(
&meta,
"`subscribe = \"…\"` names the upstream node, as a type path in a string literal",
) {
Ok(path) => subscribe = Some(path),
Err(e) => errors.push(e),
}
return Ok(());
}
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
errors.push(named(
&meta,
"`subscribe(…)` holds at least one `upstream(node = \"…\")` entry — a node that draws \
from nothing is spelled by omitting the word, and one upstream is \
`subscribe = \"path::To::Upstream\"`"
.to_owned(),
));
return Ok(());
}
let mut entries: Vec<SubscribeEntry> = Vec::new();
let walked = meta.parse_nested_meta(|inner| {
if inner.path.is_ident("upstream") {
let at = inner.path.clone();
let mut entry = SubscribeEntry {
node: None,
key: None,
out: None,
channel: None,
changes: None,
notify: None,
at,
};
let walked =
attribute::options(&inner, |word| subscribe_entry(&word, &mut entry, errors));
entries.push(entry);
return walked;
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `subscribe(…)` — every upstream is one `upstream(node = \"…\")` entry, \
carrying `key` where it joins the keyed group, `notify` where this consumer wants the \
landed entity's KEY rather than the entity, `out = \"<Variant>\"` where the upstream \
emits several products, and `channel = bounded(…) | unbounded` where its author ships a \
default for the edge",
&["upstream"],
));
Ok(())
});
subscriptions = Some(SubscribeBlock { entries });
return walked;
}
if meta.path.is_ident("emits") {
let at = meta.path.clone();
set_once(
&mut emits_seen,
at.clone(),
&at,
"`emits` is declared more than once — one word names every product this node has",
errors,
);
if attribute::has_block(&meta) {
errors.push(named(&meta, EMITS_IS_QUOTED.to_owned()));
return Ok(());
}
let literals = match value::literals(&meta, EMITS_IS_QUOTED) {
Ok(literals) => literals,
Err(e) => {
errors.push(e);
return Ok(());
}
};
let mut declared: Vec<syn::Path> = Vec::new();
for literal in literals {
match literal.parse::<syn::Path>() {
Ok(product) => declared.push(product),
Err(_) => errors.push(syn::Error::new_spanned(
&literal,
"`emits` names MESSAGE TYPES, so each value is a type path — an expression or an empty \
string is not one",
)),
}
}
if declared.is_empty() {
errors.push(syn::Error::new_spanned(
&at,
"`emits` names at least one product — a node whose product is the declared struct itself \
is spelled by omitting the word",
));
return Ok(());
}
products = Some(EmitsWord {
products: declared,
at,
});
return Ok(());
}
if meta.path.is_ident("write") {
errors.push(named(&meta, WRITE_SITS_IN_THE_POLL.to_owned()));
return Ok(());
}
if meta.path.is_ident("poll") {
let at = meta.path.clone();
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
errors.push(named(&meta, POLL_TAKES_A_NAME.to_owned()));
return Ok(());
}
let mut block = PollBlock {
name: None,
every: None,
cron: None,
zone: None,
write: None,
handler: None,
light: None,
body_spoken: false,
mode: None,
concurrent: None,
spoken: false,
at,
};
let walked = attribute::options(&meta, |inner| poll_entry(&inner, &mut block, errors));
polls.push(block);
return walked;
}
if meta.path.is_ident("upstream") {
let at = meta.path.clone();
let (mut upstream, mut key) = (None, None);
let walked = attribute::options(&meta, |inner| {
fusion_entry(&inner, &mut upstream, &mut key, node, errors)
});
upstreams.push(UpstreamBlock {
node: upstream,
key,
at,
});
return walked;
}
if meta.path.is_ident("teardown") {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(named(
&meta,
"`teardown` is a bare word — the goodbye itself is the `AsyncTeardown` impl on this type, so \
there is nothing here to configure"
.to_owned(),
));
return Ok(());
}
set_once(
&mut teardown,
meta.path.clone(),
&meta.path,
"`teardown` is declared more than once — one declaration says goodbye once",
errors,
);
return Ok(());
}
if meta.path.is_ident("async") {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(named(
&meta,
"`async` is a bare word HERE — it names the face this node's own `accept` wears, and the \
body itself is the `AsyncOperator` impl on this type, so there is nothing to configure. \
(The `async(inline)` / `async(spawn)` pair inside `poll(…)` is a different word on a \
different axis: it says WHERE a tick runs, not what a unit answers.)"
.to_owned(),
));
return Ok(());
}
set_once(
&mut asynchronous,
meta.path.clone(),
&meta.path,
"`async` is declared more than once — one declaration wears one face",
errors,
);
return Ok(());
}
if meta.path.is_ident("stream") {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(named(
&meta,
"`stream` is a bare word — it names the PAIR this node's body wears, and the body itself \
is the `StreamOperator` (or `AsyncStreamOperator`) impl on this type, so there is \
nothing here to configure. The per-node seats a lane runs under — how many deliveries it \
holds at once, how deep each one's feed is cut — are `StreamOptions` at the launch, \
because a feed policy is a value and an attribute cannot name one"
.to_owned(),
));
return Ok(());
}
set_once(
&mut streaming,
meta.path.clone(),
&meta.path,
"`stream` is declared more than once — one declaration wears one pair",
errors,
);
return Ok(());
}
if meta.path.is_ident("autonomous") {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(named(
&meta,
"`autonomous` is a bare word — it names the KIND this node's body wears, and the body \
itself is the `AutonomousOperator` (or `AsyncAutonomousOperator`) impl on this type, so \
there is nothing here to configure. What such a node would otherwise configure — how \
many workers it keeps, how it routes among them, how deep its own queues are — is \
inside `run`, because those are the node's own and not the framework's"
.to_owned(),
));
return Ok(());
}
set_once(
&mut autonomous,
meta.path.clone(),
&meta.path,
"`autonomous` is declared more than once — one declaration wears one kind",
errors,
);
return Ok(());
}
if meta.path.is_ident("attributed") {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(named(
&meta,
"`attributed` is a bare word — the projection is the `Attributes` impl this node's OUTPUT \
carries, emitted beside that output's own declaration, so there is nothing here to name. \
An attribution that carries state — a journal writer, a queue, a handle — is a VALUE no \
attribute can name, and it is attached at the launch through `Resident::attributing`"
.to_owned(),
));
return Ok(());
}
set_once(
&mut attributed,
meta.path.clone(),
&meta.path,
"`attributed` is declared more than once — one declaration attributes its outputs once",
errors,
);
return Ok(());
}
if meta.path.is_ident("key") {
return attribute::block(
&meta,
&mut key_seen,
"`key(…)` is declared more than once — one block per emitted type",
errors,
|inner, errors| {
if inner.path.is_ident("rename") {
match rename(&inner) {
Ok(name) => set_once(
&mut key_rename,
name,
&inner.path,
"`rename` is declared more than once in `key(…)` — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `key(…)` — it takes `rename = \"…\"`",
&["rename"],
));
Ok(())
},
);
}
if meta.path.is_ident("lineage") {
let mut names: Option<Vec<LineageField>> = None;
let mut renamed = None;
let walked = attribute::block(
&meta,
&mut lineage_seen,
"`lineage(…)` is declared more than once — one block per emitted type",
errors,
|inner, errors| {
if inner.path.is_ident("fields") {
const REPEATED: &str = "`fields` is declared more than once in `lineage(…)` — one \
list carries the whole path";
if attribute::empty_group(&inner) {
errors.push(syn::Error::new_spanned(
&inner.path,
"`fields(…)` must name at least one field — a record with no path is a root, \
and a root is spelled by omitting the `lineage(…)` block",
));
attribute::skip_entry(&inner);
set_once(&mut names, Vec::new(), &inner.path, REPEATED, errors);
return Ok(());
}
let mut collected = Vec::new();
let walked = inner.parse_nested_meta(|field| {
let Some(name) = field.path.get_ident().cloned() else {
errors.push(attribute::unknown(
&field,
"`lineage(fields(…))` takes field idents",
&[],
));
return Ok(());
};
collected.push(LineageField {
from: mirrored_field(&field, &name, errors),
name,
});
Ok(())
});
set_once(&mut names, collected, &inner.path, REPEATED, errors);
return walked;
}
if inner.path.is_ident("rename") {
match rename(&inner) {
Ok(name) => set_once(
&mut renamed,
name,
&inner.path,
"`rename` is declared more than once in `lineage(…)` — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `lineage(…)` — it takes `fields(…)` and `rename = \"…\"`",
&["fields", "rename"],
));
Ok(())
},
);
match names {
Some(fields) if !fields.is_empty() => {
lineage = Some(LineageBlock {
fields,
rename: renamed,
});
}
Some(_) => {}
None => errors.push(syn::Error::new_spanned(
&meta.path,
"`lineage(…)` needs `fields(…)` — it is the path the type carries, and without it \
there is no type to emit; a root is spelled by omitting the block",
)),
}
return walked;
}
if let Some(kind) = database_kind(&meta.path) {
if !node.holds_rows() {
errors.push(named(
&meta,
format!(
"{article} {noun} stores no rows — `{db}` names a DATABASE the rows land in, and the \
MACRO is the storage declaration, so a node whose messages land in a database is a \
`record`. {law}",
article = node.article(),
noun = node.noun(),
db = kind.as_str(),
law = owns_one_storage(node),
),
));
attribute::skip_entry(&meta);
return Ok(());
}
let block = persist_block.get_or_insert_with(PersistBlock::default);
return record_database(&meta, kind, &mut block.databases, errors);
}
if meta.path.is_ident("table") || meta.path.is_ident("rename") {
if !node.holds_rows() {
errors.push(named(
&meta,
format!(
"{article} {noun} stores no rows, so it has no {subject} to name — `{word}` is a store \
word's common entry, and the store words are a `record`'s. {law}",
article = node.article(),
noun = node.noun(),
subject = if meta.path.is_ident("table") {
"table"
} else {
"row type"
},
word = if meta.path.is_ident("table") {
"table"
} else {
"rename"
},
law = owns_one_storage(node),
),
));
attribute::skip_entry(&meta);
return Ok(());
}
let block = persist_block.get_or_insert_with(PersistBlock::default);
if meta.path.is_ident("table") {
match value::literal(&meta, TABLE_VALUE) {
Ok(name) => set_once(
&mut block.table,
name,
&meta.path,
"`table` is declared more than once — one record, one common table name",
errors,
),
Err(e) => errors.push(e),
}
} else {
match rename(&meta) {
Ok(name) => set_once(
&mut block.rename,
name,
&meta.path,
"`rename` is declared more than once — one record, one row-type base",
errors,
),
Err(e) => errors.push(e),
}
}
return Ok(());
}
if meta.path.is_ident("persist") {
let sentence = if node.holds_rows() {
"`persist(…)` is gone — a record's stores are named BARE at the head, so write \
`#[ingraph::record(sqlite)]` and keep every word that was inside each database's own \
block. Storage is a record's ESSENCE and an essence does not wrap; `graphql(…)`, which is \
OPTIONAL, still does. A node that stores nothing is an `entity`."
.to_owned()
} else {
format!(
"{article} {noun} stores no rows — `persist(…)` was the ROW storage's wrapper and the \
rows are a `record`'s, so unwrapping it here would only reach the same refusal one \
compile later. {law}",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
)
};
errors.push(named(&meta, sentence));
attribute::skip_entry(&meta);
return Ok(());
}
if meta.path.is_ident("vector") {
errors.push(named(
&meta,
format!(
"{article} {noun} owns no embedding index — an index is its OWN node, so the engines this \
block names are that node's to name: declare them with the `vector` macro, on a type \
whose `upstream(…)` names this {noun}. `element` and `filter` describe the EMBEDDINGS \
rather than these rows, so they travel with the engines. {law}",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
if meta.path.is_ident("fulltext") {
errors.push(named(
&meta,
format!(
"{article} {noun} owns no full-text index — an index is its OWN node, so the engines this \
block names are that node's to name: declare them with the `fulltext` macro, on a type \
whose `upstream(…)` names this {noun}. {law}",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
if meta.path.is_ident("blob") {
errors.push(named(
&meta,
format!(
"{article} {noun} owns no artifact store — a blob family is its OWN node, so the stores \
this block names are that node's to name: declare them with the `blob` macro, on a \
type whose `upstream(…)` names this {noun}. `extension` is part of the ADDRESS that \
node's key renders, so it travels with the stores. {law} A column of BYTES is a \
different thing and stays: write `bytes` beside `persist`, and the bytes are a value in \
this {noun}'s own row.",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
for (family, why) in DERIVED {
if meta.path.is_ident(family) {
errors.push(named(
&meta,
format!(
"`{family}(…)` is not a declaration — it is derived from the storage families, so \
remove the block. {why}"
),
));
return Ok(());
}
}
if meta.path.is_ident("graphql") {
if !node.dressable() {
errors.push(named(
&meta,
format!(
"{article} {noun} publishes nothing — an operator is the node family's BASE, and the \
rowless tier that publishes its address is an `entity`. Change the macro, or drop the \
block. {law}",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
let at = meta.path.clone();
let mut backends: Vec<BackendBlock> = Vec::new();
let mut wire = [None, None, None, None];
let mut renamed = None;
let mut connection: Option<syn::LitStr> = None;
let mut edge_name: Option<syn::LitStr> = None;
let mut plural: Option<syn::LitStr> = None;
let mut key_object: Option<syn::LitStr> = None;
let mut key_argument: Option<syn::LitStr> = None;
let walked = attribute::options(&meta, |inner| {
if let Some(kind) = graphql_kind(&inner.path) {
return record_backend(&inner, kind, &mut backends, errors);
}
if inner.path.is_ident("output") {
return attribute::options(&inner, |option| {
if database_kind(&option.path).is_some() {
return error_blocks(
&option,
Crossing::Output,
"graphql(output(…))",
"try_from",
&mut declared_errors,
errors,
);
}
if option.path.is_ident("rename") {
match value::parse_literal::<syn::Ident>(&option, attribute::TYPE_NAME) {
Ok(spelled) => set_once(
&mut wire[0],
spelled,
&option.path,
"`rename` is declared more than once in `output(…)` — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
"unknown entry in `output(…)` — it takes `rename = \"…\"`, which names the object, \
and one block per database carrying `try_from(error = \"…\")`, which types the \
crossing a stored row takes onto it",
&["rename"]
.into_iter()
.chain(DatabaseKind::ALL.map(DatabaseKind::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
}
if inner.path.is_ident("input") {
return attribute::options(&inner, |position| {
if position.path.is_ident("comparison") {
return attribute::options(&position, |option| {
error_blocks(
&option,
Crossing::Comparison,
"graphql(input(comparison(…)))",
"try_into",
&mut declared_errors,
errors,
)
});
}
errors.push(attribute::unknown(
&position,
"unknown entry in `input(…)` on a record — the input half has ONE crossing that \
carries a value, and it is `comparison(…)`. An order names a column and a \
direction and a page names a cursor, so neither has an operand to convert.",
&["comparison"],
));
Ok(())
});
}
if inner.path.is_ident("key") {
return key_block(
&inner,
&mut wire[1],
&mut key_object,
&mut key_argument,
errors,
);
}
for (index, what) in ["filter", "order_by"].into_iter().enumerate() {
if inner.path.is_ident(what) {
return attribute::rename_block(&inner, &mut wire[index + 2], what, errors);
}
}
for (what, slot) in [("connection", &mut connection), ("edge", &mut edge_name)] {
if inner.path.is_ident(what) {
return attribute::sdl_name_block(&inner, slot, what, errors);
}
}
if inner.path.is_ident("name") {
errors.push(named(
&inner,
"`name` moved into `output(…)` — the wire face emits four types, so write \
`output(rename = \"…\")`; one `rename` sets both the Rust name and the schema name"
.to_owned(),
));
return Ok(());
}
if inner.path.is_ident("rename") {
match rename(&inner) {
Ok(spelled) => set_once(
&mut renamed,
spelled,
&inner.path,
"`rename` is declared more than once in `graphql(…)` — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("plural") {
match value::literal(&inner, PLURAL_WORD) {
Ok(word) => {
wire::refuse_invalid_name(&word.value(), &word, errors);
set_once(
&mut plural,
word,
&inner.path,
"`plural` is declared more than once in `graphql(…)` — one option, one value",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
if let Some(error) = queryability(&inner) {
errors.push(error);
return Ok(());
}
errors.push(wire_option(
&inner,
"unknown entry in `graphql(…)` — it takes `rename = \"…\"`, `plural = \"…\"`, a block per \
emitted type (`output`, `key`, `filter`, `order_by`), a block per SDL page name \
(`connection`, `edge`), `input(comparison(error(…)))` and one per backend \
(`async_graphql`)",
&["rename", "plural", "output", "key", "filter", "order_by", "connection", "edge", "input"]
.into_iter()
.chain(GraphqlKind::ALL.map(GraphqlKind::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
set_once(
&mut graphql_block,
GraphqlBlock {
backends,
output: wire[0].clone(),
key: wire[1].clone(),
filter: wire[2].clone(),
order_by: wire[3].clone(),
key_object,
key_argument,
connection,
edge: edge_name,
rename: renamed,
plural,
at: at.clone(),
},
&at,
"`graphql(…)` is declared more than once — one block per emitted type",
errors,
);
return walked;
}
if meta.path.is_ident("derived") {
let at = meta.path.clone();
let mut entries: Vec<DerivedEntry> = Vec::new();
let walked = attribute::options(&meta, |inner| derived_entry(&inner, &mut entries, errors));
set_once(
&mut derived_block,
DerivedBlock {
entries,
at: at.clone(),
},
&at,
"`derived(…)` is declared more than once — one block carries every reverse position",
errors,
);
return walked;
}
if meta.path.is_ident("locate") {
let at = meta.path.clone();
let mut entries: Vec<LocateEntry> = Vec::new();
let walked = attribute::options(&meta, |inner| locate_entry(&inner, &mut entries, errors));
set_once(
&mut locate_block,
LocateBlock {
entries,
at: at.clone(),
},
&at,
"`locate(…)` is declared more than once — one block carries every artifact family",
errors,
);
return walked;
}
if meta.path.is_ident("implements") {
let at = meta.path.clone();
let walked = attribute::options(&meta, |inner| membership(&inner, &mut memberships, errors));
set_once(
&mut implements_seen,
at.clone(),
&at,
"`implements(…)` is declared more than once — one block carries every interface",
errors,
);
return walked;
}
if meta.path.is_ident("tracing") {
let at = meta.path.clone();
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
errors.push(named(&meta, TRACING_TAKES_A_LEVEL.to_owned()));
return Ok(());
}
let walked = attribute::options(&meta, |inner| tracing_entry(&inner, &mut tracing, errors));
set_once(
&mut tracing_seen,
at.clone(),
&at,
"`tracing(…)` is declared more than once — one node observes itself at one level",
errors,
);
return walked;
}
for word in [
ingraph_codegen::aggregate::GROUP,
ingraph_codegen::aggregate::MEASURE,
] {
if meta.path.is_ident(word) {
errors.push(named(
&meta,
crate::aggregate::wrong_kind(word, node, crate::aggregate::Written::AtTheHead),
));
return Ok(());
}
}
errors.push(attribute::unknown(
&meta,
&format!(
"unknown `ingraph` record attribute — a record takes its STORE WORDS bare ({stores}, with \
`table = \"…\"` and `rename = \"…\"` beside them), and `key(…)`, `lineage(…)`, \
`graphql(…)`, `derived(…)`, `locate(…)`, `implements(…)`, `upstream(…)`, `subscribe`, \
`emits`, `poll(…)`, `tracing(…)`, the bare `teardown`, `async`, `stream`, \
`autonomous` and `attributed` words, `crate = \"…\"`, `options = \"…\"`, \
`receipt = \"…\"`, `remote = \"…\"` and `builder(…)`",
stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
),
&[
"table",
"rename",
"key",
"lineage",
"graphql",
"derived",
"locate",
"implements",
"upstream",
"subscribe",
"emits",
"poll",
"tracing",
"teardown",
"async",
"stream",
"autonomous",
"attributed",
"crate",
"options",
"receipt",
"remote",
crate::construct::WORD,
]
.into_iter()
.chain(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
Options {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
key_rename,
lineage,
persist: persist_block,
graphql: graphql_block,
derived: derived_block,
locate: locate_block,
implements: memberships,
subscribe,
subscribe_at: subscribe_seen,
subscriptions,
products,
polls,
teardown: teardown.is_some(),
asynchronous,
streaming,
autonomous,
attributed: attributed.is_some(),
options: options_type,
remote,
construction,
upstreams,
errors: declared_errors,
tracing,
receipt,
}
}
fn remote_is_a_published_rung(node: NodeKind) -> String {
format!(
"{article} {noun} publishes no address, and `remote = \"…\"` exists to give a FOREIGN type this \
framework's faces — a key, a filter and a wire face are what a wrapper is for. The \
declarations that take the word are `entity`, `record` and `fields`",
article = node.article(),
noun = node.noun(),
)
}
fn receipt_is_the_messages_word(node: NodeKind) -> String {
format!(
"{article} {noun} mints no MESSAGE, and `receipt = \"…\"` is a property of the thing GIVEN \
rather than of the seat that answers for it — one message, one receipt, whichever consumer is \
on the far end. Write the word on the declaration that MINTS the message this node is \
answering for: an `entity` (the message node), a `record`, or an `aggregate`. A seat that must \
answer with something its message did not declare states it through `Emitter::receipt` or \
`Ack::receipting`, which take any value and name no type",
article = node.article(),
noun = node.noun(),
)
}
const TRACING_TAKES_A_LEVEL: &str = "`tracing` is a block — write `tracing(level = debug)`. The \
word exists to carry the level a node's spans open at, and \
there is nothing else it could say";
fn tracing_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
tracing: &mut Option<TracingLevel>,
errors: &mut Errors,
) -> syn::Result<()> {
if !inner.path.is_ident("level") {
errors.push(attribute::unknown(
inner,
"unknown entry in `tracing(…)` — the block carries exactly one word, `level = …`",
&["level"],
));
return Ok(());
}
let value = inner
.value()
.map_err(|e| syn::Error::new(e.span(), LEVEL_TAKES_A_WORD))?;
let word: syn::Ident = value
.parse()
.map_err(|e| syn::Error::new(e.span(), LEVEL_TAKES_A_WORD))?;
let Some(level) = TracingLevel::named(&word.to_string()) else {
errors.push(syn::Error::new_spanned(
&word,
format!(
"`{word}` is not a level this framework names — the words are {words}. The vocabulary is \
`tracing`'s own five, so a level it cannot filter on is not a word here{near}",
words = shipped(TracingLevel::ALL.into_iter().map(TracingLevel::as_str)),
near = crate::suggest::did_you_mean(
&word.to_string(),
TracingLevel::ALL.map(TracingLevel::as_str)
),
),
));
return Ok(());
};
set_once(
tracing,
level,
&inner.path,
"`level` is declared more than once in `tracing(…)` — one option, one value",
errors,
);
Ok(())
}
const LEVEL_TAKES_A_WORD: &str = "`level` takes a BARE WORD — write `tracing(level = debug)` and \
not `tracing(level = \"debug\")`. A quoted value in this grammar \
REFERS to something declared elsewhere, and a level refers to \
nothing: it is one of five words the framework itself ships";
fn membership(
inner: &syn::meta::ParseNestedMeta<'_>,
memberships: &mut Vec<syn::Path>,
errors: &mut Errors,
) -> syn::Result<()> {
let interface = inner.path.clone();
if memberships
.iter()
.any(|already| tight(already) == tight(&interface))
{
errors.push(syn::Error::new_spanned(
interface.to_token_stream(),
format!(
"`{name}` is named more than once in `implements(…)` — a record is a member of an \
interface once, and a second word states the same fact",
name = tight(&interface)
),
));
attribute::skip_entry(inner);
return Ok(());
}
if attribute::has_value(inner) {
errors.push(attribute::unknown(inner, MEMBERSHIP_SHAPE, &[]));
return Ok(());
}
memberships.push(interface);
attribute::options(inner, |renamed| {
errors.push(attribute::unknown(&renamed, MEMBERSHIP_RENAME, &[]));
Ok(())
})
}
const MEMBERSHIP_SHAPE: &str = "`implements(…)` names INTERFACES — write the type, as in \
`implements(media::Media)`. A membership is a fact rather than a \
value, so there is nothing for it to be equal to";
const MEMBERSHIP_RENAME: &str = "a member's column answers an interface's field name where the \
INTERFACE declares it — `<field>(…, members(<Variant>(field = \
\"…\")))` in \
its `fields(…)` list. Declared there, the variant key is checked \
against the enum's own variants in one derive input; declared \
here, it would have to reach that expansion across a derive \
boundary, and only a type or a const crosses one";
fn tight(path: &syn::Path) -> String {
path.to_token_stream().to_string().replace(' ', "")
}
fn error_blocks(
inner: &syn::meta::ParseNestedMeta<'_>,
crossing: Crossing,
scope: &str,
leg_word: &'static str,
declared: &mut Vec<BackendError>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(kind) = database_kind(&inner.path) else {
errors.push(attribute::unknown(
inner,
&format!(
"unknown entry in `{scope}` — a per-database entry opens that DATABASE's block, because an \
error is what one crossing's impls at one backend answer with: {list}",
list = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
),
&DatabaseKind::ALL.map(DatabaseKind::as_str),
));
return Ok(());
};
attribute::options(inner, |option| {
if option.path.is_ident("error") {
errors.push(named(
&option,
format!(
"`error` rides its LEG now — write `{leg_word}(error = \"…\")` in `{scope}`'s `{kind}` \
block, which is the same word the FIELD's leg is written under one level down",
kind = kind.as_str()
),
));
return Ok(());
}
if option.path.is_ident(leg_word) {
let (_, cell) = leg(&option, leg_word, true, true, scope, errors);
let Some(path) = cell else {
return Ok(());
};
if declared
.iter()
.any(|error| error.crossing == crossing && error.kind == kind)
{
errors.push(syn::Error::new_spanned(
&option.path,
format!(
"`error` is declared more than once in `{scope}`'s `{kind}` block — one leg, one type",
kind = kind.as_str()
),
));
return Ok(());
}
declared.push(BackendError {
crossing,
kind,
path,
});
return Ok(());
}
errors.push(attribute::unknown(
&option,
&format!(
"unknown entry in `{scope}`'s `{kind}` block — this crossing has ONE leg and it is \
`{leg_word}(…)`, which is the word the field's own leg is written under; the cell it \
carries is `error = \"…\"`",
kind = kind.as_str()
),
&[leg_word],
));
Ok(())
})
}
fn derived_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
entries: &mut Vec<DerivedEntry>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(name) = inner.path.get_ident().cloned() else {
errors.push(attribute::unknown(inner, DERIVED_SHAPE, &[]));
return Ok(());
};
if entries.iter().any(|entry| entry.name == name) {
errors.push(syn::Error::new_spanned(
&name,
format!("`{name}` is declared more than once in `derived(…)` — one position, one name"),
));
attribute::skip_entry(inner);
return Ok(());
}
if attribute::has_value(inner) {
match value::parse_literal::<syn::Path>(inner, DERIVED_SHAPE) {
Ok(source) => entries.push(DerivedEntry {
name,
source,
field: None,
}),
Err(e) => errors.push(e),
}
return Ok(());
}
let mut source: Option<syn::Path> = None;
let mut field: Option<syn::LitStr> = None;
let walked = attribute::options(inner, |option| {
if option.path.is_ident("type") {
match value::parse_literal::<syn::Path>(&option, DERIVED_TYPE) {
Ok(path) => set_once(
&mut source,
path,
&option.path,
"`type` is declared more than once in a reverse position — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("field") {
match value::literal(&option, DERIVED_FIELD) {
Ok(named) => set_once(
&mut field,
named,
&option.path,
"`field` is declared more than once in a reverse position — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
"unknown entry in a reverse position — it takes `type = \"…\"` and `field = \"…\"`",
&["type", "field"],
));
Ok(())
});
match source {
Some(source) => entries.push(DerivedEntry {
name,
source,
field,
}),
None => errors.push(syn::Error::new_spanned(&name, DERIVED_SHAPE)),
}
walked
}
fn locate_entry(
inner: &syn::meta::ParseNestedMeta<'_>,
entries: &mut Vec<LocateEntry>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(name) = inner.path.get_ident().cloned() else {
errors.push(attribute::unknown(inner, LOCATE_MINTS_ITS_OWN_WORD, &[]));
return Ok(());
};
if entries.iter().any(|entry| entry.name == name) {
errors.push(syn::Error::new_spanned(
&name,
format!("`{name}` is declared more than once in `locate(…)` — one position, one name"),
));
attribute::skip_entry(inner);
return Ok(());
}
if !attribute::has_block(inner) {
match value::parse_literal::<syn::Path>(inner, LOCATE_SHAPE) {
Ok(family) => entries.push(LocateEntry {
name,
family,
data: None,
required: false,
}),
Err(e) => errors.push(e),
}
return Ok(());
}
let mut family: Option<syn::Path> = None;
let mut data: Option<LocateData> = None;
let mut required = false;
let walked = attribute::options(inner, |option| {
if option.path.is_ident("family") {
match value::parse_literal::<syn::Path>(&option, LOCATE_FAMILY) {
Ok(path) => set_once(
&mut family,
path,
&option.path,
"`family` is declared more than once in an artifact position — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("data") {
return locate_data(&option, &mut data, errors);
}
if option.path.is_ident(REQUIRED) {
if attribute::has_value(&option) || attribute::has_block(&option) {
errors.push(named(&option, LOCATE_REQUIRED_IS_BARE.to_owned()));
return Ok(());
}
if required {
errors.push(syn::Error::new_spanned(
&option.path,
"`required` is declared more than once in an artifact position — the word is PRESENCE, \
so the second one says exactly what the first already said",
));
}
required = true;
attribute::skip_entry(&option);
return Ok(());
}
if option.path.is_ident("type") || option.path.is_ident("field") {
errors.push(named(&option, LOCATE_SIBLINGS_WORDS.to_owned()));
return Ok(());
}
errors.push(attribute::unknown(&option, LOCATE_OPTIONS, &LOCATE_WORDS));
Ok(())
});
match family {
Some(family) => entries.push(LocateEntry {
name,
family,
data,
required,
}),
None => errors.push(syn::Error::new_spanned(&name, LOCATE_FAMILY_MISSING)),
}
walked
}
fn locate_data(
option: &syn::meta::ParseNestedMeta<'_>,
data: &mut Option<LocateData>,
errors: &mut Errors,
) -> syn::Result<()> {
let at = option.path.clone();
if attribute::has_block(option) {
let mut rename = None;
let mut required = false;
let walked = attribute::options(option, |inner| {
if inner.path.is_ident("rename") {
match value::literal(&inner, LOCATE_DATA_RENAME) {
Ok(name) => set_once(
&mut rename,
name,
&inner.path,
"`rename` is declared more than once in a `data(…)` ask — one field, one name",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident(REQUIRED) {
if attribute::has_value(&inner) || attribute::has_block(&inner) {
errors.push(named(&inner, LOCATE_REQUIRED_IS_BARE.to_owned()));
return Ok(());
}
if required {
errors.push(syn::Error::new_spanned(
&inner.path,
"`required` is declared more than once in a `data(…)` ask — the word is PRESENCE, so \
the second one says exactly what the first already said",
));
}
required = true;
attribute::skip_entry(&inner);
return Ok(());
}
errors.push(attribute::unknown(
&inner,
LOCATE_DATA_OPTIONS,
&LOCATE_DATA_WORDS,
));
Ok(())
});
set_once(
data,
LocateData {
at,
rename,
required,
},
&option.path,
"`data` is declared more than once in an artifact position — one ask, one field",
errors,
);
return walked;
}
let rename = if attribute::has_value(option) {
match value::literal(option, LOCATE_DATA_SHAPE) {
Ok(name) => Some(name),
Err(e) => {
errors.push(e);
return Ok(());
}
}
} else {
attribute::skip_entry(option);
None
};
set_once(
data,
LocateData {
at,
rename,
required: false,
},
&option.path,
"`data` is declared more than once in an artifact position — one ask, one field",
errors,
);
Ok(())
}
const DERIVED_TYPE: &str = "`type` names the record that points back at this one, as a type path \
in a string literal";
const DERIVED_FIELD: &str = "`field` names one of the source's `ref` fields, in a string literal";
pub(crate) fn owns_one_storage(kind: NodeKind) -> String {
let held = match kind {
NodeKind::Record => "its rows",
NodeKind::Aggregate => "the folded rows it keeps",
NodeKind::Operator | NodeKind::Entity => "none at all",
NodeKind::Fulltext | NodeKind::Vector | NodeKind::Blob => "the one its own macro names",
};
let article = kind.article();
let noun = kind.noun();
let elsewhere = if kind.derives_its_key() {
"A second storage over the same messages is a second node, subscribing to the same upstream."
.to_owned()
} else {
format!(
"The storage node subscribes to this {noun} and shares its key, which is why it carries no \
`id` of its own."
)
};
format!(
"One node holds ONE storage, so the MACRO is the storage declaration and {article} {noun}'s \
is {held}. {elsewhere}"
)
}
const TABLE_VALUE: &str = "`table` must be the table's name, in a string literal";
fn record_database(
inner: &syn::meta::ParseNestedMeta<'_>,
kind: DatabaseKind,
databases: &mut Vec<DatabaseBlock>,
errors: &mut Errors,
) -> syn::Result<()> {
let repeated = databases.iter().any(|block| block.kind == kind);
if repeated {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once — one block per database",
kind = kind.as_str()
),
));
}
let mut block = DatabaseBlock {
kind,
uniques: Vec::new(),
rename: None,
comparison: None,
table: None,
schema: None,
from: ConversionSpec::default(),
into: ConversionSpec::default(),
aliases: AliasOptions::default(),
};
let mut alias_seen = None;
let scope = format!("`{}(…)`", kind.as_str());
let walked = attribute::options(inner, |option| {
if option.path.is_ident("alias") {
return alias::block(
&option,
&mut block.aliases,
&mut alias_seen,
&scope,
alias::Depth::Sized,
errors,
);
}
if option.path.is_ident("row") {
return attribute::rename_block(&option, &mut block.rename, "row", errors);
}
if option.path.is_ident("comparison") {
return attribute::rename_block(&option, &mut block.comparison, "comparison", errors);
}
if option.path.is_ident("rename") {
errors.push(named(
&option,
format!(
"`{db}` emits a ROW and a COMPARISON, so a bare `rename` cannot say which — write \
`row(rename = \"…\")` or `comparison(rename = \"…\")`",
db = kind.as_str()
),
));
return Ok(());
}
for (spelled, belongs) in [("table", true), ("collection", false)] {
if option.path.is_ident(spelled) {
if belongs != kind.is_sql() {
let (theirs, ours) = if belongs {
("table", "collection")
} else {
("collection", "table")
};
errors.push(named(
&option,
format!(
"`{theirs}` is not `{db}`'s word — `{db}` names it `{ours} = \"…\"`",
db = kind.as_str()
),
));
return Ok(());
}
match value::literal(&option, TABLE_VALUE) {
Ok(name) => set_once(
&mut block.table,
name,
&option.path,
&format!("`{spelled}` is declared more than once in {scope} — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
}
if option.path.is_ident("unique") {
return composite_unique(&option, kind, &mut block.uniques, errors);
}
if option.path.is_ident("schema") {
if !kind.is_sql() {
errors.push(named(
&option,
format!(
"`schema` is a SQL notion and `{db}` has none — it names its database and its \
collection, and the collection is `collection = \"…\"`",
db = kind.as_str()
),
));
return Ok(());
}
match value::literal(
&option,
"`schema` must be the schema's name, in a string literal",
) {
Ok(name) => set_once(
&mut block.schema,
name,
&option.path,
&format!("`schema` is declared more than once in {scope} — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("error") {
errors.push(named(
&option,
format!(
"`error` rides its LEG now — write `try_into(error = \"…\")` for the read or \
`try_from(error = \"…\")` for the write, in {scope}. A row's read and its write are two \
impls with two callers, so one cell over both said that either shares an error with the \
other or that the shape had not been asked."
),
));
return Ok(());
}
if conversion(
&option,
&mut block.from,
&mut block.into,
&scope,
Cells::Admitted,
errors,
) {
return Ok(());
}
errors.push(column_option(
&option,
kind,
&format!(
"unknown entry in {scope} — a database block takes `rename = \"…\"`, `{name} = \"…\"`, \
{schema}`alias(…)`{unique} and the row's own conversions, each of which may carry its \
leg's `error = \"…\"`",
name = if kind.is_sql() { "table" } else { "collection" },
schema = if kind.is_sql() {
"`schema = \"…\"`, "
} else {
""
},
unique = if kind.is_sql() { ", `unique(…)`" } else { "" }
),
&["rename", "alias", "from", "try_from", "into", "try_into"]
.into_iter()
.chain(if kind.is_sql() {
vec!["table", "schema", "unique"]
} else {
vec!["collection"]
})
.collect::<Vec<_>>(),
));
Ok(())
});
if !repeated {
databases.push(block);
}
walked
}
fn composite_unique(
option: &syn::meta::ParseNestedMeta<'_>,
kind: DatabaseKind,
uniques: &mut Vec<CompositeUniqueWord>,
errors: &mut Errors,
) -> syn::Result<()> {
if !kind.is_sql() {
errors.push(named(
option,
format!(
"`unique(…)` is a SQL constraint and `{db}` renders none — this crate's `{db}` emission \
builds a collection and no index, so a constraint written here would be read and then \
enforced by nothing. Declare it on the SQL databases this record names, or keep the \
uniqueness where `{db}` can hold it: in the document's own `_id`.",
db = kind.as_str()
),
));
return Ok(());
}
if !attribute::has_block(option) || attribute::empty_group(option) {
errors.push(named(
option,
"`unique(…)` must name at least one field — a constraint over no column constrains nothing, \
and the statement it would render is not legal SQL. Write the fields it is over, in the \
order the index should carry them: `unique(media, track, index)`."
.to_owned(),
));
return Ok(());
}
let at = option.path.clone();
let mut entries: Vec<syn::Ident> = Vec::new();
let walked = option.parse_nested_meta(|entry| {
let Some(name) = entry.path.get_ident().cloned() else {
errors.push(attribute::unknown(
&entry,
"`unique(…)` takes field idents",
&[],
));
return Ok(());
};
if attribute::has_value(&entry) || attribute::has_block(&entry) {
errors.push(attribute::named(
&entry,
format!(
"`{name}` is one COLUMN of this constraint and takes nothing — a composite unique is a \
list of fields and the ORDER is the only thing said about them"
),
));
return Ok(());
}
if let Some(first) = entries.iter().find(|written| *written == &name) {
errors.push(syn::Error::new_spanned(
&entry.path,
format!(
"`{name}` is named twice in one `unique(…)` — a column appears once in an index, and a \
constraint that repeated it would be the same constraint one column narrower"
),
));
let _ = first;
return Ok(());
}
entries.push(name);
Ok(())
});
uniques.push(CompositeUniqueWord { entries, at });
walked
}
fn record_backend(
inner: &syn::meta::ParseNestedMeta<'_>,
kind: GraphqlKind,
backends: &mut Vec<BackendBlock>,
errors: &mut Errors,
) -> syn::Result<()> {
let repeated = backends.iter().any(|block| block.kind == kind);
if repeated {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once in `graphql(…)` — one block per backend",
kind = kind.as_str()
),
));
}
let mut block = BackendBlock {
kind,
rename: None,
attrs: None,
};
let scope = format!("`{}(…)`", kind.as_str());
let walked = attribute::options(inner, |option| {
if option.path.is_ident("rename") {
match rename(&option) {
Ok(spelled) => set_once(
&mut block.rename,
spelled,
&option.path,
&format!("`rename` is declared more than once in {scope} — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("attrs") {
match attribute::verbatim(&option) {
Ok(tokens) => set_once(
&mut block.attrs,
tokens,
&option.path,
&format!("`attrs(…)` is declared more than once in {scope} — one list, one type"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if let Some(error) = queryability(&option) {
errors.push(error);
return Ok(());
}
errors.push(wire_option(
&option,
&format!(
"unknown entry in {scope} on a record — a backend block takes `rename = \"…\"` and \
`attrs(…)`; `input_type` and `output_type` describe one FIELD"
),
&["rename", "attrs"],
));
Ok(())
});
if !repeated {
backends.push(block);
}
walked
}
#[derive(Default)]
struct FaceBlock {
rename: Option<syn::LitStr>,
rust: Option<syn::Ident>,
attrs: Option<proc_macro2::TokenStream>,
}
fn face_block(
inner: &syn::meta::ParseNestedMeta<'_>,
slot: &mut Option<FaceBlock>,
position: &str,
direction: Direction,
errors: &mut Errors,
) -> syn::Result<()> {
if slot.is_some() {
errors.push(syn::Error::new_spanned(
&inner.path,
format!("`{position}(…)` is declared more than once — one block per schema position"),
));
}
let mut block = FaceBlock::default();
let scope = format!("`{position}(…)`");
let walked = attribute::options(inner, |option| {
if option.path.is_ident("rename") {
match value::literal(&option, WIRE_NAME) {
Ok(spelled) => set_once(
&mut block.rename,
spelled,
&option.path,
&format!("`rename` is declared more than once in {scope} — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("field") {
if position != "output" {
errors.push(named(&option, FIELD_IS_THE_OUTPUTS.to_owned()));
return Ok(());
}
match value::literal(&option, OUTPUT_FIELD)
.and_then(|literal| value::named_field(&literal, OUTPUT_FIELD))
{
Ok(member) => set_once(
&mut block.rust,
member,
&option.path,
&format!("`field` is declared more than once in {scope} — one member, one name"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("type") {
errors.push(named(
&option,
"`type` moved to the field's own block — write `graphql(type = \"…\")`. The wire form is \
ONE: the operand a client filters with and the value it receives back are the same thing, \
and neither may vary with a deployment's storage backend."
.to_owned(),
));
return Ok(());
}
if option.path.is_ident("attrs") {
match attribute::verbatim(&option) {
Ok(tokens) => set_once(
&mut block.attrs,
tokens,
&option.path,
&format!("`attrs(…)` is declared more than once in {scope} — one list, one field"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
let wrong = if direction.plain == "into" {
[("from", "try_from")]
} else {
[("into", "try_into")]
};
for (plain, fallible) in wrong {
if option.path.is_ident(plain) || option.path.is_ident(fallible) {
return {
errors.push(named(
&option,
format!(
"`{position}(…)` takes `{}`/`{}` — `from` BUILDS the projection its block is \
about and `into` LEAVES it, so an `input` is written with `into` and an `output` \
with `from`",
direction.plain, direction.fallible
),
));
Ok(())
};
}
}
for spelling in [direction.plain, direction.fallible] {
if option.path.is_ident(spelling) {
errors.push(named(
&option,
format!(
"`{spelling}` moved out of `{position}(…)` and gained a DATABASE — write \
`graphql({home}({db}({spelling} = \"…\")))`. A crossing has a row on one side, and a \
row is one database's; what stood here crossed from the DOMAIN, which is not what a \
deployment will answer with.",
db = "<db>",
home = if direction.plain == "from" {
"output"
} else {
"input(comparison"
},
),
));
return Ok(());
}
}
if let Some(error) = queryability(&option) {
errors.push(error);
return Ok(());
}
errors.push(wire_option(
&option,
&format!(
"unknown entry in {scope} — a schema position takes `rename = \"…\"`, `attrs(…)` and — in \
`output(…)` — `field = \"…\"`; the wire FORM is the field's own `type = \"…\"` and its \
crossings are per database"
),
&if position == "output" {
vec!["rename", "attrs", "field"]
} else {
vec!["rename", "attrs"]
},
));
Ok(())
});
if slot.is_none() {
*slot = Some(block);
}
walked
}
const OUTPUT_FIELD: &str = "`field` must be the name the output object reads this field under, as an identifier in a string \
literal";
const FIELD_IS_THE_OUTPUTS: &str = "`field` names the OUTPUT object's accessor for a field — write \
it in `output(…)`. The input face names a FILTER field, whose \
Rust spelling is the mangling of the schema name `rename` \
already moves, so there is no second ident here to name.";
fn field_backend(
inner: &syn::meta::ParseNestedMeta<'_>,
kind: GraphqlKind,
per_backend: &mut Vec<FieldBackend>,
errors: &mut Errors,
) -> syn::Result<()> {
let repeated = per_backend.iter().any(|block| block.kind == kind);
if repeated {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once in `graphql(…)` on this field — one block per backend",
kind = kind.as_str()
),
));
}
let mut block = FieldBackend {
kind,
at: inner.path.clone(),
input: None,
output: None,
skip: None,
};
let scope = format!("`{}(…)` on this field", kind.as_str());
let walked = attribute::options(inner, |option| {
if option.path.is_ident("input") {
return face_block(&option, &mut block.input, "input", LEAVES, errors);
}
if option.path.is_ident("output") {
return face_block(&option, &mut block.output, "output", BUILDS, errors);
}
if option.path.is_ident("skip") {
if attribute::has_value(&option) || attribute::has_block(&option) {
errors.push(attribute::named(&option, WIRE_SKIP_IS_BARE.to_owned()));
return Ok(());
}
attribute::skip_entry(&option);
set_once(
&mut block.skip,
option.path.clone(),
&option.path,
&format!("`skip` is declared more than once in {scope} — one word, one backend"),
errors,
);
return Ok(());
}
if let Some(error) = queryability(&option) {
errors.push(error);
return Ok(());
}
errors.push(wire_option(
&option,
&format!(
"unknown entry in {scope} — a field's backend block takes `skip`, `input(…)` and \
`output(…)`, the last two being two SCHEMA POSITIONS that may differ in name, type and \
attributes"
),
&["skip", "input", "output"],
));
Ok(())
});
if !repeated {
per_backend.push(block);
}
walked
}
fn wire_option(
option: &syn::meta::ParseNestedMeta<'_>,
takes: &str,
vocabulary: &[&str],
) -> syn::Error {
if let Some(error) = queryability(option) {
return error;
}
if option.path.is_ident("desc") || option.path.is_ident("description") {
return named(
option,
"a description is passed through verbatim — write `attrs(desc = \"…\")` in the backend's \
block. A source `///` comment is deliberately NOT published: what reaches a schema is what a \
declaration says reaches it."
.to_owned(),
);
}
attribute::unknown(option, takes, vocabulary)
}
pub(crate) fn conversion(
option: &syn::meta::ParseNestedMeta<'_>,
from: &mut ConversionSpec,
into: &mut ConversionSpec,
scope: &str,
cells: Cells,
errors: &mut Errors,
) -> bool {
for (spelled, fallible, reads, direction) in [
("from", false, true, BUILDS),
("try_from", true, true, BUILDS),
("into", false, false, LEAVES),
("try_into", true, false, LEAVES),
] {
if option.path.is_ident(spelled) {
let slot = if reads { &mut *from } else { &mut *into };
let admits = fallible && matches!(cells, Cells::Admitted);
let (named, cell) = leg(option, spelled, fallible, admits, scope, errors);
if let Some(path) = cell {
set_once(
&mut slot.cell,
path,
&option.path,
&format!("`error` is declared more than once in `{spelled}(…)` — one leg, one type"),
errors,
);
}
if let Some(named) = named {
slot.set(fallible, named, scope, direction, errors);
}
return true;
}
}
false
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Cells {
Admitted,
Elsewhere,
}
fn leg(
option: &syn::meta::ParseNestedMeta<'_>,
spelled: &str,
fallible: bool,
cell_admitted: bool,
scope: &str,
errors: &mut Errors,
) -> (Option<Named>, Option<syn::Path>) {
let at = option.path.clone();
if !attribute::has_block(option) {
return match value::parse_literal::<syn::Path>(
option,
&format!(
"`{spelled}` must be a path to a function, in a string literal — or the structured form \
`{spelled}(…)`, which carries the conversion beside whatever else this block says about \
the leg"
),
) {
Ok(path) => (
Some(Named {
path,
escape: None,
at,
}),
None,
),
Err(e) => {
errors.push(e);
(None, None)
}
};
}
if !fallible {
errors.push(attribute::unknown(
option,
&format!(
"`{spelled}` takes a function and nothing else — an INFALLIBLE leg cannot fail, so it has \
no error to map and none to name, and the structured form would only restate \
`{spelled} = \"…\"` in more words"
),
&[],
));
return (None, None);
}
let (mut function, mut escape, mut cell) = (None, None, None);
let walked = attribute::options(option, |inner| {
for (entry, slot) in [("fn", &mut function), ("error_with", &mut escape)] {
if inner.path.is_ident(entry) {
match value::parse_literal::<syn::Path>(
&inner,
&format!("`{entry}` must be a path to a function, in a string literal"),
) {
Ok(path) => set_once(
slot,
path,
&inner.path,
&format!(
"`{entry}` is declared more than once in `{spelled}(…)` — one option, one value"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
}
if inner.path.is_ident("error") {
if !cell_admitted {
errors.push(named(
&inner,
format!(
"a leg's `error` is the RECORD's — write it at `{spelled}(error = \"…\")` in the \
record's own block for this crossing. What a refusal is CALLED is one answer for the \
whole record; a field says how one column crosses, and where its function's error \
cannot be absorbed, `error_with` maps it."
),
));
return Ok(());
}
match value::parse_literal::<syn::Path>(
&inner,
"`error` must be a path to the type this leg's fallible impls answer with, in a string \
literal",
) {
Ok(path) => set_once(
&mut cell,
path,
&inner.path,
&format!("`error` is declared more than once in `{spelled}(…)` — one leg, one type"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
&format!(
"unknown entry in `{spelled}(…)` in {scope} — a leg takes `fn = \"…\"`, which is the \
conversion, `error_with = \"…\"`, which maps that function's error{cell}",
cell = if cell_admitted {
", and `error = \"…\"`, which names the type this leg's impls answer with"
} else {
""
}
),
&if cell_admitted {
vec!["fn", "error_with", "error"]
} else {
vec!["fn", "error_with"]
},
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
if escape.is_some() && function.is_none() {
errors.push(syn::Error::new_spanned(
&at,
format!(
"`{spelled}(…)` maps an error and names no function — `error_with` is what a CONVERSION's \
error is carried through, so there is nothing here for it to map"
),
));
return (None, cell);
}
let Some(path) = function else {
if !cell_admitted {
errors.push(syn::Error::new_spanned(
&at,
format!(
"`{spelled}(…)` names no function — the structured form exists to carry `error_with` \
BESIDE the conversion, so `fn = \"…\"` is what it is about and is not optional"
),
));
}
return (None, cell);
};
(Some(Named { path, escape, at }), cell)
}
fn column_option(
option: &syn::meta::ParseNestedMeta<'_>,
kind: DatabaseKind,
takes: &str,
vocabulary: &[&str],
) -> syn::Error {
for name in ["indexed", "unique", "copy", "edge", "type"] {
if option.path.is_ident(name) {
return named(
option,
format!(
"`{name}` describes one COLUMN, and this block describes the whole row — write it on the \
field, as `#[ingraph({db}({name}))]`",
db = kind.as_str()
),
);
}
}
if let Some(name) = NULLABILITY.iter().find(|name| option.path.is_ident(name)) {
return named(
option,
format!(
"`{name}` is not an option — a column's nullability follows the `optional` MARKER on the \
field and is not overridable"
),
);
}
attribute::unknown(option, takes, vocabulary)
}
fn key_block(
inner: &syn::meta::ParseNestedMeta<'_>,
base: &mut Option<syn::Ident>,
object: &mut Option<syn::LitStr>,
argument: &mut Option<syn::LitStr>,
errors: &mut Errors,
) -> syn::Result<()> {
if !attribute::has_block(inner) || attribute::empty_group(inner) {
errors.push(attribute::unknown(
inner,
"`key(…)` names the ADDRESS — `rename = \"…\"` re-bases both of its faces, and \
`output(rename = \"…\")` and `input(rename = \"…\")` name the schema's reading half and its \
sending half outright. A block with none of them says nothing",
&[],
));
return Ok(());
}
attribute::options(inner, |option| {
if option.path.is_ident("rename") {
match value::parse_literal::<syn::Ident>(&option, attribute::TYPE_NAME) {
Ok(spelled) => set_once(
base,
spelled,
&option.path,
"`rename` is declared more than once in `key(…)` — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
for (what, slot) in [("output", &mut *object), ("input", &mut *argument)] {
if option.path.is_ident(what) {
let walked = attribute::sdl_name_block(&option, slot, what, errors);
if let Some(name) = slot.as_ref() {
wire::refuse_invalid_name(&name.value(), name, errors);
}
return walked;
}
}
errors.push(attribute::unknown(
&option,
"unknown entry in `key(…)` — it takes `rename = \"…\"`, the BASE both of the address's faces \
are built on, and one block per face: `output(rename = \"…\")` is the object a client reads \
an address back in, `input(rename = \"…\")` the object it sends one in. A face named outright \
is carried verbatim; a face left unnamed takes the base, and the sending half takes it with \
`Input` on the end",
&["rename", "output", "input"],
));
Ok(())
})
}
fn rename(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<syn::Ident> {
value::parse_literal(
meta,
"`rename` must be a valid identifier, in a string literal",
)
}
#[derive(Default)]
struct Markers {
id: Option<syn::Path>,
copy: Option<syn::Path>,
repeated: Option<syn::Path>,
optional: Option<syn::Path>,
key: Option<Rename>,
lineage: Option<Rename>,
storage: FieldStorage,
build: Option<Build>,
skip: Option<SkipField>,
graphql: Option<WireField>,
label_refused: bool,
label: Option<Written>,
reference: Option<syn::Path>,
}
#[derive(Default)]
struct FieldStorage {
rename: Option<syn::LitStr>,
rename_at: Option<syn::Path>,
sortable: Option<syn::Path>,
indexed: Option<syn::Path>,
flatten: Option<syn::Path>,
per_db: Vec<FieldDatabase>,
}
impl FieldStorage {
fn at(&self) -> Option<&syn::Path> {
self
.rename_at
.as_ref()
.or(self.sortable.as_ref())
.or(self.indexed.as_ref())
.or(self.flatten.as_ref())
.or_else(|| self.per_db.first().map(|per| &per.at))
}
fn presence(&self) -> impl Iterator<Item = &FieldDatabase> {
self.per_db.iter().filter(|per| per.bare)
}
fn participates(&self, kind: DatabaseKind, declared: &[DatabaseKind]) -> bool {
let narrowed = self.presence().any(|per| declared.contains(&per.kind));
if narrowed && !self.presence().any(|per| per.kind == kind) {
return false;
}
!self
.per_db
.iter()
.any(|per| per.kind == kind && per.skip.is_some())
}
fn fill_at(&self, kind: DatabaseKind) -> Option<&SkipField> {
self
.per_db
.iter()
.find(|per| per.kind == kind)
.and_then(|per| per.skip.as_ref())
.filter(|skip| skip.default.is_some())
}
}
pub(crate) struct SkipField {
pub(crate) at: syn::Path,
pub(crate) default: Option<syn::Path>,
}
impl SkipField {
pub(crate) fn fill(&self) -> Fill {
use syn::spanned::Spanned as _;
Fill {
at: self.at.span(),
named: self.default.clone(),
}
}
}
pub(crate) struct FieldDatabase {
pub(crate) kind: DatabaseKind,
pub(crate) at: syn::Path,
pub(crate) bare: bool,
pub(crate) rename: Option<syn::LitStr>,
pub(crate) indexed: Option<syn::Path>,
pub(crate) unique: Option<syn::Path>,
pub(crate) copy: Option<syn::Path>,
pub(crate) edge: Option<syn::Path>,
pub(crate) flatten: Option<syn::Path>,
pub(crate) skip: Option<SkipField>,
pub(crate) stored: Option<syn::Type>,
pub(crate) from: ConversionSpec,
pub(crate) into: ConversionSpec,
}
impl FieldDatabase {
pub(crate) fn configured(&self) -> bool {
self.rename.is_some()
|| self.indexed.is_some()
|| self.unique.is_some()
|| self.copy.is_some()
|| self.edge.is_some()
|| self.stored.is_some()
|| self.from.written()
|| self.into.written()
}
}
struct Rename {
name: syn::Ident,
at: syn::Path,
}
impl Markers {
fn projection(&self, field: &syn::Ident, errors: &mut Errors) -> Projection {
let declared: Vec<(&str, &syn::Path)> = [
("copy", self.copy.as_ref()),
("repeated", self.repeated.as_ref()),
("optional", self.optional.as_ref()),
]
.into_iter()
.filter_map(|(name, path)| path.map(|path| (name, path)))
.collect();
column::projection(&declared, field, errors)
}
fn reference(&self) -> Option<Reference> {
let held = self.label.as_ref().is_some_and(Written::collection)
|| self.repeated.is_some()
|| self.optional.is_some();
self.reference.as_ref().map(|target| Reference {
target: target.clone(),
through: if held { Through::Held } else { Through::Value },
})
}
}
const SKIP_DEFAULT: &str = "`default` names the FUNCTION that fills a skipped column — a \
`fn() -> T`, as a path in a string literal, which is serde's own \
`default = \"…\"` spelling";
pub(crate) fn skip_word(
meta: &syn::meta::ParseNestedMeta<'_>,
scope: &str,
errors: &mut Errors,
) -> syn::Result<SkipField> {
let mut declared = SkipField {
at: meta.path.clone(),
default: None,
};
attribute::options(meta, |option| {
if option.path.is_ident("default") {
match value::parse_literal::<syn::Path>(&option, SKIP_DEFAULT) {
Ok(path) => set_once(
&mut declared.default,
path,
&option.path,
&format!(
"`default` is declared more than once in `skip(…)` {scope} — one option, one value"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
&format!(
"unknown entry in `skip(…)` {scope} — the word takes `default = \"path::to::fn\"` and \
nothing else: a skipped column has no stored value, so what a read needs told is the \
function that supplies one. Written bare, the fill is `Default::default()`."
),
&["default"],
));
Ok(())
})?;
Ok(declared)
}
fn field_markers(attrs: &[syn::Attribute], node: NodeKind, errors: &mut Errors) -> Markers {
let mut markers = Markers::default();
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("id") {
set_once(
&mut markers.id,
meta.path.clone(),
&meta.path,
"`id` is declared more than once on this field — one marker, one field",
errors,
);
return Ok(());
}
for marker in ["copy", "repeated", "optional"] {
if meta.path.is_ident(marker) {
let slot = match marker {
"copy" => &mut markers.copy,
"repeated" => &mut markers.repeated,
_ => &mut markers.optional,
};
set_once(
slot,
meta.path.clone(),
&meta.path,
&format!("`{marker}` is declared more than once on this field — one marker, one field"),
errors,
);
return Ok(());
}
}
for scope in ["key", "lineage"] {
if meta.path.is_ident(scope) {
let block = meta.path.clone();
let slot = if scope == "key" {
&mut markers.key
} else {
&mut markers.lineage
};
return meta.parse_nested_meta(|inner| {
if inner.path.is_ident("rename") {
match rename(&inner) {
Ok(name) => set_once(
slot,
Rename {
name,
at: block.clone(),
},
&inner.path,
&format!(
"`rename` is declared more than once in `{scope}(…)` on this field — one \
option, one value"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
&format!("unknown entry in `{scope}(…)` — it takes `rename = \"…\"`"),
&["rename"],
));
Ok(())
});
}
}
if meta.path.is_ident(crate::construct::WORD) {
return crate::construct::field(&meta, &mut markers.build, errors);
}
if meta.path.is_ident("skip") {
let at = meta.path.clone();
let declared = skip_word(&meta, "on this field", errors)?;
set_once(
&mut markers.skip,
declared,
&at,
"`skip` is declared more than once on this field — one word, one field",
errors,
);
return Ok(());
}
if meta.path.is_ident("persist") {
attribute::skip_entry(&meta);
errors.push(named(
&meta,
format!(
"`persist` is retired at a field — a bare field is already a column in every database the \
declaration names, so there is nothing left for a wrapper to grant. What it held goes on \
the field itself, where the head writes its own store words: NARROW with a database's \
bare word (`#[ingraph({db})]`), CONFIGURE with its block (`#[ingraph({db}(rename = \
\"…\", type = \"…\", indexed))]`), and write what every database shares bare beside \
them (`rename = \"…\"`, `sortable`, `indexed`, `flatten`). The absence is still `skip`.",
db = DatabaseKind::Sqlite.as_str(),
),
));
return Ok(());
}
if let Some(kind) = database_kind(&meta.path) {
return field_database(&meta, kind, &mut markers.storage.per_db, errors);
}
if meta.path.is_ident(SORTABLE) {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(attribute::named(&meta, BARE_WORD.to_owned()));
return Ok(());
}
attribute::skip_entry(&meta);
set_once(
&mut markers.storage.sortable,
meta.path.clone(),
&meta.path,
SORTABLE_ONCE,
errors,
);
return Ok(());
}
if meta.path.is_ident(INDEXED) {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(attribute::named(&meta, BARE_WORD.to_owned()));
return Ok(());
}
attribute::skip_entry(&meta);
set_once(
&mut markers.storage.indexed,
meta.path.clone(),
&meta.path,
INDEXED_ONCE,
errors,
);
return Ok(());
}
if meta.path.is_ident(DERIVED_COLUMN) {
attribute::skip_entry(&meta);
errors.push(attribute::named(
&meta,
DERIVED_COLUMN_AT_A_RECORD.to_owned(),
));
return Ok(());
}
if meta.path.is_ident(WRITE_TRANSFORM) || meta.path.is_ident(READ_TRANSFORM) {
attribute::skip_entry(&meta);
errors.push(attribute::named(&meta, TRANSFORM_AT_A_RECORD.to_owned()));
return Ok(());
}
if meta.path.is_ident("flatten") {
if attribute::has_value(&meta) || attribute::has_block(&meta) {
errors.push(attribute::named(&meta, FLATTEN_IS_BARE.to_owned()));
return Ok(());
}
attribute::skip_entry(&meta);
set_once(
&mut markers.storage.flatten,
meta.path.clone(),
&meta.path,
"`flatten` is declared more than once on this field — one word, one layout",
errors,
);
return Ok(());
}
if meta.path.is_ident("vector") {
errors.push(named(
&meta,
format!(
"`vector` marks a field as an embedding, and an embedding index is its OWN node, so the \
marker is that node's declaration: write the field under the `vector` macro, on a type \
whose `upstream(…)` names this {noun}. {law} The field's own column stays here, where \
`persist` puts it.",
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
if meta.path.is_ident("blob") {
errors.push(named(
&meta,
format!(
"`blob` marks a field as an artifact's payload, and an artifact family is its OWN node, so \
the marker is that node's declaration: write the field under the `blob` macro, on a type \
whose `upstream(…)` names this {noun}. {law} A `Vec<u8>` COLUMN is a different thing and \
stays: write `bytes` beside `persist`, and the bytes are a value in this {noun}'s own \
row.",
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
if meta.path.is_ident("fulltext") {
errors.push(named(
&meta,
format!(
"`fulltext` marks a field for an index that is its OWN node, so the marker — and the \
per-engine conversion its block carried — belong to that node's declaration: write the \
field under the `fulltext` macro, on a type whose `upstream(…)` names this {noun}. {law} \
The field's own column stays here, where `persist` puts it.",
noun = node.noun(),
law = owns_one_storage(node),
),
));
return Ok(());
}
if meta.path.is_ident("graphql") {
if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
attribute::skip_entry(&meta);
errors.push(named(
&meta,
"`graphql` alone says nothing now — a declaration naming a wire backend publishes every \
column it has, so the word that put a field on the face is the DEFAULT. Delete it. \
`graphql(…)` stays for what it always also did: name the field on the wire \
(`rename = \"…\"`), pin its form (`type = \"…\"`), carry its crossings \
(`output(…)`, `input(comparison(…))`) and WITHHOLD it (`skip`, or one backend's own \
`async_graphql(skip)`)."
.to_owned(),
));
return Ok(());
}
let at = meta.path.clone();
let mut refused = false;
let mut declared = WireField {
at: at.clone(),
rename: None,
ty: None,
output: Vec::new(),
comparison: Vec::new(),
skip: None,
per_backend: Vec::new(),
};
let walked = attribute::options(&meta, |inner| {
if let Some(kind) = graphql_kind(&inner.path) {
return field_backend(&inner, kind, &mut declared.per_backend, errors);
}
if inner.path.is_ident("skip") {
if attribute::has_value(&inner) || attribute::has_block(&inner) {
errors.push(attribute::named(&inner, WIRE_SKIP_IS_BARE.to_owned()));
return Ok(());
}
attribute::skip_entry(&inner);
set_once(
&mut declared.skip,
inner.path.clone(),
&inner.path,
"`skip` is declared more than once in `graphql(…)` on this field — one word, one field",
errors,
);
return Ok(());
}
if inner.path.is_ident("type") {
match value::parse_literal::<syn::Type>(
&inner,
"`type` must be the form this field takes ON THE WIRE, in a string literal",
) {
Ok(ty) => set_once(
&mut declared.ty,
ty,
&inner.path,
"`type` is declared more than once in `graphql(…)` on this field — one field, one \
wire form",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("output") {
return wire_legs(
&inner,
&mut declared.output,
"graphql(output(…))",
BUILDS,
errors,
);
}
if inner.path.is_ident("input") {
return attribute::options(&inner, |position| {
if position.path.is_ident("comparison") {
return wire_legs(
&position,
&mut declared.comparison,
"graphql(input(comparison(…)))",
LEAVES,
errors,
);
}
if position.path.is_ident("orderby") || position.path.is_ident("order_by") {
errors.push(named(
&position,
"an order carries a COLUMN and a DIRECTION and never a value — its lowering is a \
variant partition emitted from the tier declarations, so a per-field conversion \
here would have no reader"
.to_owned(),
));
return Ok(());
}
if position.path.is_ident("pagination") || position.path.is_ident("page") {
errors.push(named(
&position,
"a cursor is an opaque round trip of the ENGINE's own: its values speak `persist`'s \
vocabulary and never take the wire form, so there is nothing here for a conversion \
to cross"
.to_owned(),
));
return Ok(());
}
errors.push(attribute::unknown(
&position,
"unknown entry in `input(…)` on a field — the input half has ONE crossing that \
carries a value, and it is `comparison(…)`",
&["comparison"],
));
Ok(())
});
}
if inner.path.is_ident("marker") {
let message = marker_is_the_older_spelling(&inner);
errors.push(attribute::unknown(&inner, &message, &[]));
refused = true;
return Ok(());
}
if inner.path.is_ident("rename") {
match value::literal(&inner, WIRE_NAME) {
Ok(spelled) => set_once(
&mut declared.rename,
spelled,
&inner.path,
"`rename` is declared more than once in `graphql(…)` on this field — one option, \
one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(wire_option(
&inner,
"unknown entry in `graphql(…)` on a field — it takes `skip`, `rename = \"…\"`, \
`type = \"…\"`, `output(<db>(…))`, `input(comparison(<db>(…)))` and one block per \
backend (`async_graphql`)",
&["skip", "rename", "type", "output", "input"]
.into_iter()
.chain(GraphqlKind::ALL.map(GraphqlKind::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
markers.label_refused |= refused;
set_once(
&mut markers.graphql,
declared,
&at,
"`graphql` is declared more than once on this field — one marker, one field",
errors,
);
return walked;
}
if meta.path.is_ident(REFERS) {
let at = meta.path.clone();
let target = if attribute::has_value(&meta) {
value::parse_literal::<syn::Path>(&meta, REF_SHAPE)
} else {
reference_block(&meta, errors)
};
match target {
Ok(target) => set_once(
&mut markers.reference,
target,
&at,
"`ref` is declared more than once on this field — one column addresses one record",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("rename") {
match value::literal(&meta, COLUMN_VALUE) {
Ok(name) => {
set_once(
&mut markers.storage.rename,
name,
&meta.path,
"`rename` is declared more than once on this field — one option, one value",
errors,
);
markers
.storage
.rename_at
.get_or_insert_with(|| meta.path.clone());
}
Err(e) => errors.push(e),
}
return Ok(());
}
if begins_a_label(&meta.path) {
let at = meta.path.clone();
match label(&meta, errors) {
Some(declared) => set_once(&mut markers.label, declared, &at, ONE_LABEL, errors),
None => markers.label_refused = true,
}
return Ok(());
}
for word in [
ingraph_codegen::aggregate::GROUP,
ingraph_codegen::aggregate::MEASURE,
] {
if meta.path.is_ident(word) {
errors.push(named(
&meta,
crate::aggregate::wrong_kind(word, node, crate::aggregate::Written::OnAField),
));
return Ok(());
}
}
errors.push(misplaced(
&meta,
&format!(
"unknown `ingraph` field attribute — a field takes `id`, `copy`, `repeated`, `optional`, \
`skip`, `graphql`, `ref`, `key(…)`, `lineage(…)` and `builder(…)`; its STORAGE words \
(`rename = \"…\"`, `sortable`, `indexed`, `flatten`, and one block per database — \
{stores}); and its \
LABEL: {list}, a collection's element inside it (`list(string)`), or \
`label = \"a::marker::Path\"`",
stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
list = shipped(Label::ALL.into_iter().map(Label::as_str)),
),
&[
"id",
"copy",
"repeated",
"optional",
"rename",
SORTABLE,
INDEXED,
"flatten",
"skip",
DERIVED_COLUMN,
WRITE_TRANSFORM,
READ_TRANSFORM,
"graphql",
REFERS,
"key",
"lineage",
crate::construct::WORD,
]
.into_iter()
.chain(DatabaseKind::ALL.map(DatabaseKind::as_str))
.chain(label_words())
.collect::<Vec<_>>(),
));
Ok(())
});
crate::construct::refuse_a_whole_non_option(
markers.optional.is_some(),
markers.build.as_ref(),
errors,
);
markers
}
fn reference_block(
meta: &syn::meta::ParseNestedMeta<'_>,
errors: &mut Errors,
) -> syn::Result<syn::Path> {
let mut target: Option<syn::Path> = None;
attribute::options(meta, |option| {
if option.path.is_ident("type") {
match value::parse_literal::<syn::Path>(&option, REF_TYPE) {
Ok(path) => set_once(
&mut target,
path,
&option.path,
"`type` is declared more than once in `ref(…)` — one option, one value",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
"unknown entry in `ref(…)` — it takes `type = \"…\"`",
&["type"],
));
Ok(())
})?;
target.ok_or_else(|| syn::Error::new_spanned(&meta.path, REF_SHAPE))
}
const WIRE_NAME: &str = "a wire field's `rename` must be its name in the schema, in a string \
literal";
const WIRE_SKIP_IS_BARE: &str = "`skip` on the wire is a BARE word — it takes no `default`, because \
a fill is what a READ needs when a column is not there and a field \
the wire never publishes is never read. The fill belongs to the \
storage word: `#[ingraph(skip(default = \"…\"))]`.";
const COLUMN_VALUE: &str = "a column's `rename` must be its name, in a string literal";
const FLATTEN_IS_BARE: &str = "`flatten` is a BARE word — it drops this field's own name from the \
columns its type renders, and there is nothing for a value to say \
about that. One database's own is `#[ingraph(sqlite(flatten))]`.";
pub(crate) fn field_database(
inner: &syn::meta::ParseNestedMeta<'_>,
kind: DatabaseKind,
per_db: &mut Vec<FieldDatabase>,
errors: &mut Errors,
) -> syn::Result<()> {
let repeated = per_db.iter().any(|block| block.kind == kind);
if repeated {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once on this field — one block per database",
kind = kind.as_str()
),
));
}
if attribute::has_value(inner) {
errors.push(attribute::named(
inner,
format!(
"`{kind}` names a DATABASE and takes no value — write it bare to narrow this field to that \
database, or as a block to say how it stores the column: `#[ingraph({kind}(rename = \
\"…\"))]`",
kind = kind.as_str()
),
));
return Ok(());
}
let bare = !attribute::has_block(inner) || attribute::empty_group(inner);
let mut block = FieldDatabase {
kind,
at: inner.path.clone(),
bare,
rename: None,
indexed: None,
unique: None,
copy: None,
edge: None,
flatten: None,
skip: None,
stored: None,
from: ConversionSpec::default(),
into: ConversionSpec::default(),
};
let scope = format!("`{}(…)` on this field", kind.as_str());
let walked = attribute::options(inner, |option| {
if option.path.is_ident("flatten") {
if !kind.is_sql() {
errors.push(named(
&option,
format!(
"`flatten` drops a field's name so its type's COLUMNS join the holder's, and `{db}` has \
no columns — its default is the nested subdocument already. Lifting an embedded \
document's keys into its holder is a different thing and is not spelled here.",
db = kind.as_str()
),
));
return Ok(());
}
set_once(
&mut block.flatten,
option.path.clone(),
&option.path,
&format!("`flatten` is declared more than once in {scope} — one marker, one layout"),
errors,
);
return Ok(());
}
if option.path.is_ident("edge") {
if let Some(instead) = no_strategy_to_choose(kind) {
errors.push(named(
&option,
format!(
"`edge` names a storage STRATEGY and `{db}` has none to choose — {instead}. The word \
is Postgres's alone, that being the one dialect with two usable strategies",
db = kind.as_str()
),
));
return Ok(());
}
set_once(
&mut block.edge,
option.path.clone(),
&option.path,
&format!("`edge` is declared more than once in {scope} — one word, one column"),
errors,
);
return Ok(());
}
for spelled in ["indexed", "unique", "copy"] {
if option.path.is_ident(spelled) {
let slot = match spelled {
"indexed" => &mut block.indexed,
"unique" => &mut block.unique,
_ => &mut block.copy,
};
set_once(
slot,
option.path.clone(),
&option.path,
&format!("`{spelled}` is declared more than once in {scope} — one marker, one column"),
errors,
);
return Ok(());
}
}
if option.path.is_ident("rename") {
match value::literal(&option, COLUMN_VALUE) {
Ok(name) => set_once(
&mut block.rename,
name,
&option.path,
&format!("`rename` is declared more than once in {scope} — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("type") {
match value::parse_literal::<syn::Type>(
&option,
"`type` must be the type this database stores, in a string literal",
) {
Ok(stored) => set_once(
&mut block.stored,
stored,
&option.path,
&format!("`type` is declared more than once in {scope} — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident("skip") {
let at = option.path.clone();
let declared = skip_word(&option, &scope, errors)?;
if declared.default.is_none() {
errors.push(named(
&option,
format!(
"`{db}(skip)` says this field is a column of the OTHER databases and not of `{db}`, and \
a read of a `{db}` row has to hand something back — write \
`#[ingraph({db}(skip(default = \"…\")))]`, naming the `fn() -> T` that supplies it. \
The bare word's `Default::default()` floor is the FIELD's own `#[ingraph(skip)]`, \
which is the absence stated once and read the same way out of every store; a partial \
one is read two ways, and which value the second store hands back is a fact only this \
declaration carries.",
db = kind.as_str()
),
));
return Ok(());
}
set_once(
&mut block.skip,
declared,
&at,
&format!("`skip` is declared more than once in {scope} — one word, one database"),
errors,
);
return Ok(());
}
if conversion(
&option,
&mut block.from,
&mut block.into,
&scope,
Cells::Elsewhere,
errors,
) {
return Ok(());
}
if attribute::has_block(&option) && !attribute::empty_group(&option) {
let segment = option
.path
.get_ident()
.map_or_else(|| "that".to_owned(), ToString::to_string);
errors.push(named(
&option,
format!(
"`{segment}(…)` names a SEGMENT of a held value, and a per-segment override has not \
arrived — see `flatten`, whose container is where one is written. What decides a held \
value's columns here today is one word: laid out under this field's name by default, or \
under the held type's own names with `flatten`"
),
));
return Ok(());
}
errors.push(row_option(
&option,
kind,
&format!(
"unknown entry in {scope} — a column's database block takes `rename = \"…\"`, \
`indexed`, `unique`, `copy`, `flatten`, `type = \"…\"` and its conversions, plus \
`skip(default = \"…\")` for a column this database alone does not carry; Postgres also \
takes `edge`"
),
&[
"rename", "indexed", "unique", "copy", "flatten", "skip", "type", "edge", "from",
"try_from", "into", "try_into",
],
));
Ok(())
});
if !repeated {
per_db.push(block);
}
walked
}
fn row_option(
option: &syn::meta::ParseNestedMeta<'_>,
kind: DatabaseKind,
takes: &str,
vocabulary: &[&str],
) -> syn::Error {
for name in ["table", "collection", "schema"] {
if option.path.is_ident(name) {
return named(
option,
format!(
"`{name}` names where the whole ROW lives, and this block describes one column — write \
it on the record, as `#[ingraph::record({db}({name} = \"…\"))]`",
db = kind.as_str()
),
);
}
}
if let Some(name) = NULLABILITY.iter().find(|name| option.path.is_ident(name)) {
return named(
option,
format!(
"`{name}` is not an option — a column's nullability follows the `optional` MARKER on the \
field and is not overridable: `#[ingraph(optional)]` is nullable and a field without it is \
`NOT NULL`"
),
);
}
if option.path.is_ident(SORTABLE) {
return named(
option,
format!(
"`sortable` is ONE intent for every database and this block is `{db}`'s — write it in the \
common scope, as `#[ingraph(sortable, {db}(…))]`. What each database DOES with it \
is derived rather than declared: a dialect storing the collection as a native array orders \
it already and mints nothing, and one storing edge rows mints the companion column.",
db = kind.as_str()
),
);
}
attribute::unknown(option, takes, vocabulary)
}
fn refuse_a_half_declared_collection_crossing(
field: &syn::Field,
per_db: &[FieldDatabase],
errors: &mut Errors,
) {
let source = field
.ident
.as_ref()
.expect("a named field")
.clone()
.to_string();
for per in per_db {
if per.stored.is_none() {
continue;
}
let missing: Vec<&Direction> = [(&per.from, &BUILDS), (&per.into, &LEAVES)]
.into_iter()
.filter(|(spec, _)| spec.infallible.is_none() && spec.fallible.is_none())
.map(|(_, direction)| direction)
.collect();
if missing.is_empty() {
continue;
}
let verbs = missing
.iter()
.map(|direction| format!("`{}`/`{}`", direction.plain, direction.fallible))
.collect::<Vec<_>>()
.join(" and ");
errors.push(syn::Error::new_spanned(
&per.at,
format!(
"`{source}` is a COLLECTION and `{db}` stores its ELEMENTS, so `type = \"…\"` names one \
element and the row holds the list of them — the crossing between the two is this \
declaration's, and {verbs} {is} missing. Write the pair: \
`#[ingraph({db}(type = \"E\", from = \"to_elements\", into = \"from_elements\"))]`, where \
`to_elements` takes the field's own type and answers `Vec<E>` and `from_elements` answers \
the field's own type from one. Where the two shapes already agree the functions are \
identities, and writing them is what says so.",
db = per.kind.as_str(),
is = if missing.len() == 1 { "is" } else { "are" },
),
));
}
}
fn refuse_a_strategy_on_a_column_that_is_not_a_collection(
field: &syn::Field,
per_db: &[FieldDatabase],
errors: &mut Errors,
) {
let source = field.ident.as_ref().expect("a named field");
for per in per_db {
let Some(at) = per.edge.as_ref() else {
continue;
};
errors.push(syn::Error::new_spanned(
at,
format!(
"`{source}` is not a COLLECTION and `edge` names how one is STORED — a value list goes in \
an array column or in a second table of one row per element, and a single value takes \
neither. Write `list(…)` or `set(…)` on the field if it holds many, and drop the word if \
it holds one"
),
));
}
}
fn refuse_unique_on_a_collection(
field: &syn::Field,
per_db: &[FieldDatabase],
errors: &mut Errors,
) {
let source = field.ident.as_ref().expect("a named field");
for per in per_db {
let Some(at) = per.unique.as_ref() else {
continue;
};
errors.push(syn::Error::new_spanned(
at,
format!(
"`{source}` is a COLLECTION and `unique` names a constraint over ONE column's values, held \
by at most one row apiece — a row here holds MANY values and there is no single one for \
that comparison to be about. An element repeated WITHIN one row is `set(…)`'s own \
refusal already, its edge table being keyed on the value; a claim over the whole \
collection as one value has no column here to carry it. Drop the word."
),
));
}
}
fn composite_uniques(
written: &[CompositeUniqueWord],
kind: DatabaseKind,
columns: &[PersistColumn],
collections: &[(&syn::Ident, bool)],
record: &syn::Ident,
errors: &mut Errors,
) -> Vec<CompositeUnique> {
let db = kind.as_str();
let mut resolved: Vec<CompositeUnique> = Vec::new();
for word in written {
let mut entries: Vec<RustSafeName> = Vec::new();
let mut whole = true;
for entry in &word.entries {
let Some(column) = columns.iter().find(|column| &column.source == entry) else {
whole = false;
let known = collections.iter().any(|(name, _)| *name == entry);
errors.push(syn::Error::new_spanned(
entry,
if known {
format!(
"`{entry}` is a field of `{record}` and no column of `{db}`'s row — a word narrowed \
it away from this database, so a constraint naming it here is over a column this \
`CREATE TABLE` never declares. Name it in the blocks whose rows carry it."
)
} else {
format!("`{db}(unique(…))` names fields of `{record}` — `{entry}` is not one")
},
));
continue;
};
if collections
.iter()
.any(|(name, collects)| *name == entry && *collects)
{
whole = false;
errors.push(syn::Error::new_spanned(
entry,
format!(
"`{entry}` is a COLLECTION, and a composite unique is over columns of THIS row — a \
collection's elements are rows of a second table, so the parent row holds no single \
value for the constraint to compare. An element repeated within one row is `set(…)`'s \
own refusal; a claim over the whole collection as one value has no column here to \
carry it."
),
));
continue;
}
entries.push(column.name.clone());
}
if !whole {
continue;
}
if let [only] = entries.as_slice()
&& let Some(marked) = columns
.iter()
.find(|column| column.unique && column.name.external() == only.external())
{
errors.push(syn::Error::new_spanned(
&word.at,
format!(
"`{source}` is already `unique` in `{db}`, and a one-entry `unique({source})` over it \
derives the SAME constraint name — `__ig_<table>_{column}` by either road — so the \
second statement would create nothing. The two roads differ in SCOPE and not in width: keep \
the field marker where the constraint belongs to every database this record declares, \
and this word where it belongs to `{db}` alone.",
source = marked.source,
column = only.external(),
),
));
continue;
}
if resolved.iter().any(|other| {
other.entries.len() == entries.len()
&& other
.entries
.iter()
.zip(&entries)
.all(|(left, right)| left.external() == right.external())
}) {
let columns = entries
.iter()
.map(|entry| entry.external().to_owned())
.collect::<Vec<_>>()
.join(", ");
errors.push(syn::Error::new_spanned(
&word.at,
format!(
"`{db}` declares `unique({columns})` twice — both spellings derive one constraint name, \
so the second creates nothing. A different ORDER would be a different constraint: a \
composite index answers a seek by a leading prefix of its columns, so `(a, b)` and \
`(b, a)` serve different reads."
),
));
continue;
}
resolved.push(CompositeUnique { entries });
}
resolved
}
fn refuse_indexed_on_a_collection(
field: &syn::Field,
per_db: &[FieldDatabase],
errors: &mut Errors,
) {
let source = field.ident.as_ref().expect("a named field");
for per in per_db {
let Some(at) = per.indexed.as_ref() else {
continue;
};
let db = per.kind.as_str();
errors.push(syn::Error::new_spanned(
at,
format!(
"`{source}` is a COLLECTION and `{db}(indexed)` names a structure over ONE COLUMN of this \
row — a collection is not one column of a row in any database here: it is a second table \
keyed on the row, or an array column whose elements an index reaches through that \
database's own access method. The word a collection takes is the FIELD's, written where \
nothing scopes it: `#[ingraph(list(scalar), indexed)]`. It is ONE intent and each database \
derives its mechanism from it — which is also why it cannot be written per database: on \
`{sqlite}` the path folds case, and a fold is visible in a `set(…)`'s own identity, so a \
word written for one store and withheld from the next would be a declaration that means \
two different things.",
sqlite = DatabaseKind::Sqlite.as_str(),
),
));
}
}
fn refuse_an_unfilled_absence(
field: &syn::Field,
declaring: &FieldStorage,
record: &syn::Ident,
declared: &[DatabaseKind],
errors: &mut Errors,
) {
let unfilled: Vec<DatabaseKind> = declared
.iter()
.copied()
.filter(|kind| !declaring.participates(*kind, declared))
.filter(|kind| {
!declaring
.per_db
.iter()
.any(|per| per.kind == *kind && per.skip.is_some())
})
.collect();
let (Some(first), Some(at)) = (unfilled.first(), declaring.presence().next()) else {
return;
};
let source = field.ident.as_ref().expect("a named field");
let kept: Vec<DatabaseKind> = declared
.iter()
.copied()
.filter(|kind| declaring.participates(*kind, declared))
.collect();
errors.push(syn::Error::new_spanned(
&at.at,
format!(
"`{source}` is a column of {kept} and `{record}` stores its rows in {all}, so a read of {gone} \
has no `{source}` to fetch and nothing to hand back instead — write \
`#[ingraph({db}(skip(default = \"…\")))]` for each of them, naming the `fn() -> T` that \
supplies the value there. The word may stay beside the fills or go: the two spellings state \
the same absence from its two ends, and the fill is the half only the declaration can carry.",
kept = list(&kept),
all = list(declared),
gone = list(&unfilled),
db = first.as_str(),
),
));
}
fn persist_model(
record: &syn::Ident,
node: NodeKind,
block: Option<PersistBlock>,
fence: &alias::Fence,
marked: &[(&syn::Field, Markers)],
address: &[syn::Ident],
errors: &mut Errors,
) -> Option<Persist> {
let markers = || {
marked.iter().filter_map(|(field, markers)| {
let at = markers.storage.at()?;
Some((field.ident.as_ref().expect("a named field"), at))
})
};
if !node.holds_rows() {
for (field, at) in markers() {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{field}` refines a stored column and {article} {noun} has no rows — a field's storage \
words say how a column is rendered, and columns are a `record`'s. {law}",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
),
));
}
for (field, markers) in marked {
let name = field.ident.as_ref().expect("a named field");
if let Some(skip) = &markers.skip {
errors.push(syn::Error::new_spanned(
&skip.at,
format!(
"`{name}` declares that no row holds it and {article} {noun} has no rows — `skip` is \
the answer to a question a `record` asks, and this declaration never asks it. {law}",
article = node.article(),
noun = node.noun(),
law = owns_one_storage(node),
),
));
}
}
return None;
}
let Some(block) = block.filter(|block| !block.databases.is_empty()) else {
errors.push(syn::Error::new_spanned(
record,
format!(
"`{record}` holds rows and names no store — write one of {stores} at the head, as \
`#[ingraph::record(sqlite)]`, or declare it an `entity`, which is this same declaration \
without the rows: the key family, the accessors and the wire face, all of it, and no \
table anywhere. A record IS rows.",
stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
),
));
return None;
};
let base = block.rename.clone().unwrap_or_else(|| record.clone());
let names: Vec<(syn::Ident, syn::Ident)> = block
.databases
.iter()
.map(|db| {
let row = db
.rename
.clone()
.unwrap_or_else(|| default_row_name(&base, db.kind));
let comparison = db
.comparison
.clone()
.unwrap_or_else(|| default_comparison_name(&row));
(row, comparison)
})
.collect();
let declared: Vec<DatabaseKind> = block.databases.iter().map(|db| db.kind).collect();
let participating: Vec<(&syn::Field, &FieldStorage, bool, bool)> = marked
.iter()
.filter(|(_, markers)| markers.skip.is_none())
.map(|(field, markers)| {
(
*field,
&markers.storage,
markers.optional.is_some(),
markers.label.as_ref().is_some_and(Written::collection),
)
})
.collect();
let collections: Vec<(&syn::Ident, bool)> = participating
.iter()
.map(|(field, _, _, collects)| (field.ident.as_ref().expect("a named field"), *collects))
.collect();
for (field, declaring, _, collects) in &participating {
if *collects {
refuse_a_half_declared_collection_crossing(field, &declaring.per_db, errors);
refuse_unique_on_a_collection(field, &declaring.per_db, errors);
refuse_indexed_on_a_collection(field, &declaring.per_db, errors);
} else {
refuse_a_strategy_on_a_column_that_is_not_a_collection(field, &declaring.per_db, errors);
}
}
for (_, declaring, _, _) in &participating {
for per in &declaring.per_db {
if !declared.contains(&per.kind) {
errors.push(syn::Error::new_spanned(
&per.at,
format!(
"`{db}` is not one of the databases `{record}` declares — it stores its rows in {list}. \
A field names a database to narrow itself to it or to say how it renders the column \
there, and both need the record to store the row in it first.",
db = per.kind.as_str(),
list = list(&declared),
),
));
}
}
}
for (field, declaring, _, _) in &participating {
if address.contains(field.ident.as_ref().expect("a named field")) {
continue;
}
refuse_an_unfilled_absence(field, declaring, record, &declared, errors);
}
let databases = block
.databases
.iter()
.zip(names)
.map(|(db, (name, comparison))| {
let scope = format!("`{}`", db.kind.as_str());
let fills: Vec<Filled> = participating
.iter()
.filter(|(_, declaring, _, _)| !declaring.participates(db.kind, &declared))
.filter_map(|(field, declaring, _, _)| {
Some(Filled {
source: field.ident.clone().expect("a named field"),
fill: declaring.fill_at(db.kind)?.fill(),
})
})
.collect();
let columns: Vec<PersistColumn> = participating
.iter()
.filter(|(_, declaring, _, _)| declaring.participates(db.kind, &declared))
.map(|(field, declaring, nullable, _)| {
let source = field.ident.clone().expect("a named field");
let per = declaring.per_db.iter().find(|per| per.kind == db.kind);
let column = per
.and_then(|per| per.rename.as_ref())
.or(declaring.rename.as_ref())
.map_or_else(
|| RustSafeName::from_ident(&source),
|lit| RustSafeName::new(lit.value(), lit.span()),
);
let subject = format!("`{source}` in {scope}");
let (from, into) = per.map_or_else(
|| (Conversion::Default, Conversion::Default),
|per| {
(
per.from.resolve(&subject, BUILDS, errors),
per.into.resolve(&subject, LEAVES, errors),
)
},
);
for (container, column, direction) in
[(&db.from, &from, BUILDS), (&db.into, &into, LEAVES)]
{
if let (true, true, Some(at)) = (
container.declared(),
column.declared(),
per.map(|per| &per.at).or_else(|| declaring.at()),
) {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{db}` declares `{plain}`/`{try}` for the WHOLE row and `{source}` declares one \
of its own — the row's conversion replaces the field-wise body, so both is \
ambiguous. Keep the container's, or drop it and convert field by field.",
db = db.kind.as_str(),
plain = direction.plain,
try = direction.fallible,
),
));
}
}
PersistColumn {
name: column,
domain: field.ty.clone(),
stored: per.and_then(|per| per.stored.clone()),
copy: per.is_some_and(|per| per.copy.is_some()),
edge: per.is_some_and(|per| per.edge.is_some()),
nullable: *nullable,
indexed: per.is_some_and(|per| per.indexed.is_some()),
unique: per.is_some_and(|per| per.unique.is_some()),
flatten: per.is_some_and(|per| per.flatten.is_some())
|| (declaring.flatten.is_some() && db.kind.is_sql()),
from,
into,
source,
}
})
.collect();
let uniques = composite_uniques(&db.uniques, db.kind, &columns, &collections, record, errors);
let storage = Storage {
name,
comparison,
from: db
.from
.resolve(&format!("the `{}` row", db.kind.as_str()), BUILDS, errors),
into: db
.into
.resolve(&format!("the `{}` row", db.kind.as_str()), LEAVES, errors),
columns,
fills,
aliases: db.aliases.clone(),
};
let table = db.table.as_ref().map(literal_name);
if let Some(declared) = db.table.as_ref() {
column::refuse_reserved_table(fence, &declared.value(), declared, errors);
}
let schema = db.schema.as_ref().map(syn::LitStr::value);
match db.kind {
DatabaseKind::Sqlite => DatabaseBackend::Sqlite(SqliteDatabase {
table,
schema,
uniques,
storage,
}),
DatabaseKind::Postgres => DatabaseBackend::Postgres(PostgresDatabase {
table,
schema,
uniques,
storage,
}),
DatabaseKind::Mysql => DatabaseBackend::MySql(MySqlDatabase {
table,
schema,
uniques,
storage,
}),
DatabaseKind::Mongo => DatabaseBackend::Mongo(MongoDatabase {
collection: table,
storage,
}),
}
})
.collect::<Vec<DatabaseBackend>>();
for database in &databases {
let mut taken: Vec<&PersistColumn> = Vec::new();
for column in database.columns() {
column::refuse_framework_name(fence, column.name.external(), column.name.safe(), errors);
if let Some(first) = taken
.iter()
.find(|first| first.name.safe() == column.name.safe())
{
let called = if first.name.external() == column.name.external() {
format!("one column called `{}`", column.name)
} else {
format!(
"one column called `{}` — `{}` and `{}` are two column names with one Rust spelling",
column.name.safe(),
first.name,
column.name,
)
};
errors.push(syn::Error::new_spanned(
column.name.safe(),
format!(
"the `{db}` row would carry `{first}` and `{second}` as {called} — within one database \
every column needs its own name",
db = database.kind().as_str(),
first = first.source,
second = column.source,
),
));
}
taken.push(column);
}
}
if let Some(declared) = block.table.as_ref() {
column::refuse_reserved_table(fence, &declared.value(), declared, errors);
}
Some(Persist {
backends: databases,
table: block.table.as_ref().map(literal_name),
})
}
fn no_family_block<'a>(
record: &syn::Ident,
family: &str,
consequence: &str,
puts: &str,
names: &str,
markers: impl Iterator<Item = &'a syn::Path>,
errors: &mut Errors,
) {
for at in markers {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{record}` declares no `{family}(…)` block, so {consequence} — a field's `{family}` marker \
{puts}, and the record's `{family}(…)` is what names {names}"
),
));
}
}
fn stored_in(persist: Option<&Persist>, name: &syn::Ident) -> bool {
persist.is_some_and(|persist| {
persist.backends.iter().any(|database| {
database
.columns()
.iter()
.any(|column| &column.source == name)
})
})
}
fn progress_model(persist: Option<&Persist>) -> Option<Progress> {
let hosts: Vec<ProgressHost> = persist?
.backends
.iter()
.filter_map(|backend| ProgressHost::of(backend.kind()))
.collect();
(!hosts.is_empty()).then_some(Progress { hosts })
}
fn derived_model(
block: Option<DerivedBlock>,
marked: &[(&syn::Field, Markers)],
errors: &mut Errors,
) -> Vec<Derived> {
let Some(block) = block else {
return Vec::new();
};
if block.entries.is_empty() {
errors.push(syn::Error::new_spanned(
&block.at,
"`derived(…)` names the records that point back at this one, and it names none — write \
`<name> = \"path::to::Source\"` inside it; a record nothing refers to is spelled by omitting \
the block",
));
return Vec::new();
}
block
.entries
.into_iter()
.filter(|entry| {
let clash = marked
.iter()
.any(|(field, _)| field.ident.as_ref() == Some(&entry.name));
if clash {
errors.push(syn::Error::new_spanned(
&entry.name,
format!(
"`{name}` is already a field of this record — a reverse position has NO Rust field, so \
the two would be one name on one face. One namespace per face: rename the position, or \
the field.",
name = entry.name,
),
));
}
!clash
})
.map(|entry| Derived {
name: entry.name,
source: entry.source,
field: entry.field,
})
.collect()
}
fn locate_model(
block: Option<LocateBlock>,
marked: &[(&syn::Field, Markers)],
reverse: &[Derived],
errors: &mut Errors,
) -> Vec<Artifact> {
let Some(block) = block else {
return Vec::new();
};
if block.entries.is_empty() {
errors.push(syn::Error::new_spanned(
&block.at,
"`locate(…)` names the artifact families this record answers an address for, and it names \
none — write `<name> = \"path::to::Family\"` inside it; a record nothing was derived from is \
spelled by omitting the block",
));
return Vec::new();
}
let mut settled: Vec<Artifact> = Vec::new();
for entry in block.entries {
let taken = if marked
.iter()
.any(|(field, _)| field.ident.as_ref() == Some(&entry.name))
{
Some(("a field of this record", "the field"))
} else if reverse.iter().any(|position| position.name == entry.name) {
Some((
"a reverse position this record declares",
"the reverse position",
))
} else {
None
};
if let Some((already, other)) = taken {
errors.push(syn::Error::new_spanned(
&entry.name,
format!(
"`{name}` is already {already} — an artifact position has NO Rust field either, so the \
two would be one name on one face. One namespace per face: rename the artifact, or \
{other}.",
name = entry.name,
),
));
continue;
}
let data = entry.data.and_then(|ask| {
let require = |bytes: ArtifactBytes| {
if ask.required { bytes.require() } else { bytes }
};
let Some(written) = ask.rename else {
return Some(require(ArtifactBytes::asked()));
};
let name = written.value();
if let Some(other) = settled
.iter()
.find(|position| position.data.as_ref().and_then(ArtifactBytes::name) == Some(&name))
{
errors.push(syn::Error::new_spanned(
&ask.at,
format!(
"`{name}` is the wire field `{other}` already asks for — two positions naming one \
field is one name on one face. One namespace per face: rename this ask, or the other.",
other = other.name,
),
));
return None;
}
Some(require(ArtifactBytes::named(name)))
});
settled.push(Artifact {
name: entry.name,
family: entry.family,
data,
required: entry.required,
});
}
settled
}
fn refuse_a_converter_a_quantified_column_cannot_carry(
markers: &Markers,
declaring: &WireField,
name: &syn::Ident,
errors: &mut Errors,
) {
if markers.label.as_ref().and_then(Written::word) != Some(Label::Quantified) {
return;
}
for leg in &declaring.comparison {
let (word, at) = match &leg.conversion {
Conversion::Default => continue,
Conversion::Infallible(path) => ("into", path),
Conversion::Fallible(convert) => ("try_into", &convert.path),
};
errors.push(syn::Error::new_spanned(
at,
format!(
"`{name}` is a `quantified(…)` collection and `{word} = \"…\"` converts its ELEMENT \
OPERANDS — the narrow kind has none. It carries two slots and neither holds an element: \
`any` holds a whole element FILTER and `count` holds a cardinality, which is the whole \
reason the kind exists (an element with no honest literal form has no operand worth \
publishing). Write `list(…)` or `set(…)` if this element does have one — their seven \
element slots are what a converter is for — or drop the word and let the element's own \
filter carry its crossing.",
),
));
}
}
fn graphql_model(
record: &syn::Ident,
node: NodeKind,
block: Option<GraphqlBlock>,
persist: Option<&Persist>,
marked: &[(&syn::Field, Markers)],
errors: &mut Errors,
) -> Option<Graphql> {
let Some(block) = block else {
no_family_block(
record,
"graphql",
"it has no wire face",
"puts a field on a type",
"the backends that render it",
marked
.iter()
.filter_map(|(_, markers)| markers.graphql.as_ref().map(|declared| &declared.at)),
errors,
);
return None;
};
if block.backends.is_empty() {
errors.push(syn::Error::new_spanned(
&block.at,
"`graphql(…)` names the backends that render the record, and it names none — write \
`async_graphql` inside it; a record with no wire face is spelled by omitting the block",
));
return None;
}
let declared: Vec<GraphqlKind> = block.backends.iter().map(|backend| backend.kind).collect();
let unrefined: Vec<WireField> = marked
.iter()
.map(|(field, _)| WireField::unrefined(field.ident.as_ref().expect("a named field")))
.collect();
let mut exposed: Vec<(&syn::Field, &WireField)> = Vec::new();
let mut skipped: Vec<syn::Ident> = Vec::new();
let mut per_backend_skipped: Vec<(GraphqlKind, syn::Ident)> = Vec::new();
for ((field, markers), silent) in marked.iter().zip(&unrefined) {
let name = field.ident.as_ref().expect("a named field");
let declaring = markers.graphql.as_ref().unwrap_or(silent);
if let Some(at) = &declaring.skip {
let others = [
declaring.rename.is_some().then_some("rename"),
declaring.ty.is_some().then_some("type"),
(!declaring.output.is_empty()).then_some("output"),
(!declaring.comparison.is_empty()).then_some("input"),
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
if !others.is_empty() {
errors.push(syn::Error::new_spanned(
at,
format!(
"`skip` withholds `{name}` from every wire vocabulary, and {list} declares what it \
looks like on one — a field the schema never names has no name, no form and no \
crossing to declare. Drop the word, or drop what it makes unreachable.",
list = shipped(others.iter().copied()),
),
));
}
for per in &declaring.per_backend {
if let Some(at) = &per.skip {
errors.push(syn::Error::new_spanned(
at,
format!(
"`skip` already withholds `{name}` from EVERY backend — `{backend}(skip)` beside it \
says the same thing about one of them. One absence, said once.",
backend = per.kind.as_str(),
),
));
}
}
skipped.push(name.clone());
continue;
}
for per in &declaring.per_backend {
if let Some(at) = &per.skip {
if declared.contains(&per.kind) {
per_backend_skipped.push((per.kind, name.clone()));
} else {
let _ = at;
}
}
}
if node.holds_rows() && !stored_in(persist, name) {
let at = markers.skip.as_ref().map_or(&declaring.at, |skip| &skip.at);
errors.push(syn::Error::new_spanned(
at,
format!(
"`{name}` wears `skip`, so it is a column in no database, and the wire face publishes \
every column — a wire field with no stored source has nothing to answer a read with, so \
the pair is REFUSED BY NAME rather than silently answering `null`. Withhold it from the \
wire too (`graphql(skip)`), or drop `skip` and store it. This is the one shape a \
resolver-computed field would revive: the day a declaration can name a function that \
COMPUTES a published field, stored-nowhere-yet-published becomes a real declaration and \
this refusal is what to lift."
),
));
continue;
}
for per in &declaring.per_backend {
if !declared.contains(&per.kind) {
errors.push(syn::Error::new_spanned(
&per.at,
format!(
"`{backend}` is not one of the backends `{record}` declares — its `graphql(…)` names \
{list}",
backend = per.kind.as_str(),
list = block
.backends
.iter()
.map(|backend| format!("`{}`", backend.kind.as_str()))
.collect::<Vec<_>>()
.join(", "),
),
));
}
}
refuse_a_converter_a_quantified_column_cannot_carry(markers, declaring, name, errors);
exposed.push((field, declaring));
}
let base = block.rename.clone().unwrap_or_else(|| record.clone());
let wire = |renamed: Option<syn::Ident>, default: syn::Ident| {
RustSafeName::from_ident(&renamed.unwrap_or(default))
};
let input = wire(None, default_input_name(&base));
let output = wire(block.output.clone(), default_output_name(&base));
let key_output = wire(block.key.clone(), default_key_output_name(&base));
let filter = wire(block.filter.clone(), default_filter_name(&base));
let mut sdl_name = |renamed: Option<syn::LitStr>| -> Option<String> {
let spelled = renamed?;
let word = spelled.value();
wire::refuse_invalid_name(&word, &spelled, errors);
Some(word)
};
let connection = sdl_name(block.connection.clone());
let edge = sdl_name(block.edge.clone());
let key_object = sdl_name(block.key_object.clone());
let key_argument = sdl_name(block.key_argument.clone());
let backends = block
.backends
.iter()
.map(|backend| {
let fields = exposed
.iter()
.filter(|(field, _)| {
let source = field.ident.as_ref().expect("a named field");
!per_backend_skipped
.iter()
.any(|(kind, skipped)| *kind == backend.kind && skipped == source)
})
.map(|(field, declaring)| {
let source = field.ident.clone().expect("a named field");
let per = declaring
.per_backend
.iter()
.find(|per| per.kind == backend.kind);
let common = declaring.rename.as_ref();
let face = |block: Option<&FaceBlock>| Face {
name: block
.and_then(|block| block.rename.as_ref())
.or(common)
.map_or_else(
|| RustSafeName::from_ident(&source),
|lit| RustSafeName::new(lit.value(), lit.span()),
),
attrs: block
.and_then(|block| block.attrs.clone())
.unwrap_or_default(),
};
let position = |legs: &[WireLeg]| WirePosition {
legs: legs.to_vec(),
};
let output = per.and_then(|per| per.output.as_ref());
GraphqlField {
input: face(per.and_then(|per| per.input.as_ref())),
output: face(output),
output_field: output.and_then(|block| block.rust.clone()),
wire: declaring.ty.clone(),
output_crossing: position(&declaring.output),
input_crossing: position(&declaring.comparison),
domain: field.ty.clone(),
source,
}
})
.collect();
let rendering = AsyncGraphql {
attrs: backend.attrs.clone().unwrap_or_default(),
fields,
skipped: per_backend_skipped
.iter()
.filter(|(kind, _)| *kind == backend.kind)
.map(|(_, source)| source.clone())
.collect(),
};
match backend.kind {
GraphqlKind::AsyncGraphql => GraphqlBackend::AsyncGraphql(rendering),
}
})
.collect::<Vec<GraphqlBackend>>();
let mut refused: Vec<(&syn::Ident, &str)> = Vec::new();
for field in backends.iter().flat_map(GraphqlBackend::fields) {
for face in [&field.output, &field.input] {
let name = face.name.external();
if refused
.iter()
.any(|(source, seen)| *source == &field.source && *seen == name)
{
continue;
}
refused.push((&field.source, name));
wire::refuse_invalid_name(name, face.name.safe(), errors);
}
}
for backend in &backends {
let mut taken: Vec<&GraphqlField> = Vec::new();
for field in backend.fields() {
let name = &field.input.name;
if let Some(first) = taken
.iter()
.find(|first| first.input.name.external() == name.external())
{
errors.push(collision(
backend,
"input",
name.safe(),
first,
field,
&format!("one field called `{name}`"),
));
}
taken.push(field);
}
let mut taken: Vec<&GraphqlField> = Vec::new();
for field in backend.fields() {
let name = &field.output.name;
if let Some(first) = taken
.iter()
.find(|first| first.output.name.external() == name.external())
{
errors.push(collision(
backend,
"output",
name.safe(),
first,
field,
&format!("one field called `{name}`"),
));
}
taken.push(field);
}
let mut taken: Vec<&GraphqlField> = Vec::new();
for field in backend.fields() {
let named = field.accessor();
if let Some(first) = taken.iter().find(|first| first.accessor() == named) {
errors.push(syn::Error::new_spanned(
named,
format!(
"the output object would read `{first}` and `{second}` through one accessor, \
`{named}_ref` — a `field = \"…\"` names what the object CALLS a field in Rust, and two \
of them cannot name one method. The MEMBERS behind them are the domain names and do \
not collide; the schema names are a third axis again.",
first = first.source,
second = field.source,
),
));
}
taken.push(field);
}
}
Some(Graphql {
backends,
input,
output,
key_output,
key_object,
key_argument,
filter,
plural: block.plural.as_ref().map(syn::LitStr::value),
connection,
edge,
skipped,
})
}
fn collision(
backend: &GraphqlBackend,
position: &str,
at: &syn::Ident,
first: &GraphqlField,
second: &GraphqlField,
why: &str,
) -> syn::Error {
syn::Error::new_spanned(
at,
format!(
"the `{backend}` face would expose `{first}` and `{second}` in its {position} as {why}. \
Within one schema type every field needs its own name.",
backend = backend.kind().as_str(),
first = first.source,
second = second.source,
),
)
}
fn order_by_name(record: &syn::Ident, block: Option<&GraphqlBlock>) -> RustSafeName {
let base = block
.and_then(|block| block.rename.clone())
.unwrap_or_else(|| record.clone());
let named = block
.and_then(|block| block.order_by.clone())
.unwrap_or_else(|| default_order_by_name(&base));
RustSafeName::from_ident(&named)
}
fn emitted_names(model: &RecordModel, errors: &mut Errors) {
let named = |declared: Declared| (declared.name, declared.role.to_string());
let mut declared = model.emitted_types().into_iter();
let key = declared.next().expect("an emission declares a key type");
let mut emitted: Vec<(syn::Ident, String)> = vec![
named(key),
(model.record.clone(), "the record's own name".to_owned()),
];
emitted.extend(declared.map(named));
let mut taken: Vec<&(syn::Ident, String)> = Vec::new();
for candidate in &emitted {
if let Some(first) = taken.iter().find(|(name, _)| *name == candidate.0) {
errors.push(syn::Error::new(
candidate.0.span(),
format!(
"{second} would be named `{name}`, which is already {first} — one declaration emits each \
of its types into the same scope, so every one needs its own name",
second = candidate.1,
name = candidate.0,
first = first.1,
),
));
}
taken.push(candidate);
}
}
fn emitted_methods(model: &RecordModel, errors: &mut Errors) {
let emitted = model.emitted_methods();
let mut taken: Vec<&Emitted> = Vec::new();
for candidate in &emitted {
if let Some(first) = taken.iter().find(|earlier| {
earlier.owner == candidate.owner
&& earlier.name == candidate.name
&& earlier.origin != candidate.origin
}) {
let why = format!(
"`{owner}` would declare `{name}` twice — {first}, and {second} — and rustc reports that \
duplicate inside the expansion, where nothing names the column that caused it. Rename \
the column.",
owner = candidate.owner_name,
name = candidate.name,
first = first.origin,
second = candidate.origin,
);
errors.push(
match candidate.origin.column().or_else(|| first.origin.column()) {
Some(at) => syn::Error::new_spanned(at, why),
None => syn::Error::new_spanned(&candidate.owner_name, why),
},
);
}
taken.push(candidate);
}
}
fn derived_plural(model: &RecordModel, errors: &mut Errors) {
let Some(field) = model.degenerate_plural() else {
return;
};
errors.push(syn::Error::new(
model.record.span(),
format!(
"`{record}`'s page would be published as `{field}`, which is what its single field is already \
called: the plural derived from the published name is the word itself. Write the plural — \
`graphql(plural = \"…\")` — which declares this entity's PLURAL rather than this field's \
name, so every later reader of it inherits the correction. Nothing downstream refuses this: \
two root fields of one name build a schema whose SDL carries one of them and whose resolver \
answers from the other.",
record = model.record,
),
));
}
fn literal_name(literal: &syn::LitStr) -> RustSafeName {
RustSafeName::new(literal.value(), literal.span())
}
fn list(declared: &[DatabaseKind]) -> String {
declared
.iter()
.map(|kind| format!("`{}`", kind.as_str()))
.collect::<Vec<_>>()
.join(", ")
}
fn concrete(generics: &syn::Generics, kind: NodeKind, errors: &mut Errors) {
let why = format!(
"generic {plural} are not supported — {article} {noun} must be concrete, because a key \
column's type is read straight off the declaration",
plural = kind.plural(),
article = kind.article(),
noun = kind.noun(),
);
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, kind: NodeKind) -> 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,
format!(
"{article} {noun} must be a struct with named fields — `#[ingraph(id)]` and \
`lineage(fields(…))` both name fields",
article = kind.article(),
noun = kind.noun(),
),
)),
},
syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
&input.ident,
format!(
"`#[ingraph::{macro_name}]` supports structs only",
macro_name = kind.as_str()
),
)),
}
}
pub(crate) struct StandaloneField {
pub(crate) marker: Option<Marker>,
pub(crate) wire: Option<syn::Type>,
pub(crate) rename: Option<syn::LitStr>,
pub(crate) per_db: Vec<StandaloneDatabaseField>,
pub(crate) beyond: Vec<(&'static str, syn::Path)>,
pub(crate) conversions: Vec<(&'static str, syn::Path)>,
}
pub(crate) struct StandaloneDatabaseField {
pub(crate) kind: DatabaseKind,
pub(crate) at: syn::Path,
pub(crate) stored: Option<syn::Type>,
pub(crate) flatten: bool,
}
pub(crate) fn standalone_field(attrs: &[syn::Attribute], errors: &mut Errors) -> StandaloneField {
let markers = field_markers(attrs, NodeKind::Record, errors);
let Markers {
id,
copy,
repeated,
optional,
key,
lineage,
storage,
graphql,
label,
reference,
build,
..
} = markers;
let mut beyond = Vec::new();
let mut carry = |word: &'static str, at: Option<syn::Path>| {
if let Some(at) = at {
beyond.push((word, at));
}
};
carry("id", id);
carry("copy", copy);
carry("repeated", repeated);
carry("optional", optional);
carry("key", key.map(|rename| rename.at));
carry("lineage", lineage.map(|rename| rename.at));
carry("ref", reference);
carry(SORTABLE, storage.sortable.clone());
carry(INDEXED, storage.indexed.clone());
carry(crate::construct::WORD, build.and_then(|written| written.at));
let mut conversions = Vec::new();
let mut per_db = Vec::new();
let rename = storage.rename.clone();
{
for database in storage.per_db {
let FieldDatabase {
kind,
at,
indexed,
unique,
copy,
edge,
flatten,
stored,
from,
into,
..
} = database;
carry("indexed", indexed);
carry("unique", unique);
carry("copy", copy);
carry("edge", edge);
for (word, spec) in [("from", &from), ("into", &into)] {
if let Some(named) = spec.infallible.as_ref() {
conversions.push((word, named.at.clone()));
}
if let Some(named) = spec.fallible.as_ref() {
conversions.push((
if word == "from" {
"try_from"
} else {
"try_into"
},
named.at.clone(),
));
}
}
per_db.push(StandaloneDatabaseField {
kind,
at,
stored,
flatten: flatten.is_some() || storage.flatten.is_some(),
});
}
}
let wire = graphql.as_ref().and_then(|field| field.ty.clone());
if let Some(graphql) = graphql {
if !graphql.output.is_empty() {
conversions.push(("graphql(output(…))", graphql.at.clone()));
}
if !graphql.comparison.is_empty() {
conversions.push(("graphql(input(comparison(…)))", graphql.at.clone()));
}
}
StandaloneField {
marker: label.as_ref().map(Written::marker),
wire,
rename,
per_db,
beyond,
conversions,
}
}
#[cfg(test)]
mod channel_tests;
#[cfg(test)]
mod key_faces_tests;
#[cfg(test)]
mod light_tests;
#[cfg(test)]
mod lineage_source_tests;
#[cfg(test)]
mod options_tests;
#[cfg(test)]
mod output_field_tests;
#[cfg(test)]
mod receipt_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tracing_tests;