use ingraph_codegen::id::IdModel;
use crate::{attribute, errors::Errors, value};
#[cfg(test)]
mod tests;
const DERIVE: &str = "#[derive(ingraph::Id)]";
const CRATE_PATH: &str =
"`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";
const BUILT: [&str; 1] = ["crate"];
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<IdModel> {
let mut errors = Errors::default();
let krate = options(&input.attrs, &mut errors);
concrete(input, &mut errors);
transparent(input, &mut errors);
let inner = match held(input) {
Ok(inner) => inner,
Err(terminal) => return Err(errors.seal(terminal)),
};
let model = IdModel {
vis: input.vis.clone(),
subject: input.ident.clone(),
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
inner,
};
errors.into_result(model)
}
fn held(input: &syn::DeriveInput) -> syn::Result<syn::Type> {
let syn::Data::Struct(data) = &input.data else {
let shape = match &input.data {
syn::Data::Enum(_) => {
"this declaration is an ENUM, whose content is its ALTERNATIVES — so there is no one value \
for a key duty to read. A vocabulary is already a key by another road: \
`#[derive(ingraph::Enum)]` writes the transparency row along with the rest of a \
vocabulary's citizenship"
}
_ => {
"this declaration is a UNION, whose content is whichever field was last written — a fact no \
`unsafe`-free read can recover, and an identity nothing can compare. There is no road for \
one here and none is planned"
}
};
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"{DERIVE} equips a WRAPPER — one type holding one value, transparently — and {shape}."
),
));
};
let syn::Fields::Unnamed(fields) = &data.fields else {
let (shape, fix) = match &data.fields {
syn::Fields::Named(_) => (
"holds a NAMED field",
"write it as a tuple struct — `struct Name(Inner);` — which is the same declaration with \
the name dropped",
),
_ => (
"holds NOTHING",
"a type with no value in it addresses nothing, and there is no field for the key duties to \
read",
),
};
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"{DERIVE} equips a TUPLE wrapper — `struct Name(Inner);` — and this one {shape}. The casts \
this device writes are about POSITION ZERO and every emitted row builds one as \
`Self(inner)`, so the shape is the device's own rather than a preference: {fix}."
),
));
};
let mut held = fields.unnamed.iter();
let (Some(field), None) = (held.next(), held.next()) else {
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"{DERIVE} equips a wrapper holding EXACTLY ONE value, and this one holds {count}. The \
transparency assertion it writes says this type IS the value inside it — at the same \
equality, the same order and the same stored form — and a declaration with two values has \
two answers and no rule for picking between them. A key spanning several columns is a KEY \
STRUCT, which a record mints from its own `#[ingraph(id)]` and lineage columns rather than \
from a wrapper.",
count = fields.unnamed.len(),
),
));
};
Ok(field.ty.clone())
}
fn transparent(input: &syn::DeriveInput, errors: &mut Errors) {
if input.attrs.iter().any(is_transparent) {
return;
}
errors.push(syn::Error::new_spanned(
&input.ident,
format!(
"the Id derive's admission requires `#[repr(transparent)]`, and this declaration carries no \
such attribute. It is not ceremony: {DERIVE} writes `from_ref`, which VIEWS a `&Inner` as a \
`&Self`, and the only thing that makes that view sound is the two types having one layout. \
Written down, layout identity is the compiler's guarantee; left to the default \
representation it is a hope about a `repr(Rust)` type, which is explicitly free to be laid \
out otherwise. Add `#[repr(transparent)]` above the declaration."
),
));
}
fn is_transparent(attr: &syn::Attribute) -> bool {
if !attr.path().is_ident("repr") {
return false;
}
let mut found = false;
let _ = attr.parse_nested_meta(|entry| {
if entry.path.is_ident("transparent") {
found = true;
}
if entry.input.peek(syn::token::Paren) {
let content;
syn::parenthesized!(content in entry.input);
let _ = content.parse::<proc_macro2::TokenStream>();
}
Ok(())
});
found
}
fn concrete(input: &syn::DeriveInput, errors: &mut Errors) {
if input.generics.params.is_empty() {
return;
}
errors.push(syn::Error::new_spanned(
&input.generics,
format!(
"{DERIVE} equips a CONCRETE wrapper, and this declaration is generic. An id is an address: it \
is stored, rendered into a path segment, published under its own name in a schema and \
compared against a column — and every one of those is a fact about ONE type rather than \
about a family of them. The three rows that break are worth naming: `From<Self> for Inner` \
puts an uncovered parameter in the self position (`E0210`), the minted `<Name>Wire` reading \
carries a parameter nothing uses (`E0392`), and the emitted `Debug` prints a name that is \
not the one a reader was shown. Wrap the concrete type instead, or take \
`#[derive(ingraph::NewType)]`, which is the device for a generic value."
),
));
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Option<syn::Path> {
let mut krate: Option<syn::Path> = None;
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
Ok(path) => attribute::set_once(&mut krate, path, &meta.path, CRATE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
if let Some(refusal) = candidate(&meta.path) {
errors.push(attribute::named(&meta, refusal));
return Ok(());
}
errors.push(attribute::unknown(
&meta,
"unknown entry in `#[ingraph(…)]` on an id wrapper — this device takes `crate = \"…\"` and \
nothing else. The register it writes is not chosen: an address needs every face of it, so \
there is no word here to install one",
&BUILT,
));
Ok(())
});
krate
}
fn candidate(path: &syn::Path) -> Option<String> {
let word = if path.is_ident("graphql") {
"`graphql(<backend>(…))` is `#[derive(ingraph::NewType)]`'s word and this device has no seat \
for it: an id publishes ONE wire face — a scalar under its own name, with its `FromStr` as the \
door and its `Display` as the rendering — and that face is written unconditionally. A type \
that wants to choose its wire faces is a VALUE rather than an address; take the newtype door."
} else if path.is_ident("marker") || path.is_ident("filter") {
"`marker(<family>)` and `filter` are `#[derive(ingraph::NewType)]`'s words, where they choose \
which interpretation a field of the type is read under. An id has no choice to make: it is \
read as a COMPOSITE — one value occupying one column — and this device writes that reading, \
its filter and the `<Name>Wire` the filter is parameterised by, all three unconditionally."
} else if path.is_ident("cursor") {
"`cursor` is `#[derive(ingraph::NewType)]`'s word for a keyset position, and this device writes \
that row with no word at all: an id is what a page is ordered and resumed by, so a `CursorValue` \
that had to be asked for would be a face every declaration asks for."
} else if path.is_ident("sqlite") || path.is_ident("postgres") || path.is_ident("mysql") {
"the dialect words are `#[derive(ingraph::NewType)]`'s, where they pick which dialects a value \
is a column in. This device writes ONE set of storage rows for every dialect at once — a \
`StoredAs<Db>`, a `Carrier<Db>` and an `Assemble` generic in the database, all three routed \
through `ingraph::IdColumn<Db>` at the INNER — so there is no per-dialect choice here to make. \
Which form a dialect stores is the inner type's answer through that seam, and a downstream \
inner joins by writing that one row rather than by naming dialects here."
} else if path.is_ident("mongo") {
"`mongo` names the document kit, and this device does not write it. Neither live register wrote \
one either: `MediaId` and `VolumeId` both stop at the SQL pair, so a document row here would \
be the first of its kind and unmeasured. The seat is held rather than filled."
} else if path.is_ident("rename") {
"`rename = \"…\"` moves the name a SCHEMA publishes, and an id does not take one: the type's \
own name is the only thing a client can correlate an address with, and both live registers \
spell `#[Scalar(name = \"<the type>\")]` with nothing beside it."
} else {
return None;
};
Some(word.to_owned())
}