use ingraph_codegen::{
construct::{Build, Construction},
delegate::Delegate,
fields::{BuiltFor, Derived, FieldsModel, FragmentField, RecordHost, WireFace},
name::RustSafeName,
prelude::*,
};
use crate::{
alias,
attribute::{self, set_once},
column,
errors::Errors,
parse::{FieldDatabase, SkipField},
value,
};
#[cfg(test)]
mod tests;
const STORED_NOWHERE: &str = "a field fragment is stored in no table of its own — its columns are \
the HOLDER's row, which is what the holder's own store words name. A \
dialect at THIS head is a different claim and has a seat of its own: \
`record(sqlite)` names a dialect this fragment is BUILT for, without \
claiming a table in it";
const A_FRAGMENT_IS_HELD: &str = "A field fragment is HELD by whatever declares it, so its \
identity, its storage and its place on the wire are all its \
holder's. A group of fields that bears an identity of its own is \
an `entity`, and one that holds rows besides is a `record`.";
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
) -> syn::Result<FieldsModel> {
let fragment = &input.ident;
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let Declared {
krate,
remote,
record,
entity,
wire,
construction,
cursor,
filter,
delegates,
} = options(arguments, &mut errors);
refuse_a_fragment_no_kind_can_hold(fragment, record.as_ref(), entity.as_ref(), &mut errors);
let activated = Activated {
record: record.as_ref(),
wire: wire.is_some(),
};
refuse_a_position_no_kind_stores(record.as_ref(), cursor.as_ref(), &mut errors);
concrete(&input.generics, &mut errors);
if remote.is_some() {
crate::remote::refuse_a_representation(&input.attrs, &mut errors);
}
let fields = match named_fields(input) {
Ok(fields) => fields,
Err(terminal) => return Err(errors.seal(terminal)),
};
if fields.named.is_empty() {
errors.push(syn::Error::new_spanned(
fragment,
"a field fragment with no fields extracts nothing — the tier exists to declare the fields \
several types hold, so a declaration with none has nothing for a holder to inherit",
));
}
let fence = alias::Fence::default();
let columns: Vec<FragmentField> = fields
.named
.iter()
.filter_map(|field| {
let name = field.ident.clone()?;
column::refuse_framework_namespace(&fence, &name, &mut errors);
if remote.is_some() {
crate::remote::refuse_an_unplaceable_attribute(field, &mut errors);
}
let mut written = Marked::default();
let project = markers(&field.attrs, &name, &activated, &mut written, &mut errors);
let Marked {
build,
stored,
wire_name,
} = written;
refuse_a_dialect_the_layout_cannot_carry(&name, record.as_ref(), &stored, &mut errors);
refuse_a_skipped_position(&name, cursor.as_ref(), &stored, &mut errors);
refuse_a_column_derived_off_a_field_that_has_none(&name, &stored, &mut errors);
refuse_a_transform_with_nothing_to_transform(&name, &stored, &mut errors);
crate::construct::refuse_a_whole_non_option(
matches!(project, Projection::Optional),
build.as_ref(),
&mut errors,
);
refuse_a_cycle(fragment, &name, &field.ty, &mut errors);
if cursor.is_some() {
attribute::refuse_a_conditional_position(field, &mut errors);
}
Some(FragmentField {
flatten: stored.flatten.is_some(),
stored_name: stored.rename.as_ref().map(syn::LitStr::value),
skip: stored.skip.as_ref().map(SkipField::fill),
derived: stored
.derived
.iter()
.map(|one| Derived {
column: RustSafeName::new(one.column.value(), one.column.span()),
from: one.from.clone(),
ty: one.ty.clone(),
})
.collect(),
write: stored.write.as_ref().map(|one| one.path.clone()),
read: stored.read.as_ref().map(|one| one.path.clone()),
column: Column {
project,
ty: field.ty.clone(),
source: name.clone(),
name,
},
docs: crate::remote::docs(field),
condition: attribute::condition(field, remote.is_some(), &mut errors),
wire_name: wire_name.map(|spelled: syn::LitStr| spelled.value()),
build: build.unwrap_or_default(),
})
})
.collect();
refuse_a_derived_name_a_column_already_has(&columns, &mut errors);
crate::construct::refuse_without_a_remote(
remote.as_ref(),
construction
.as_ref()
.and_then(|written| written.at.as_ref()),
columns.iter().filter_map(|field| field.build.at.clone()),
"field fragment",
&mut errors,
);
let construction = construction.unwrap_or_default();
let described: Vec<(syn::Ident, Build)> = columns
.iter()
.map(|field| (field.column.source.clone(), field.build.clone()))
.collect();
crate::construct::refuse_a_homeless_argument(&construction, &described, &mut errors);
refuse_an_own_entry_that_publishes_nothing(remote.as_ref(), &delegates, &mut errors);
refuse_a_word_that_suppresses_nothing(remote.as_ref(), &delegates, &mut errors);
refuse_a_lifted_entry_without_a_face(&delegates, wire.is_some(), &mut errors);
refuse_a_codec_with_no_position(record.as_ref(), cursor.as_ref(), &mut errors);
let cursor = cursor.map(|written| key(&written, &columns, &mut errors));
let model = FieldsModel {
fragment: fragment.clone(),
vis: input.vis.clone(),
krate,
remote,
record: record.map(|written| RecordHost {
databases: written
.databases
.into_iter()
.map(|one| BuiltFor {
kind: one.kind,
comparison: one.mounted.comparison,
cursor: one.mounted.cursor.map(|codec| codec.path),
})
.collect(),
write: written.write.map(|one| one.path),
read: written.read.map(|one| one.path),
}),
entity: entity.is_some(),
wire,
fields: columns,
construction,
cursor,
filter,
delegates,
};
emitted_methods(&model, &mut errors);
refuse_a_published_collision(&model, &mut errors);
refuse_an_absent_position(&model, &mut errors);
refuse_a_fallible_position(&model, &mut errors);
errors.into_result(model)
}
fn refuse_a_fragment_no_kind_can_hold(
fragment: &syn::Ident,
record: Option<&RecordActivation>,
entity: Option<&syn::Path>,
errors: &mut Errors,
) {
if record.is_some() || entity.is_some() {
return;
}
errors.push(syn::Error::new_spanned(
fragment,
format!(
"`{fragment}` activates no host kind, so no declaration can consume it — a fragment is HELD, \
and WHICH faces it answers with is decided by the kind that holds it. Write \
`record[(<db>, …)]` to be held by the rung that stores rows, which is what the width, the \
bind, the read and the comparison are for; write `entity` to be held by the rung that bears \
an identity and no rows, which asks for the predicate alone. Write BOTH where both hold it — \
there is no one word for the pair. The accessor family is the tier's own and is emitted \
either way."
),
));
}
fn refuse_a_position_no_kind_stores(
record: Option<&RecordActivation>,
cursor: Option<&Cursor>,
errors: &mut Errors,
) {
let (None, Some(written)) = (record, cursor) else {
return;
};
errors.push(syn::Error::new_spanned(
&written.at,
"`cursor` asserts a total order for PAGING, and paging is the record host's: the keyset writes \
this value's members as cursor bytes and a statement resumes strictly after them, both of which \
need rows to walk. This fragment activates no `record`, so the assertion has no reader — add \
`record[(<db>, …)]` beside the word, or drop the word: a fragment without one is filtered and \
read back exactly as before, and is simply not a paging position",
));
}
fn refuse_a_codec_with_no_position(
record: Option<&RecordActivation>,
cursor: Option<&Cursor>,
errors: &mut Errors,
) {
let (Some(host), None) = (record, cursor) else {
return;
};
for (db, at) in host.databases.iter().filter_map(|one| {
one
.mounted
.cursor
.as_ref()
.map(|codec| (one.kind.as_str(), &codec.at))
}) {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{db}(cursor = \"…\")` mounts the codec this fragment's PAGING BOUNDARY is written by at \
`{db}`, and this fragment is no paging position — the rows a codec is spent at are the \
cursor rows, and only the bare `cursor` word at the head emits any. So the mount has no \
reader. Write `cursor` beside `record(…)` to assert that the order you declared these \
fields in is the one legitimate total order over this value, or drop the mount: a fragment \
without either is stored, filtered and read back exactly as before"
),
));
}
}
fn refuse_an_own_entry_that_publishes_nothing(
remote: Option<&syn::Path>,
delegates: &[Delegate],
errors: &mut Errors,
) {
const OFFER: &str = "Write `#[graphql(<backend>)]` on the entry to publish it, or drop the entry: \
the method is reached exactly as before either way";
for delegate in delegates
.iter()
.filter(|entry| entry.wire.is_empty() && !mints_a_forwarding_half(remote, entry))
{
let method = &delegate.signature.ident;
let why = if remote.is_some() {
format!(
"`{method}` publishes nothing and `on = self` waives its forwarding half, so the entry has \
no reader. Without the word a plain entry earns its keep here — it mints the inherent \
method a `Deref` would otherwise be needed for — and with it the method is already yours, \
on your own `impl`, leaving the seat's whole content the wire field. {OFFER}"
)
} else {
format!(
"`{method}` publishes nothing and this fragment wraps nothing, so the entry has no reader. \
On a declaration that WRAPS a type a plain entry earns its keep — it mints the inherent \
forwarding method a `Deref` would otherwise be needed for. Here the method is already \
yours, on your own `impl`, and the seat's whole content is putting it on the wire beside \
the columns. {OFFER}"
)
};
errors.push(syn::Error::new_spanned(method, why));
}
}
fn mints_a_forwarding_half(remote: Option<&syn::Path>, delegate: &Delegate) -> bool {
remote.is_some() && delegate.on_self.is_none()
}
fn refuse_a_word_that_suppresses_nothing(
remote: Option<&syn::Path>,
delegates: &[Delegate],
errors: &mut Errors,
) {
if remote.is_some() {
return;
}
for (delegate, at) in delegates
.iter()
.filter_map(|entry| entry.on_self.as_ref().map(|at| (entry, at)))
{
errors.push(syn::Error::new_spanned(
at,
format!(
"`on = self` suppresses the FORWARDING method a wrapping declaration mints for `{method}`, \
and this fragment wraps nothing — so there is no mint here for the word to suppress and \
the expansion is the same with it and without. The method is the author's own already, \
which is what an ordinary fragment's entry means: drop the property, and write the entry \
in the shorthand the tier had before the word existed. `remote = \"…\"` at the head is \
what gives this word something to say",
method = delegate.signature.ident,
),
));
}
}
fn refuse_a_lifted_entry_without_a_face(
delegates: &[Delegate],
published: bool,
errors: &mut Errors,
) {
if published {
return;
}
for delegate in delegates.iter().filter(|entry| !entry.wire.is_empty()) {
errors.push(syn::Error::new_spanned(
&delegate.signature.ident,
format!(
"`{method}` is published onto a wire face this fragment does not have — the tier publishes \
nothing unless the declaration asks, so `#[graphql(…)]` here is a field of no object. \
Write `graphql[(…)]` at the head to give this fragment a face, or drop the attribute: the \
entry is still forwarded onto the wrapped value either way",
method = delegate.signature.ident,
),
));
}
}
fn refuse_a_fallible_position(model: &FieldsModel, errors: &mut Errors) {
if model.cursor.is_none() || !model.construction.fallible {
return;
}
let declared = model
.record
.as_ref()
.map_or(&[][..], |host| host.databases.as_slice());
let unmounted: Vec<&str> = declared
.iter()
.filter(|built| built.cursor.is_none())
.map(|built| built.kind.as_str())
.collect();
if !declared.is_empty() && unmounted.is_empty() {
return;
}
let at = model
.construction
.at
.as_ref()
.expect("a parsed protocol keeps its word");
let framed = if unmounted.is_empty() {
"This declaration names no dialect to mount one at, so the framed read is the only one it has"
.to_owned()
} else {
format!(
"No codec is mounted at `{}`, so the framed read — the one that raises — is what this \
fragment still writes there",
unmounted.join("`, `"),
)
};
errors.push(syn::Error::new_spanned(
at,
format!(
"`fallible` says the wrapped type's construction hands back a `Result`, and `cursor` says \
this fragment is a paging position — a cursor's read answers `Some` or `None`, and there is \
nowhere in that answer for an `Err`. Swallowing it would report a FORGED frame and a value \
the remote rejected as one thing, which are the two states a cursor codec exists to tell \
apart. Drop the `cursor` word, give the protocol an infallible terminal step, or mount a \
codec at every dialect this fragment declares — a mounted read is the codec's own `Option` \
from the bytes up and never raises through the protocol at all. {framed}"
),
));
}
struct Declared {
krate: syn::Path,
remote: Option<syn::Path>,
record: Option<RecordActivation>,
entity: Option<syn::Path>,
wire: Option<WireFace>,
construction: Option<Construction>,
cursor: Option<Cursor>,
filter: Option<syn::Path>,
delegates: Vec<Delegate>,
}
struct RecordActivation {
databases: Vec<WrittenDialect>,
write: Option<Transform>,
read: Option<Transform>,
}
struct WrittenDialect {
kind: DatabaseKind,
mounted: Mounted,
}
#[derive(Default)]
struct Mounted {
comparison: Option<syn::Path>,
cursor: Option<Codec>,
}
struct Codec {
at: syn::Path,
path: syn::Path,
}
struct Cursor {
at: syn::Path,
named: Vec<syn::Ident>,
}
fn key(written: &Cursor, columns: &[FragmentField], errors: &mut Errors) -> Vec<syn::Ident> {
const WHY: &str = "A cursor's slot is the boundary row's WHOLE value and the SQL keyset compares \
its columns in the order they are DECLARED — so a key that names a different \
order, or fewer than all of them, is one the engine never pages by. Write the \
fields in the order you want them keyed, or take the bare `cursor`, which is \
this same key without the pin";
if written.named.is_empty() {
return Vec::new();
}
let declared: Vec<&syn::Ident> = columns.iter().map(|field| &field.column.name).collect();
if written.named.len() != declared.len()
|| !written
.named
.iter()
.zip(&declared)
.all(|(named, column)| &named == column)
{
let spelled: Vec<String> = declared.iter().map(ToString::to_string).collect();
errors.push(syn::Error::new_spanned(
&written.at,
format!(
"`cursor(…)` PINS this fragment's key, and a pin states the declared order in full — this \
one does not. Written out, the key is `cursor({})`. {WHY}",
spelled.join(", ")
),
));
}
written.named.clone()
}
fn refuse_an_absent_position(model: &FieldsModel, errors: &mut Errors) {
let Some(key) = model.cursor.as_ref() else {
return;
};
for field in &model.fields {
let name = &field.column.name;
if !matches!(field.column.project, Projection::Optional) {
continue;
}
if !key.is_empty() && !key.contains(name) {
continue;
}
errors.push(syn::Error::new_spanned(
name,
format!(
"`{name}` is `optional`, so it cannot be part of this fragment's cursor key — a page \
resumes STRICTLY AFTER a boundary, and an absent value has no place in the run it would \
resume. Drop the field from the key, or drop the `cursor` word: a fragment without one is \
stored, filtered and read back exactly as before, and is simply not a paging position"
),
));
}
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Declared {
const CLAIMED: [(&str, &str); 13] = [
(
"implements",
"an interface's members are NODES WITH ROWS — a membership is proved by a stored row \
answering the contract's columns, and a fragment has no row of its own to answer with. \
Whether the fragment tier can be a member at all is tracked at \
https://github.com/findit-studio/ingraph/issues/168, with the inheritance round",
),
(
"subscribe",
"a field fragment subscribes to nothing — an edge drives a NODE, and a fragment is carried \
by whatever declares it rather than driven by anything",
),
(
"key",
"a field fragment has no key — bearing no identity is what this tier means, and the identity \
a question about one ever needs is the holder's",
),
(
"lineage",
"a field fragment has no lineage — a path to the root is a path between NODES, and a \
fragment is not one of them",
),
("sqlite", STORED_NOWHERE),
("postgres", STORED_NOWHERE),
("mysql", STORED_NOWHERE),
("mongo", STORED_NOWHERE),
("table", STORED_NOWHERE),
(
"persist",
"a field fragment is stored in no table of its own — and `persist(…)` is gone besides: a \
record names its stores BARE at its head, and a fragment names the dialects it is built for \
inside `record(…)`, which is that same head one namespace in",
),
(
"fulltext",
"a field fragment owns no full-text index — an index is a node with a storage, and this tier \
has neither",
),
(
"vector",
"a field fragment owns no embedding index — an index is a node with a storage, and this tier \
has neither",
),
(
"blob",
"a field fragment owns no artifact store — an artifact family is a node with a storage, and \
this tier has neither",
),
];
let mut krate = None;
let mut remote = None;
let mut construction = None;
let mut cursor: Option<Cursor> = None;
let mut record: Option<RecordActivation> = None;
let mut entity: Option<syn::Path> = None;
let mut wire: Option<WireFace> = None;
let mut filter = None;
let mut delegates = Vec::new();
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("remote") {
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(RECORD) {
let written = record_activation(&meta, errors).unwrap_or_else(|refusal| {
errors.push(refusal);
RecordActivation {
databases: Vec::new(),
write: None,
read: None,
}
});
set_once(
&mut record,
written,
&meta.path,
"`record` is declared more than once — one declaration names one host kind once",
errors,
);
return Ok(());
}
if meta.path.is_ident(ENTITY) {
if let Err(refusal) = entity_activation(&meta) {
errors.push(refusal);
}
set_once(
&mut entity,
meta.path.clone(),
&meta.path,
"`entity` is declared more than once — one declaration names one host kind once",
errors,
);
return Ok(());
}
if meta.path.is_ident(GRAPHQL) {
let written = wire_activation(&meta, errors).unwrap_or_else(|refusal| {
errors.push(refusal);
WireFace {
object: None,
filter: None,
}
});
set_once(
&mut wire,
written,
&meta.path,
"`graphql` is declared more than once — one declaration has one wire face",
errors,
);
return Ok(());
}
if meta.path.is_ident(crate::delegate::WORD) {
return crate::delegate::block(&meta, &mut delegates, &FRAGMENT, errors);
}
if meta.path.is_ident(FILTER) {
match value::parse_literal::<syn::Path>(
&meta,
"`filter = \"…\"` names the predicate this fragment mounts in place of the generated one, \
as a type path in a string literal",
) {
Ok(path) => set_once(
&mut filter,
path,
&meta.path,
"`filter` is declared more than once — one fragment is compared by one predicate",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident(CURSOR) {
match cursor_word(&meta) {
Ok(written) => set_once(
&mut cursor,
written,
&meta.path,
"`cursor` is declared more than once — one fragment is a position in one order",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
for (family, why) in CLAIMED {
if meta.path.is_ident(family) {
errors.push(syn::Error::new_spanned(
&meta.path,
format!("{why}. {A_FRAGMENT_IS_HELD}"),
));
attribute::skip_entry(&meta);
return Ok(());
}
}
errors.push(attribute::unknown(
&meta,
"unknown entry on a field fragment — it takes its HOST-KIND activations \
(`record[(<db>, …)]`, `entity`), `crate = \"…\"`, `remote = \"…\"`, `builder(…)`, \
`cursor[(…)]`, `filter = \"…\"` and `delegate(fn …)`, every other block naming something a \
fragment does not have",
&[
RECORD,
ENTITY,
"crate",
"remote",
crate::construct::WORD,
CURSOR,
FILTER,
crate::delegate::WORD,
],
));
Ok(())
});
Declared {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
remote,
record,
entity,
wire,
construction,
cursor,
filter,
delegates,
}
}
const FRAGMENT: crate::delegate::Delegation<'static> = crate::delegate::Delegation {
receiver: "a delegated method BORROWS its receiver — `&self` reaches the method on `Self`, and \
`&mut self` mutates the value in place. There is no `self` for one to consume, the \
value being the caller's rather than this seat's, and a signature with no receiver has \
nothing to reach a method FROM",
exclusive: "a published delegate takes `&self` — a resolver READS, and an exclusive receiver's \
body mutates the value it was called on. Drop the `#[graphql(…)]` to keep the method, \
or take the receiver by shared reference to keep the field",
};
const FILTER: &str = "filter";
const GRAPHQL: &str = "graphql";
fn wire_activation(
meta: &syn::meta::ParseNestedMeta<'_>,
errors: &mut Errors,
) -> syn::Result<WireFace> {
const SHAPE: &str = "`graphql` is written bare — the fragment publishes its own name — or as \
`graphql(rename = \"…\", filter(rename = \"…\"))`, which names the OBJECT and \
the BASE the FILTER's input objects compose off";
if attribute::has_value(meta) {
return Err(attribute::named(meta, SHAPE.to_owned()));
}
let mut object: Option<syn::LitStr> = None;
let mut filter: Option<syn::LitStr> = None;
attribute::options(meta, |inner| {
if inner.path.is_ident("rename") {
match value::literal(&inner, OBJECT_NAME) {
Ok(spelled) => set_once(
&mut object,
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("filter") {
return attribute::sdl_name_block(&inner, &mut filter, "filter", errors);
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `graphql(…)` on a fragment — it names the two TYPES this face mints \
(`rename = \"…\"` for the object, `filter(rename = \"…\")` for the base its input objects \
compose off). What a \
CLIENT calls one field is that field's own `graphql(rename = \"…\")`, and the queryable-root \
words (`plural`, `connection`, `edge`, `key`, `order_by`) belong to a declaration that IS a \
root — a fragment shows on the wire as a fragment of whatever holds it",
&["rename", "filter"],
));
Ok(())
})?;
for spelled in [object.as_ref(), filter.as_ref()].into_iter().flatten() {
crate::wire::refuse_invalid_name(&spelled.value(), spelled, errors);
}
Ok(WireFace {
object: object.map(|spelled| RustSafeName::new(spelled.value(), spelled.span())),
filter: filter.map(|spelled| RustSafeName::new(spelled.value(), spelled.span())),
})
}
const OBJECT_NAME: &str = "a fragment's `graphql(rename = \"…\")` names its OBJECT in the schema, as \
a word in a string literal";
const RECORD: &str = "record";
const ENTITY: &str = "entity";
fn record_activation(
meta: &syn::meta::ParseNestedMeta<'_>,
errors: &mut Errors,
) -> syn::Result<RecordActivation> {
const SHAPE: &str = "`record` is written bare — a record of any dialect may hold this fragment — \
or as `record(sqlite, postgres)`, which names the dialects it is BUILT for. \
A dialect that mounts something of its own writes it in a block — \
`sqlite(comparison = \"…\")` for the lowering, `sqlite(cursor = \"…\")` for \
the cursor codec — and the WHOLE VALUE's way across the storage boundary is \
`record(write = \"…\")` with `record(read = \"…\")` for the mirror";
if attribute::has_value(meta) {
return Err(attribute::named(meta, SHAPE.to_owned()));
}
let mut databases: Vec<WrittenDialect> = Vec::new();
let (mut write, mut read): (Option<Transform>, Option<Transform>) = (None, None);
attribute::options(meta, |inner| {
if let Some(kind) = crate::parse::database_kind(&inner.path) {
let db = kind.as_str();
if attribute::has_value(&inner) {
errors.push(attribute::named(
&inner,
format!(
"`{db}` at a fragment's head names the DIALECT and takes no value — a word in it is \
written in a block, as `{db}(comparison = \"…\")` or `{db}(cursor = \"…\")`"
),
));
return Ok(());
}
if databases.iter().any(|seen| seen.kind == kind) {
errors.push(syn::Error::new_spanned(
&inner.path,
format!("`{db}` is named more than once in `record(…)` — one entry per database"),
));
return Ok(());
}
if !attribute::has_block(&inner) {
attribute::skip_entry(&inner);
databases.push(WrittenDialect {
kind,
mounted: Mounted::default(),
});
return Ok(());
}
let mounted = dialect_block(&inner, kind, errors)?;
databases.push(WrittenDialect { kind, mounted });
return Ok(());
}
if inner.path.is_ident(COMPARISON) {
errors.push(attribute::named(&inner, BARE_COMPARISON.to_owned()));
return Ok(());
}
if inner.path.is_ident(CURSOR) {
errors.push(attribute::named(&inner, BARE_CODEC.to_owned()));
return Ok(());
}
for (word, slot, shape) in [
(WRITE, &mut write, HEAD_WRITE_PATH),
(READ, &mut read, HEAD_READ_PATH),
] {
if !inner.path.is_ident(word) {
continue;
}
match crate::value::parse_literal::<syn::Path>(&inner, shape) {
Ok(path) => set_once(
slot,
Transform {
at: inner.path.clone(),
path,
},
&inner.path,
&format!(
"`{word}` is declared more than once in `record(…)` — one fragment crosses the storage \
boundary by one whole-value path in each direction, and a value with two canonical \
forms has none"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
let known: Vec<&str> = DatabaseKind::ALL
.map(DatabaseKind::as_str)
.into_iter()
.chain([WRITE, READ, CURSOR])
.collect();
errors.push(attribute::unknown(
&inner,
&format!(
"unknown entry in `record(…)` on a fragment — the namespace names DIALECTS ({stores}) and \
the WHOLE VALUE's two paths across the storage boundary, `write = \"…\"` and \
`read = \"…\"`. A fragment is HELD, so the row's own words stay the holder's: `table` and \
`schema` name where a row lives, `rename` names the row type, `key` and `lineage` name an \
address, and none of the four is a thing this tier has",
stores = crate::parse::shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
),
&known,
));
Ok(())
})?;
Ok(RecordActivation {
databases,
write,
read,
})
}
const HEAD_WRITE_PATH: &str = "`write` at a fragment's head names the function the WHOLE VALUE \
passes through on its way to STORAGE, as a path in a string literal — a `fn(&Self) -> Self`. It \
is the seat a canonical form that reads SEVERAL fields needs: reducing a rational divides both \
halves by their common factor, so the numerator's stored value is not a function of the \
numerator and the per-field `record(write = \"…\")` cannot spell it. One function, spent \
wherever this emission carries the value across the boundary — the bind, and the cursor's write \
where the fragment is a paging position";
const HEAD_READ_PATH: &str = "`read` at a fragment's head names the function the WHOLE VALUE passes \
through on its way BACK, as a path in a string literal — a `fn(&Self) -> Self`, spent at the \
raise and at the cursor's read. Writing none is the IDENTITY, which is what a canonicalisation \
wants: a reduced value is a valid domain value and there is nothing to undo";
const COMPARISON: &str = "comparison";
const BARE_COMPARISON: &str = "there is no bare `comparison = \"…\"` — a lowering is mounted PER \
DIALECT, as `record(sqlite(comparison = \"…\"), postgres(comparison = \"…\"))`. A bare seat's \
SCOPE would be implicit: a type generic over the SQL family serves three dialects and not \
MongoDB, and nothing at the declaration would say so. A family-generic type is simply named at \
each dialect it serves — two mentions, zero ambiguity — and each mount is audited against the \
dialect it was written at";
const BARE_CODEC: &str = "there is no bare `cursor = \"…\"` in `record(…)` — a type-naming seat is \
written where the DIALECT is, as `record(sqlite(cursor = \"…\"), postgres(cursor = \"…\"))`, \
which is the register law `comparison` is mounted under one word over. A codec's bytes are that \
STORE's: a page cursor is short-lived pagination state rather than a durable id, so the engine \
that reads a token is the one that minted it, and each dialect may keep a byte form of its own. \
A dialect you name and mount nothing at rides the framed default there. The bare `cursor` at the \
HEAD, outside `record(…)`, is a different word entirely: it asserts this fragment's total order, \
and it is what gives a codec here a reader";
const COMPARISON_PATH: &str = "`comparison` names the type this fragment's predicate LOWERS INTO \
at this dialect, as a path in a string literal. It replaces the per-field product, which is what \
a whole-value operator needs: `overlaps` spans two columns at once and has no field to hang on. \
The type owes that dialect's faces — the crossing from this fragment's filter, the empty \
predicate, and the lowering itself";
const CODEC: &str = "codec";
const CODEC_PATH: &str = "`cursor` names the type that WRITES AND READS this fragment's cursor \
bytes, as a path in a string literal. It replaces the emission's framed default — one \
length-prefixed member per key column — which is what a household with a dense hand-written form \
needs: eight flat bytes are not four members of two, and the emission cannot know a width. The \
type owes ONE face, `ingraph::CursorCodec<Self>`, whose `encode` and `decode` are duals and \
therefore one implementor";
fn dialect_block(
meta: &syn::meta::ParseNestedMeta<'_>,
kind: DatabaseKind,
errors: &mut Errors,
) -> syn::Result<Mounted> {
let db = kind.as_str();
if attribute::empty_group(meta) {
errors.push(attribute::named(
meta,
format!(
"`{db}()` says nothing — write the dialect BARE to name it, \
`{db}(comparison = \"…\")` to mount the lowering this fragment gets there, or \
`{db}(cursor = \"…\")` to mount the codec its paging boundary is written by"
),
));
attribute::skip_entry(meta);
return Ok(Mounted::default());
}
let mut mounted = Mounted::default();
attribute::options(meta, |inner| {
if inner.path.is_ident(COMPARISON) {
match crate::value::parse_literal::<syn::Path>(&inner, COMPARISON_PATH) {
Ok(path) => attribute::set_once(
&mut mounted.comparison,
path,
&inner.path,
&format!("`comparison` is mounted more than once at `{db}` — one dialect, one lowering"),
errors,
),
Err(why) => errors.push(why),
}
return Ok(());
}
if inner.path.is_ident(CURSOR) {
match codec_word(&inner, db, errors) {
Ok(Some(written)) => attribute::set_once(
&mut mounted.cursor,
written,
&inner.path,
&format!("`cursor` is mounted more than once at `{db}` — one dialect, one codec"),
errors,
),
Ok(None) => {}
Err(why) => errors.push(why),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
&format!(
"unknown entry in `{db}(…)` at a fragment's head — the block takes the two TYPE seats, \
`comparison = \"…\"` and `cursor[(codec = \"…\")]`, and nothing else. How ONE database \
renders a COLUMN is that column's to say, on the field that holds it, as \
`#[ingraph(record({db}(…)))]`; what this seat says is what the whole VALUE lowers into \
there, and what its paging boundary is written by"
),
&[COMPARISON, CURSOR],
));
Ok(())
})?;
Ok(mounted)
}
struct CursorEntry {
word: &'static str,
read: fn(&syn::meta::ParseNestedMeta<'_>, &mut CursorBlock, &str, &mut Errors),
}
const CURSOR_ENTRIES: &[CursorEntry] = &[CursorEntry {
word: CODEC,
read: read_codec,
}];
#[derive(Default)]
struct CursorBlock {
codec: Option<syn::Path>,
}
fn read_codec(
inner: &syn::meta::ParseNestedMeta<'_>,
block: &mut CursorBlock,
db: &str,
errors: &mut Errors,
) {
match crate::value::parse_literal::<syn::Path>(inner, CODEC_PATH) {
Ok(path) => attribute::set_once(
&mut block.codec,
path,
&inner.path,
&format!(
"`{CODEC}` is declared more than once in `cursor(…)` at `{db}` — one option, one value"
),
errors,
),
Err(why) => errors.push(why),
}
}
fn cursor_words() -> Vec<&'static str> {
CURSOR_ENTRIES.iter().map(|entry| entry.word).collect()
}
fn cursor_roster() -> String {
format!(
"`cursor(…)` knows {}",
crate::parse::shipped(CURSOR_ENTRIES.iter().map(|entry| entry.word))
)
}
fn codec_word(
meta: &syn::meta::ParseNestedMeta<'_>,
db: &str,
errors: &mut Errors,
) -> syn::Result<Option<Codec>> {
let at = meta.path.clone();
if attribute::has_value(meta) {
let mut block = CursorBlock::default();
read_codec(meta, &mut block, db, errors);
return Ok(block.codec.map(|path| Codec { at, path }));
}
if !attribute::has_block(meta) || attribute::empty_group(meta) {
return Err(attribute::named(
meta,
format!(
"`cursor` says nothing on its own at `{db}` — the seat NAMES a type, in one of two \
spellings: `{db}(cursor = \"…\")`, or `{db}(cursor(codec = \"…\"))`, which is that same \
entry in the block every further word will land in. The bare word at a fragment's HEAD is \
a different seat one level out — `cursor` beside `record(…)` asserts this fragment's total \
order, and it is what makes a codec here have a reader at all"
),
));
}
let mut block = CursorBlock::default();
let mut refusal = None;
meta.parse_nested_meta(|inner| {
if let Some(entry) = CURSOR_ENTRIES
.iter()
.find(|entry| inner.path.is_ident(entry.word))
{
(entry.read)(&inner, &mut block, db, errors);
return Ok(());
}
refusal.get_or_insert_with(|| {
attribute::unknown(
&inner,
&format!(
"unknown entry in `cursor(…)` at `{db}` — {}",
cursor_roster()
),
&cursor_words(),
)
});
Ok(())
})?;
if let Some(why) = refusal {
errors.push(why);
}
Ok(block.codec.map(|path| Codec { at, path }))
}
fn entity_activation(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
if !attribute::has_value(meta) && !attribute::has_block(meta) {
attribute::skip_entry(meta);
return Ok(());
}
Err(attribute::named(
meta,
"entity-hosting has nothing to configure yet — the bare word `entity` activates the read faces, \
and a configuration you need is a ruling away. What will live here is known by name: an \
election's projection over an entity-hosted field, a `fulltext` or `vector` label on one, the \
keys tier's exposure. Each arrives with the consumer that reads it"
.to_owned(),
))
}
const CURSOR: &str = "cursor";
fn cursor_word(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<Cursor> {
const SHAPE: &str = "`cursor` is written bare — every field, in declared order — or as \
`cursor(a, b, c)`, which PINS that same key by spelling it out";
if attribute::has_value(meta) {
return Err(attribute::named(meta, SHAPE.to_owned()));
}
let at = meta.path.clone();
if !attribute::has_block(meta) {
attribute::skip_entry(meta);
return Ok(Cursor {
at,
named: Vec::new(),
});
}
if attribute::empty_group(meta) {
return Err(attribute::named(
meta,
format!("`cursor()` names no member, which is not the empty key — {SHAPE}"),
));
}
let mut named = Vec::new();
let mut refusal = None;
meta.parse_nested_meta(|inner| {
match inner.path.get_ident() {
Some(member) if !attribute::has_value(&inner) && !attribute::has_block(&inner) => {
named.push(member.clone());
}
_ => {
refusal.get_or_insert_with(|| {
attribute::named(
&inner,
format!("a cursor's members are FIELD NAMES, bare and comma-separated — {SHAPE}"),
)
});
attribute::skip_entry(&inner);
}
}
Ok(())
})?;
match refusal {
Some(e) => Err(e),
None => Ok(Cursor { at, named }),
}
}
fn markers(
attrs: &[syn::Attribute],
field: &syn::Ident,
activated: &Activated<'_>,
written: &mut Marked,
errors: &mut Errors,
) -> Projection {
column::projection_markers(attrs, field, errors, |meta, errors| {
if meta.path.is_ident(RECORD) {
return match record_column(meta, field, activated.record, &mut written.stored, errors) {
Ok(()) => column::Claim::Taken,
Err(e) => column::Claim::Refused(e),
};
}
if meta.path.is_ident(GRAPHQL) {
return match wire_column(meta, field, activated.wire, &mut written.wire_name, errors) {
Ok(()) => column::Claim::Taken,
Err(e) => column::Claim::Refused(e),
};
}
if meta.path.is_ident(PERSIST) {
return column::Claim::Refused(attribute::named(
meta,
format!(
"`persist` is retired at a fragment's field — what it held is the RECORD host's, and that \
is the namespace it moved into: write `#[ingraph(record(flatten))]` for the layout word \
this seat used to be the whole of, and `#[ingraph(record(skip))]`, \
`#[ingraph(record({db}(…)))]` for the rest of the storage grammar `{field}` may now \
declare. One idiom, one level count: a record names its stores bare at its head and a \
fragment names them inside `record(…)`.",
db = DatabaseKind::Sqlite.as_str(),
),
));
}
if meta.path.is_ident(crate::construct::WORD) {
return match crate::construct::field(meta, &mut written.build, errors) {
Ok(()) => column::Claim::Taken,
Err(e) => column::Claim::Refused(e),
};
}
if meta.path.is_ident("ref") {
return column::Claim::Refused(syn::Error::new_spanned(
&meta.path,
format!(
"`{field}` cannot reference another node from inside a fragment — a fragment is HELD, so \
a reference out of one belongs to whatever holds it, where the key that would carry it \
lives. Fragment references are wanted and are tracked at \
https://github.com/findit-studio/ingraph/issues/168; today the holder declares the `ref`"
),
));
}
if meta.path.is_ident("id") {
return column::Claim::Refused(syn::Error::new_spanned(
&meta.path,
format!(
"`{field}` cannot be a fragment's id, because a fragment has none — bearing no identity \
is what this tier means, and a group of fields that does bear one is an `entity`. \
{A_FRAGMENT_IS_HELD}"
),
));
}
column::Claim::Refused(syn::Error::new_spanned(
&meta.path,
"a fragment's field takes the projection words — `copy`, `repeated`, `optional` — plus \
`builder(…)`, the HOST-KIND namespace `record(…)` and the wire face's own \
`graphql(rename = \"…\")`, and no other word yet. What a field says to a host kind goes \
inside that kind's own namespace, which is what keeps one ident from meaning two things at \
two seats; the labels and the wire legs are declared ONCE here and inherited by every holder, \
and what reads that inheritance has not arrived",
))
})
}
struct Activated<'a> {
record: Option<&'a RecordActivation>,
wire: bool,
}
#[derive(Default)]
struct Marked {
build: Option<Build>,
stored: RecordColumn,
wire_name: Option<syn::LitStr>,
}
fn wire_column(
meta: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
published: bool,
wire_name: &mut Option<syn::LitStr>,
errors: &mut Errors,
) -> syn::Result<()> {
const SHAPE: &str = "`graphql(…)` on a fragment's field takes ONE entry — \
`graphql(rename = \"…\")`, what a CLIENT calls this field, on the object and \
in the filter alike";
if !published {
return Err(attribute::named(
meta,
format!(
"`{field}` names itself on a wire face this fragment does not have — the tier publishes \
nothing unless the declaration asks, so a name here would be a name on nothing. Write \
`graphql[(…)]` at the head to publish the object and the filter's input face, or drop the \
word"
),
));
}
if attribute::has_value(meta) {
return Err(attribute::named(meta, SHAPE.to_owned()));
}
if !attribute::has_block(meta) || attribute::empty_group(meta) {
return Err(attribute::named(
meta,
format!("`graphql` says nothing on its own at a field — {SHAPE}"),
));
}
let mut refusal = None;
meta.parse_nested_meta(|inner| {
if inner.path.is_ident("rename") {
match value::literal(&inner, FIELD_NAME) {
Ok(spelled) => {
crate::wire::refuse_invalid_name(&spelled.value(), &spelled, errors);
set_once(
wire_name,
spelled,
&inner.path,
&format!(
"`rename` is declared more than once in `graphql(…)` on `{field}` — one option, one \
value"
),
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
refusal.get_or_insert_with(|| {
attribute::unknown(
&inner,
&format!(
"unknown entry in `graphql(…)` on `{field}` — {SHAPE}. The record seat's other wire words \
(`skip`, `type = \"…\"`, the per-database crossings, a backend's own cell) each name a \
per-face or per-backend fact, and this tier publishes ONE object and ONE input face with \
no backend cell between them — so they arrive with the round that gives them one"
),
&["rename"],
)
});
Ok(())
})?;
match refusal {
Some(e) => Err(e),
None => Ok(()),
}
}
const FIELD_NAME: &str = "a wire field's `rename` must be its name in the schema, as a word in a \
string literal";
const COLUMN_NAME: &str = "a column's `rename` must be its name where it is stored, in a string \
literal";
#[derive(Default)]
struct RecordColumn {
skip: Option<SkipField>,
flatten: Option<syn::Path>,
rename: Option<syn::LitStr>,
per_db: Vec<FieldDatabase>,
derived: Vec<DerivedColumn>,
write: Option<Transform>,
read: Option<Transform>,
}
struct Transform {
at: syn::Path,
path: syn::Path,
}
struct DerivedColumn {
at: syn::Path,
column: syn::LitStr,
from: syn::Path,
ty: syn::Type,
}
const PERSIST: &str = "persist";
const FLATTEN: &str = "flatten";
const SKIP: &str = "skip";
const RENAME: &str = "rename";
const SORTABLE: &str = "sortable";
const INDEXED: &str = "indexed";
const DERIVED: &str = "derived";
const WRITE: &str = "write";
const READ: &str = "read";
const WRITE_PATH: &str = "`write` names the function a value passes through on its way to STORAGE, \
as a path in a string literal — a `fn(&T) -> T` over this field's own \
type. It is spent at BOTH the bind and the crossing's query operand, \
which is what makes an index answer `eq` exactly: a value stored in one \
spelling and asked in another is a row a client cannot find";
const READ_PATH: &str = "`read` names the function a stored value passes through on its way BACK, \
as a path in a string literal — a `fn(&T) -> T` over this field's own \
type. Writing none is the identity, which is what a canonicalisation \
wants: a reduced value is a valid domain value and there is nothing to \
undo";
const DERIVED_SHAPE: &str = "`derived(…)` names a column this fragment's WRITE computes and its \
READ never fetches — `derived(column = \"…\", from = \
\"path::to::fn\", type = \"…\")`, where `from` is a `fn(&Self) -> T` \
reading whatever sibling fields it needs and `type` is that `T`. It is \
repeatable: one block, one column";
const DERIVED_NAME: &str = "`column` names the derived column where it is stored, in a string \
literal — the name a statement renders, an order names and a filter \
slot is called after";
const DERIVED_FROM: &str = "`from` names the function that computes this column, as a path in a \
string literal — a `fn(&Self) -> T` taking the whole value, so it may \
read every field the column is derived from";
const DERIVED_TYPE: &str = "`type` names the derived column's own type, as a type in a string \
literal — the `T` the function returns, written here because a `where` \
clause, a filter slot and a comparison member all need it as TOKENS and \
no stable spelling names a function's return";
fn record_column(
meta: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
host: Option<&RecordActivation>,
stored: &mut RecordColumn,
errors: &mut Errors,
) -> syn::Result<()> {
const SHAPE: &str = "`record(…)` on a field takes the storage words — `skip` (with \
`skip(default = \"…\")` naming what fills the read), `derived(…)` for a \
column the write computes off this field, `write = \"…\"` and `read = \"…\"` \
for the transforms a value crosses the storage boundary through, `flatten`, \
`rename = \"…\"`, and one database written bare to narrow this field to it \
or with words in it to say how that database renders the column";
if host.is_none() {
return Err(attribute::named(
meta,
format!(
"`{field}` says something to the RECORD host and this fragment declares none — a word about \
a column is a word for the rung that has rows, so it is read only where the declaration \
said that rung may hold it. Write `record[(<db>, …)]` at the head, or drop the namespace \
here"
),
));
}
if attribute::has_value(meta) {
return Err(attribute::named(meta, SHAPE.to_owned()));
}
if !attribute::has_block(meta) || attribute::empty_group(meta) {
return Err(attribute::named(
meta,
format!("`record` says nothing on its own at a field — {SHAPE}"),
));
}
let mut refusal = None;
meta.parse_nested_meta(|inner| {
if inner.path.is_ident(SKIP) {
let at = inner.path.clone();
let declared = crate::parse::skip_word(&inner, "on this field", errors)?;
set_once(
&mut stored.skip,
declared,
&at,
&format!("`skip` is declared more than once on `{field}` — one word, one field"),
errors,
);
return Ok(());
}
if inner.path.is_ident(RENAME) {
match value::literal(&inner, COLUMN_NAME) {
Ok(spelled) => set_once(
&mut stored.rename,
spelled,
&inner.path,
&format!("`rename` is declared more than once on `{field}` — one option, one value"),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident(SORTABLE) {
refusal.get_or_insert_with(|| {
attribute::named(
&inner,
format!(
"`sortable` orders a COLLECTION, and a collection is what a `list(…)` or `set(…)` label \
declares — which a fragment's field cannot write: this tier takes the PROJECTION words \
(`copy`, `repeated`, `optional`), and none of them says a value is many in the sense a \
storage plan can order. So there is no order for a companion column to preserve on \
`{field}`, which is the record seat's own rule read at a seat where nothing can meet \
it. A collection whose order is stored is a column of the HOLDER's declaration"
),
)
});
return Ok(());
}
if inner.path.is_ident(INDEXED) {
refusal.get_or_insert_with(|| {
attribute::named(
&inner,
format!(
"`indexed` puts a second index on the table a COLLECTION's elements are rows of, and a \
collection is what a `list(…)` or `set(…)` label declares — which a fragment's field \
cannot write: this tier takes the PROJECTION words (`copy`, `repeated`, `optional`), \
and none of them says a value is many in the sense a storage plan can index. So there \
are no elements on `{field}` for a value-led index to lead on, which is the record \
seat's own rule read at a seat where nothing can meet it. A collection that is seeked \
by its elements is a column of the HOLDER's declaration; ONE column's index, in ONE \
database, is that database's own block — `#[ingraph(sqlite(indexed))]`"
),
)
});
return Ok(());
}
if inner.path.is_ident(FLATTEN) {
if attribute::has_value(&inner) || attribute::has_block(&inner) {
refusal.get_or_insert_with(|| {
attribute::named(
&inner,
"`flatten` is a BARE word — it drops this field's own name so its type's segments become \
columns of the fragment's namespace, and there is nothing for a value to say about that"
.to_owned(),
)
});
return Ok(());
}
attribute::skip_entry(&inner);
set_once(
&mut stored.flatten,
inner.path.clone(),
&inner.path,
&format!("`flatten` is declared more than once on `{field}` — one marker, one layout"),
errors,
);
return Ok(());
}
if inner.path.is_ident(DERIVED) {
match derived_column(&inner, field, errors) {
Ok(Some(one)) => stored.derived.push(one),
Ok(None) => {}
Err(e) => {
refusal.get_or_insert(e);
}
}
return Ok(());
}
for (word, slot, shape) in [
(WRITE, &mut stored.write, WRITE_PATH),
(READ, &mut stored.read, READ_PATH),
] {
if !inner.path.is_ident(word) {
continue;
}
match value::parse_literal::<syn::Path>(&inner, shape) {
Ok(path) => set_once(
slot,
Transform {
at: inner.path.clone(),
path,
},
&inner.path,
&format!(
"`{word}` is declared more than once on `{field}` — one field, one path to storage"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if let Some(kind) = crate::parse::database_kind(&inner.path) {
return crate::parse::field_database(&inner, kind, &mut stored.per_db, errors);
}
refusal.get_or_insert_with(|| {
attribute::unknown(
&inner,
&format!("unknown entry in `record(…)` on `{field}` — {SHAPE}"),
&[SKIP, FLATTEN, RENAME, SORTABLE, INDEXED, DERIVED, WRITE, READ],
)
});
Ok(())
})?;
match refusal {
Some(e) => Err(e),
None => Ok(()),
}
}
fn refuse_a_column_derived_off_a_field_that_has_none(
field: &syn::Ident,
stored: &RecordColumn,
errors: &mut Errors,
) {
if stored.skip.is_none() {
return;
}
for one in &stored.derived {
errors.push(syn::Error::new_spanned(
&one.at,
format!(
"`{field}` carries `skip` and `derived(column = \"{column}\", …)` — one says the field is a \
column in NO database and the other adds a column beside the ones it would have been. The \
two words are mirror images: `skip` is declared and not stored, `derived` is stored and \
not declared, and a field that ends at no position in the layout has nothing for a derived \
column to follow. Drop whichever is not meant — a computed column whose sources are all \
skipped belongs to the field that IS stored",
column = one.column.value(),
),
));
}
}
fn refuse_a_transform_with_nothing_to_transform(
field: &syn::Ident,
stored: &RecordColumn,
errors: &mut Errors,
) {
let Some(skip) = stored.skip.as_ref() else {
return;
};
let filled = skip.default.is_some();
for (word, declared) in [(WRITE, stored.write.as_ref()), (READ, stored.read.as_ref())] {
let Some(transform) = declared else {
continue;
};
errors.push(syn::Error::new_spanned(
&transform.at,
format!(
"`{field}` carries `skip` and `{word} = \"…\"`, and the word has no site left to be spent \
at — a skipped field is a column of NO database, so there is no bind to write through, no \
slot for a query operand to cross at, and a read that {supplies} instead of fetching one. \
A transform is what a value crosses the STORAGE BOUNDARY through, and this field never \
crosses it. Drop whichever is not meant",
supplies = if filled {
"hands back what `skip(default = \"…\")` named"
} else {
"hands back `Default::default()`"
},
),
));
}
}
fn refuse_a_derived_name_a_column_already_has(columns: &[FragmentField], errors: &mut Errors) {
let stored_name = |field: &FragmentField| {
field
.stored_name
.clone()
.unwrap_or_else(|| field.column.name.to_string())
};
let mut taken: Vec<(String, &'static str)> = columns
.iter()
.filter(|field| field.skip.is_none() && !field.flatten)
.map(|field| (stored_name(field), "declared field"))
.collect();
for field in columns {
for one in &field.derived {
let spelled = one.column.external().to_owned();
if let Some((_, kind)) = taken.iter().find(|(name, _)| *name == spelled) {
errors.push(syn::Error::new_spanned(
one.column.safe(),
format!(
"`{spelled}` is already a column of this fragment — the {kind} of that name renders it \
too, and two values written into one column is a row whose second write is the one \
that survives. A derived column's name is the axis its filter slot, its order and \
every statement speak in, so it has to be this fragment's alone: rename the derived \
column, or `record(rename = \"…\")` whichever declared field it met"
),
));
continue;
}
taken.push((spelled, "derived column"));
}
}
}
fn derived_column(
meta: &syn::meta::ParseNestedMeta<'_>,
field: &syn::Ident,
errors: &mut Errors,
) -> syn::Result<Option<DerivedColumn>> {
const COLUMN: &str = "column";
const FROM: &str = "from";
const TYPE: &str = "type";
if attribute::has_value(meta) {
return Err(attribute::named(meta, DERIVED_SHAPE.to_owned()));
}
if !attribute::has_block(meta) || attribute::empty_group(meta) {
return Err(attribute::named(
meta,
format!("`derived` says nothing on its own on `{field}` — {DERIVED_SHAPE}"),
));
}
let at = meta.path.clone();
let (mut column, mut from, mut ty) = (None, None, None);
let mut written: Vec<&str> = Vec::new();
attribute::options(meta, |option| {
if option.path.is_ident(COLUMN) {
written.push(COLUMN);
match value::literal(&option, DERIVED_NAME) {
Ok(spelled) => set_once(
&mut column,
spelled,
&option.path,
&format!(
"`column` is declared more than once in `derived(…)` on `{field}` — one block, one column"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident(FROM) {
written.push(FROM);
match value::parse_literal::<syn::Path>(&option, DERIVED_FROM) {
Ok(path) => set_once(
&mut from,
path,
&option.path,
&format!(
"`from` is declared more than once in `derived(…)` on `{field}` — one column, one function"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if option.path.is_ident(TYPE) {
written.push(TYPE);
match value::parse_literal::<syn::Type>(&option, DERIVED_TYPE) {
Ok(written) => set_once(
&mut ty,
written,
&option.path,
&format!(
"`type` is declared more than once in `derived(…)` on `{field}` — one column, one type"
),
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
&format!("unknown entry in `derived(…)` on `{field}` — {DERIVED_SHAPE}"),
&[COLUMN, FROM, TYPE],
));
Ok(())
})?;
let missing: Vec<&str> = [COLUMN, FROM, TYPE]
.into_iter()
.filter(|word| !written.contains(word))
.collect();
let (Some(column), Some(from), Some(ty)) = (column, from, ty) else {
if !missing.is_empty() {
errors.push(syn::Error::new_spanned(
&at,
format!(
"`derived(…)` on `{field}` names no {absent} — {DERIVED_SHAPE}",
absent = crate::parse::shipped(missing.into_iter()),
),
));
}
return Ok(None);
};
Ok(Some(DerivedColumn {
at,
column,
from,
ty,
}))
}
fn refuse_a_dialect_the_layout_cannot_carry(
field: &syn::Ident,
host: Option<&RecordActivation>,
stored: &RecordColumn,
errors: &mut Errors,
) {
const WALL: &str = "a fragment publishes ONE dialect-free layout and there is no second list for \
a second database to differ in: `ColumnKind` takes no dialect at all, and the \
READ that would have to differ cannot be split — two `Assemble` impls \
constrained to different `Row::Database`s are `E0119`, conflicting \
implementations. A layout that really does vary per database is the HOLDER's \
to write, on the field that mounts this fragment, where there is a row per \
database to write it in. What a dialect at THIS head still buys is the \
comparison pair a wire-faced holder asks for at that backend";
let Some(host) = host else {
return;
};
let declared: Vec<DatabaseKind> = host.databases.iter().map(|one| one.kind).collect();
for per in &stored.per_db {
let db = per.kind.as_str();
if !declared.contains(&per.kind) {
let head = if declared.is_empty() {
"the head is the bare `record` word, which fixes no dialect for a field to speak about"
.to_owned()
} else {
format!(
"this fragment is built for {list}",
list = crate::parse::shipped(declared.iter().map(|kind| kind.as_str()))
)
};
errors.push(syn::Error::new_spanned(
&per.at,
format!(
"`{db}` is not a database this fragment names — {head}. A field names a database to narrow \
itself to it or to say how it renders the column there, and both need the head to have \
named it first: write `#[ingraph::fields(record({db}, …))]`."
),
));
continue;
}
if let Some(at) = per.flatten.as_ref() {
errors.push(syn::Error::new_spanned(
at,
format!(
"`flatten` inside `record({db}(…))` scopes a LAYOUT to one dialect, and a fragment's \
layout carries none: what it publishes is a single `ColumnKind::SEGMENTS`, and that \
trait's own note records the measurement that keeps a dialect out of it. Write \
`record(flatten)`, which is the same decision for every database that holds `{field}`. A \
layout that really does vary per database is the HOLDER's to write, on the field that \
mounts this fragment"
),
));
continue;
}
if let Some(skip) = per.skip.as_ref() {
errors.push(syn::Error::new_spanned(
&skip.at,
format!(
"`record({db}(skip(…)))` withholds `{field}` from ONE dialect, and the fill it names is \
what a read of THAT dialect would supply — {WALL}. Write `record(skip(default = \"…\"))` \
for a field no database holds, which is one absence with one fill and needs no dialect \
to state"
),
));
continue;
}
if per.configured() {
errors.push(syn::Error::new_spanned(
&per.at,
format!("`record({db}(…))` says how ONE database renders `{field}`, and {WALL}"),
));
}
}
let narrowed: Vec<DatabaseKind> = stored
.per_db
.iter()
.filter(|per| per.bare && declared.contains(&per.kind))
.map(|per| per.kind)
.collect();
if narrowed.is_empty() || declared.iter().all(|kind| narrowed.contains(kind)) {
return;
}
let absent: Vec<DatabaseKind> = declared
.iter()
.copied()
.filter(|kind| !narrowed.contains(kind))
.collect();
if let Some(per) = stored.per_db.iter().find(|per| per.bare) {
errors.push(syn::Error::new_spanned(
&per.at,
format!(
"`{field}` names {kept} and this fragment is built for {all}, so the word withholds the \
column from {gone} — and {WALL}. Write `record(skip)` for a field no database holds, or \
name every database the head does, which is the restatement it is",
kept = crate::parse::shipped(narrowed.iter().map(|kind| kind.as_str())),
all = crate::parse::shipped(declared.iter().map(|kind| kind.as_str())),
gone = crate::parse::shipped(absent.iter().map(|kind| kind.as_str())),
),
));
}
}
fn refuse_a_skipped_position(
field: &syn::Ident,
cursor: Option<&Cursor>,
stored: &RecordColumn,
errors: &mut Errors,
) {
let (Some(skip), Some(_)) = (stored.skip.as_ref(), cursor) else {
return;
};
errors.push(syn::Error::new_spanned(
&skip.at,
format!(
"`{field}` is skipped, so it is a column of no database — and this fragment is a `cursor` \
position, whose key is every declared field in declared order. The SQL keyset compares those \
fields' columns, and a field that has none is one the engine cannot resume a page at. Drop \
the `skip`, or drop the `cursor` word: a fragment without one is stored, filtered and read \
back exactly as before, and is simply not a paging position"
),
));
}
fn refuse_a_cycle(fragment: &syn::Ident, field: &syn::Ident, ty: &syn::Type, errors: &mut Errors) {
if !holds(fragment, ty) {
return;
}
errors.push(syn::Error::new_spanned(
ty,
format!(
"`{field}` gives `{fragment}` a field of its own type, so `{fragment}` → `{fragment}` is a \
cycle — and a fragment is HELD, which means its columns are laid out inside whatever holds \
it. A value that holds itself has no width: its column list would contain its column list. \
The rung that can point at another instance of a type is `entity`, whose `ref` names one by \
ID rather than laying it out inline"
),
));
}
fn holds(fragment: &syn::Ident, ty: &syn::Type) -> bool {
let syn::Type::Path(path) = ty else {
return false;
};
let Some(last) = path.path.segments.last() else {
return false;
};
match &last.arguments {
syn::PathArguments::None => last.ident == *fragment,
syn::PathArguments::AngleBracketed(inner) if last.ident == "Option" => {
inner.args.iter().any(|argument| match argument {
syn::GenericArgument::Type(inner) => holds(fragment, inner),
_ => false,
})
}
_ => false,
}
}
fn emitted_methods(model: &FieldsModel, errors: &mut Errors) {
let mut taken: Vec<&Emitted> = Vec::new();
for emitted in &model.emitted_methods() {
if let Some(first) = taken.iter().find(|seen| seen.name == emitted.name) {
errors.push(syn::Error::new_spanned(
&emitted.name,
format!(
"`{owner}` would declare `{name}` twice — {this}, and {that} already reaches it",
owner = emitted.owner_name,
name = emitted.name,
this = emitted.origin,
that = first.origin,
),
));
}
taken.push(emitted);
}
}
fn refuse_a_published_collision(model: &FieldsModel, errors: &mut Errors) {
for kind in GraphqlKind::ALL {
let mut taken: Vec<(String, syn::Ident)> = Vec::new();
for (word, at) in model.wire_words(kind) {
if let Some((_, first)) = taken.iter().find(|(seen, _)| *seen == word) {
errors.push(syn::Error::new_spanned(
&at,
format!(
"`{at}` publishes `{word}` on this fragment's object, and `{first}` already does — one \
word is one field of the emitted object, and two entries reaching it are two members \
of one `#[Object]` block. Move one of them with \
`#[graphql({kind}(rename = \"…\"))]`, or rename the field",
kind = kind.as_str(),
),
));
continue;
}
taken.push((word, at));
}
}
}
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
const WHY: &str = "generic field fragments are not supported — a fragment must be concrete, \
because a field's type is read straight off the declaration";
if !generics.params.is_empty() {
errors.push(syn::Error::new_spanned(generics, WHY));
} else if let Some(clause) = &generics.where_clause {
errors.push(syn::Error::new_spanned(clause, WHY));
}
}
fn named_fields(input: &syn::DeriveInput) -> syn::Result<&syn::FieldsNamed> {
match &input.data {
syn::Data::Struct(data) => match &data.fields {
syn::Fields::Named(named) => Ok(named),
syn::Fields::Unnamed(_) | syn::Fields::Unit => Err(syn::Error::new_spanned(
&input.ident,
"a field fragment must be a struct with named fields — what a holder inherits is a field's \
name as much as its type, and a positional one has none to inherit",
)),
},
syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
&input.ident,
"`#[ingraph::fields(record, entity)]` supports structs only",
)),
}
}