use ingraph_codegen::{
element::ElementFamily,
model::{DatabaseKind, GraphqlKind},
newtype::{Gate, Kits, NewTypeModel, ScalarKit},
};
use crate::{attribute, errors::Errors, value};
#[cfg(test)]
mod graphql_tests;
#[cfg(test)]
mod tests;
const DERIVE: &str = "#[derive(ingraph::NewType)]";
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; 8] = [
"crate", "graphql", "marker", "filter", "cursor", "sqlite", "postgres", "mysql",
];
const WIRE: [&str; 3] = ["scalar", "input", "output"];
const DOORS: [&str; 3] = ["rename", "parse", "check"];
const DOOR_PATH: &str = "`scalar(parse = \"…\")` and `scalar(check = \"…\")` take a PATH to the door \
function, in a string literal — `parse` a `fn(&str) -> Result<Self, E>` \
and `check` a `fn(<the inner type>) -> Result<Self, E>`, with `E: Display`";
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<NewTypeModel> {
let mut errors = Errors::default();
let Options { krate, kits } = options(&input.attrs, &mut errors);
let (member, inner) = match held(input) {
Ok(held) => held,
Err(terminal) => return Err(errors.seal(terminal)),
};
coherent(&kits, input, &mut errors);
let model = NewTypeModel {
vis: input.vis.clone(),
subject: input.ident.clone(),
generics: input.generics.clone(),
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
member,
inner,
kits,
};
errors.into_result(model)
}
#[derive(Default)]
struct Options {
krate: Option<syn::Path>,
kits: Kits,
}
fn held(input: &syn::DeriveInput) -> syn::Result<(syn::Member, syn::Type)> {
let syn::Data::Struct(data) = &input.data else {
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"{DERIVE} equips a NEWTYPE — one type wrapping one value — and this declaration is not a \
struct. A vocabulary takes `#[derive(ingraph::Enum)]` and a member set \
`#[derive(ingraph::Union)]`; both equip a type whose content is its ALTERNATIVES, which is \
the shape this device has no inner type to delegate to."
),
));
};
let mut fields = data.fields.iter();
let (Some(field), None) = (fields.next(), fields.next()) else {
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"{DERIVE} equips a struct holding EXACTLY ONE value, and this one holds {count}. Every face \
it writes is that value's own answer under this type's name, so a declaration with two \
fields has two answers and no rule for picking between them, and one with none has no \
answer at all. A row of columns takes `#[derive(ingraph::Filter)]` and its siblings.",
count = data.fields.len(),
),
));
};
let member = field.ident.clone().map_or_else(
|| syn::Member::Unnamed(syn::Index::from(0)),
syn::Member::Named,
);
Ok((member, field.ty.clone()))
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut options = Options::default();
let mut graphql_at: Option<syn::Path> = None;
let mut marker_at: Option<syn::Path> = None;
let mut filter_at: Option<syn::Path> = None;
let mut cursor_at: 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 options.krate, path, &meta.path, CRATE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("graphql") {
if graphql_at.is_some() {
errors.push(syn::Error::new_spanned(
&meta.path,
"`graphql(…)` is declared more than once — one block holds every backend, and a second \
one could only repeat or contradict the first",
));
attribute::skip_entry(&meta);
return Ok(());
}
graphql_at = Some(meta.path.clone());
return backends(&meta, &mut options.kits, errors);
}
if meta.path.is_ident("marker") {
attribute::set_once(
&mut marker_at,
meta.path.clone(),
&meta.path,
"`marker` is declared more than once — a value is read under ONE interpretation, and a \
second word could only name another",
errors,
);
options.kits.marker = Some(family(&meta, errors));
return Ok(());
}
if meta.path.is_ident("filter") {
attribute::set_once(
&mut filter_at,
meta.path.clone(),
&meta.path,
"`filter` is declared more than once — one word installs one kit",
errors,
);
options.kits.filter = true;
return no_options(&meta, "filter", errors);
}
if meta.path.is_ident("cursor") {
attribute::set_once(
&mut cursor_at,
meta.path.clone(),
&meta.path,
"`cursor` is declared more than once — one word installs one kit",
errors,
);
options.kits.cursor = true;
return no_options(&meta, "cursor", errors);
}
if let Some(database) = crate::parse::database_kind(&meta.path) {
return dialect(&meta, database, &mut options.kits, errors);
}
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 a newtype — it takes the KIT words \
`graphql(<backend>(…))`, `marker(<family>)`, `filter`, `cursor` and the dialect words \
`sqlite`, `postgres` and `mysql`, plus `crate = \"…\"`. Every one of them installs one \
face, delegated to the type this declaration wraps",
&BUILT,
));
Ok(())
});
options
}
fn backends(
meta: &syn::meta::ParseNestedMeta<'_>,
kits: &mut Kits,
errors: &mut Errors,
) -> syn::Result<()> {
let mut named: Vec<GraphqlKind> = Vec::new();
let walked = attribute::options(meta, |inner| {
let Some(kind) = crate::parse::graphql_kind(&inner.path) else {
errors.push(attribute::unknown(
&inner,
"unknown backend in `graphql(…)` — a wire face is one backend's impls, and a word naming \
none of them names no face. The wire words live inside a BACKEND's block, one level down: \
`scalar(…)`, `input` and `output` are entries of that cell rather than of this one",
&GraphqlKind::ALL.map(GraphqlKind::as_str),
));
return Ok(());
};
if named.contains(&kind) {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once in `graphql(…)` — one word per backend, because a \
backend has ONE face and a second word could only re-describe it",
kind = kind.as_str(),
),
));
attribute::skip_entry(&inner);
return Ok(());
}
named.push(kind);
positions(&inner, kind, kits, errors);
Ok(())
});
if named.is_empty() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`graphql` names no backend — write `graphql({first}(scalar))`. Without the block a newtype \
keeps every face this device writes off the wire — its readings, its cursor position and \
its columns — and what the block adds is a schema over it",
first = GraphqlKind::ALL[0].as_str(),
),
));
}
walked
}
fn positions(
meta: &syn::meta::ParseNestedMeta<'_>,
kind: GraphqlKind,
kits: &mut Kits,
errors: &mut Errors,
) {
let mut scalar_at: Option<syn::Path> = None;
let mut input_at: Option<syn::Path> = None;
let mut output_at: Option<syn::Path> = None;
let walked = attribute::options(meta, |entry| {
if entry.path.is_ident("scalar") {
attribute::set_once(
&mut scalar_at,
entry.path.clone(),
&entry.path,
&declared_twice("scalar"),
errors,
);
kits.scalar = Some(doors(&entry, errors));
return Ok(());
}
if entry.path.is_ident("input") {
attribute::set_once(
&mut input_at,
entry.path.clone(),
&entry.path,
&declared_twice("input"),
errors,
);
kits.input = true;
return no_options(&entry, "input", errors);
}
if entry.path.is_ident("output") {
attribute::set_once(
&mut output_at,
entry.path.clone(),
&entry.path,
&declared_twice("output"),
errors,
);
kits.output = true;
return no_options(&entry, "output", errors);
}
if entry.path.is_ident("nullable") {
errors.push(attribute::named(
&entry,
"`nullable` is a word this roster carries and this round does not build. The face it would \
install is `NullableFace`, which the framework implements on FILTER KINDS rather than on \
values — so a nullable column of this newtype already has its face, through the `filter` \
kit and the framework's own `Nullable<F>` row, and there is nothing here for a \
pass-through to add. Write `filter` and a `marker(<family>)`; the day a newtype WRAPS a \
filter, this word is what installs the delegation, and it is measured before it is \
promised."
.to_owned(),
));
return Ok(());
}
errors.push(attribute::unknown(
&entry,
&format!(
"unknown entry in a newtype's `{kind}` block — it takes `scalar(…)`, `input` and `output`, \
the faces a schema has for a declared value",
kind = kind.as_str(),
),
&WIRE,
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
if scalar_at.is_none() && input_at.is_none() && output_at.is_none() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{kind}` dresses this newtype for no face — write `{kind}(scalar)`, `{kind}(input)`, \
`{kind}(output)` or any combination. A backend block naming none is a face nothing \
renders, and an entry nobody reads is a rule its author believes they declared",
kind = kind.as_str(),
),
));
}
}
fn doors(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> ScalarKit {
let mut kit = ScalarKit::default();
let mut rename: Option<syn::LitStr> = None;
let mut declared: Option<&'static str> = None;
let walked = attribute::options(meta, |option| {
if option.path.is_ident("rename") {
match value::literal(&option, attribute::SDL_NAME) {
Ok(word) => {
crate::wire::refuse_invalid_name(&word.value(), &word, errors);
attribute::set_once(
&mut rename,
word,
&option.path,
"`rename` is declared more than once in `scalar(…)` — one option, one value",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
let door = if option.path.is_ident("parse") {
"parse"
} else if option.path.is_ident("check") {
"check"
} else {
errors.push(attribute::unknown(
&option,
"unknown entry in `scalar(…)` — it takes `rename = \"…\"` for the schema name and ONE door, \
`parse = \"…\"` or `check = \"…\"`",
&DOORS,
));
return Ok(());
};
let path = match value::parse_literal::<syn::Path>(&option, DOOR_PATH) {
Ok(path) => path,
Err(e) => {
errors.push(e);
return Ok(());
}
};
match declared {
Some(already) if already == door => {
errors.push(syn::Error::new_spanned(
&option.path,
format!("`{door}` is declared more than once in `scalar(…)` — a door is ONE function"),
));
}
Some(already) => {
errors.push(syn::Error::new_spanned(
&option.path,
format!(
"`{already}` and `{door}` are the two DOORS a newtype may put in front of its values \
and no declaration has both: `parse` reads a SPELLING and owns the grammar that folds \
it, `check` takes the carrier's own value and says whether it is one of this type's. \
Every read path spends the door — the scalar, the cursor and the decode — so a second \
one would be two answers to one question. Keep the one this type is."
),
));
}
None => {
declared = Some(door);
kit.gate = Some(match door {
"parse" => Gate::Parse(path),
_ => Gate::Check(path),
});
}
}
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
kit.rename = rename.map(|word| word.value());
kit
}
fn family(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> ElementFamily {
let mut named: Option<ElementFamily> = None;
let walked = attribute::options(meta, |word| {
let Some(found) = ElementFamily::ALL
.into_iter()
.find(|family| word.path.is_ident(family.word()))
else {
errors.push(attribute::unknown(
&word,
"unknown family in `marker(…)` — a newtype is read under one of the framework's own value \
readings, and the four here are the four whose filter kind carries an OPERAND PARAMETER \
for a declared value to sit in. `bool` and `duration` carry none; `list` and `set` are \
collection POSITIONS rather than elements",
&ElementFamily::ALL.map(ElementFamily::word),
));
return Ok(());
};
if named.is_some() {
errors.push(syn::Error::new_spanned(
&word.path,
"`marker(…)` names more than one family — a value is read under ONE interpretation, and a \
second word could only name another",
));
attribute::skip_entry(&word);
return Ok(());
}
named = Some(found);
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
named.unwrap_or(ElementFamily::Scalar)
}
fn dialect(
meta: &syn::meta::ParseNestedMeta<'_>,
database: DatabaseKind,
kits: &mut Kits,
errors: &mut Errors,
) -> syn::Result<()> {
if !database.is_sql() {
errors.push(attribute::named(
meta,
format!(
"`{word}` is a word this roster carries and this round does not build. Its kit is the \
document one — `MongoCarrier` and the extraction beside it — where the three SQL words \
install a dialect's `Type`, `Encode`, `Decode` and bind. Nothing about it is harder; it is \
unmeasured, and a word this device accepted and did not install would be a face its author \
believes they declared.",
word = database.as_str(),
),
));
return Ok(());
}
if kits.databases.contains(&database) {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{word}` is declared more than once — one word per dialect, because a dialect has ONE set \
of rows and a second word could only re-emit them",
word = database.as_str(),
),
));
attribute::skip_entry(meta);
return Ok(());
}
kits.databases.push(database);
no_options(meta, database.as_str(), errors)
}
fn no_options(
meta: &syn::meta::ParseNestedMeta<'_>,
word: &str,
errors: &mut Errors,
) -> syn::Result<()> {
attribute::options(meta, |option| {
errors.push(attribute::unknown(
&option,
&format!(
"`{word}` takes no options — it installs one face, and every part of that face is the \
wrapped type's own answer"
),
&[],
));
Ok(())
})
}
fn declared_twice(word: &str) -> String {
format!("`{word}` is declared more than once in this backend's block — one word, one face")
}
fn candidate(path: &syn::Path) -> Option<String> {
let word = if path.is_ident("comparison") {
"`comparison` is a word this roster carries and this round does not build, and the reason is \
the ORPHAN RULE rather than effort. The row it would install is \
`TryFromFilter<<the filter>> for Sql<Kind>Comparison<Self, Db>` — a foreign self type — which \
is legal in a declaring crate only where the FILTER is that crate's own. This device names the \
framework's filter through a reading rather than minting one, so there is no local type in \
that impl for coherence to accept. `#[derive(ingraph::Filter)] #[ingraph(operator(<family>))]` \
is the door that mints, and the crossing is written beside it."
} else if path.is_ident("order_by") {
"`order_by` is a word this roster carries and this round does not build. Ordering reaches a \
value through its column and its cursor position, both of which this device installs — the \
dialect words and `cursor` — and no per-value trait in this framework carries the term itself \
yet. The word is held so that the day one exists, it lands here rather than somewhere else."
} else if path.is_ident("collection_element") {
"`collection_element` is a word this roster carries and this round does not build. It would \
install `CollectionElement`, whose whole content is an ADMISSION — that a value may be one \
element of a collection — and an admission is a decision about a type rather than a \
delegation, so it waits on the dialect words' own collection story rather than riding this \
round."
} else if path.is_ident("vector") {
"`vector(…)` is a word this roster carries and this round does not build. There is no \
per-value element trait for it to delegate to yet: a vector column's element is decided by the \
store rather than by a row on the value, and the seat is held for the day that changes."
} else if path.is_ident("blob") {
"`blob` is a word this roster carries and this round does not build. A key-addressed blob is a \
STORE position rather than a face on a value, and no trait on this shelf carries it — the seat \
is held so that the word lands here when one does."
} else if path.is_ident("tantivy") {
"`tantivy` is a word this roster carries and this round does not build. No per-value trait \
reaches the full-text engine today — a searchable column is declared at the RECORD, through \
`#[ingraph::fulltext]` — so the word names a kit with nothing yet to delegate to."
} else if path.is_ident("element") {
"`element(<family>)` is a word this roster carries and this round does not build, and today it \
names a device that already exists: `#[derive(ingraph::Filter)] \
#[ingraph(operator(<family>))]` MINTS a filter type this crate owns and gives the value the \
citizenship that filter needs. The word is booked here so that the two doors are one \
vocabulary when the mint moves; nothing about the element mode changes in the meantime."
} else if path.is_ident("record_field") {
"`record_field` is the roster's ONE bundle word and this round does not build it. It stands for \
`marker`, `filter`, the dialect words a declaration names and `cursor`, together — the set a \
value needs to be an ordinary column of a record — and a bundle is worth having only once the \
words it bundles are all built. Write them out; the expansion table is what this word will \
publish."
} else if path.is_ident("error") {
"`error(rename = \"…\")` names the refusal type a parse answers with, and this device declares \
none: a door is a function the DECLARATION supplies, so the refusal is that function's own \
error type and there is nothing here for the knob to move. `#[derive(ingraph::Enum)]` is the \
device that mints one, because a vocabulary's parse is the expansion's own."
} else {
return None;
};
Some(word.to_owned())
}
fn coherent(kits: &Kits, input: &syn::DeriveInput, errors: &mut Errors) {
if kits.filter && kits.marker.is_none() {
errors.push(syn::Error::new_spanned(
&input.ident,
"`filter` needs `marker(<family>)` beside it, and this declaration writes only the first. The \
filter kind is the FAMILY's — `marker(string)` is a text filter, `marker(scalar)` an \
ordering one — so without the word there is no family for the kind to be over; and a field \
of this type reaches its filter through the interpretation the type is read under, which is \
the row `marker` writes. Add `marker(<family>)`, or drop `filter` and keep a value that is \
filtered by nothing.",
));
}
if kits.marker.is_some() && !kits.filter {
errors.push(syn::Error::new_spanned(
&input.ident,
"`marker(<family>)` needs `filter` beside it, and this declaration writes only the first. The \
reading it installs is `DefaultMarker`, whose associated type carries an ITEM BOUND of \
`ToGraphqlFilter` — and the framework satisfies that bound over `<family>Marker<T>` by \
reading `T`'s own `<family>FilterMarker` row, which is the row `filter` writes. So a marker \
without it is not a smaller installation, it is one that does not compile, and the refusal \
would land inside an expansion rather than here. Add `filter`, or drop `marker(…)` and keep \
a value no field is read as.",
));
}
if kits.is_empty() {
errors.push(syn::Error::new_spanned(
&input.ident,
format!(
"{DERIVE} installs the faces a declaration NAMES, and this one names none — so the \
expansion is empty and the derive is a line with no effect. Write the kit words this \
newtype wants: `graphql(<backend>(…))` for a wire face, `marker(<family>)` and `filter` \
for the readings a field resolves through, `cursor` for a keyset position, and \
`sqlite`/`postgres`/`mysql` for the dialects it is a column in."
),
));
}
}