use ingraph_codegen::{
model::GraphqlKind,
mutation::{DeclaredError, ExchangeModel, HandlerModel, MutationModel},
};
use crate::{attribute, errors::Errors, value};
#[cfg(test)]
mod tests;
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
) -> syn::Result<MutationModel> {
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let (krate, graphql) = options(arguments, &mut errors);
concrete(&input.generics, &mut errors);
let fields = match named_fields(input) {
Ok(fields) => fields,
Err(terminal) => return Err(errors.seal(terminal)),
};
let exchanges = fields
.named
.iter()
.filter_map(|field| {
let name = field.ident.clone()?;
Some(exchange(field, name, &mut errors))
})
.collect();
errors.into_result(MutationModel {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
name: input.ident.clone(),
vis: input.vis.clone(),
graphql,
exchanges,
})
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> (Option<syn::Path>, Vec<GraphqlKind>) {
let mut krate: Option<syn::Path> = None;
let mut graphql: Vec<GraphqlKind> = Vec::new();
let mut graphql_at: Option<syn::Path> = None;
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::parse_literal::<syn::Path>(
&meta,
"`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
) {
Ok(path) => {
if krate.replace(path).is_some() {
errors.push(syn::Error::new_spanned(
&meta.path,
"`crate` is declared more than once — one declaration names one crate",
));
}
}
Err(e) => refuse_value(&meta, e, errors),
}
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 graphql, errors);
}
errors.push(attribute::unknown(
&meta,
"unknown entry in `#[ingraph::mutation(…)]` — it takes `graphql(…)` and `crate = \"…\"`. \
WHAT this node's fields are is written on the fields themselves, and which source mounts it \
is that source's own `mutation(node = \"…\")` word",
&["graphql", "crate"],
));
Ok(())
});
(krate, graphql)
}
fn backends(
meta: &syn::meta::ParseNestedMeta<'_>,
graphql: &mut Vec<GraphqlKind>,
errors: &mut Errors,
) -> syn::Result<()> {
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 skin",
&GraphqlKind::ALL.map(GraphqlKind::as_str),
));
return Ok(());
};
if graphql.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 skin and a second word could only re-describe it",
kind = kind.as_str(),
),
));
attribute::skip_entry(&inner);
return Ok(());
}
graphql.push(kind);
Ok(())
});
if graphql.is_empty() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`graphql` names no backend — write `graphql({first})`. Without the word this node still \
emits its whole Rust surface: the command vocabulary, the row a source mounts it through \
and the declaration record are all there, and what the block adds is a schema over them",
first = GraphqlKind::ALL[0].as_str(),
),
));
}
walked
}
fn exchange(field: &syn::Field, name: syn::Ident, errors: &mut Errors) -> ExchangeModel {
let mut rename: Option<syn::LitStr> = None;
let mut handler: Option<HandlerModel> = None;
let mut handler_at: Option<syn::Path> = None;
attribute::walk(&field.attrs, errors, |meta, errors| {
if meta.path.is_ident("rename") {
match value::literal(&meta, RENAME_WORD) {
Ok(word) => {
crate::wire::refuse_invalid_name(&word.value(), &word, errors);
attribute::set_once(
&mut rename,
word,
&meta.path,
"`rename` is declared more than once on this exchange — one field, one published word",
errors,
);
}
Err(e) => refuse_value(&meta, e, errors),
}
return Ok(());
}
if meta.path.is_ident("handler") {
if handler_at.is_some() {
errors.push(syn::Error::new_spanned(
&meta.path,
"`handler` is declared more than once on this exchange — one field is ONE thing an app \
can say, so a second handler could only be a second behaviour for one command",
));
attribute::skip_entry(&meta);
return Ok(());
}
handler_at = Some(meta.path.clone());
handler = handler_block(&meta, errors);
return Ok(());
}
errors.push(attribute::unknown(
&meta,
"unknown entry in `#[ingraph(…)]` on an exchange — a field takes `rename = \"…\"` (the wire's \
skin) and `handler(…)` (the behaviour), and everything else about the signature lives INSIDE \
the handler block",
&["rename", "handler"],
));
Ok(())
});
let handler = handler.unwrap_or_else(|| {
if handler_at.is_none() {
errors.push(syn::Error::new_spanned(&name, no_handler(&name)));
}
HandlerModel {
path: syn::parse_quote!(__ingraph_unresolved_handler),
awaited: false,
context: Vec::new(),
error: None,
}
});
ExchangeModel {
field: name,
ty: field.ty.clone(),
rename,
handler,
}
}
fn handler_block(
meta: &syn::meta::ParseNestedMeta<'_>,
errors: &mut Errors,
) -> Option<HandlerModel> {
if attribute::has_value(meta) {
return match value::parse_literal::<syn::Path>(meta, HANDLER_PATH) {
Ok(path) => Some(HandlerModel {
path,
awaited: false,
context: Vec::new(),
error: None,
}),
Err(e) => {
refuse_value(meta, e, errors);
None
}
};
}
if !attribute::has_block(meta) || attribute::empty_group(meta) {
errors.push(attribute::unknown(meta, HANDLER_EMPTY, &[]));
return None;
}
let mut path: Option<syn::Path> = None;
let mut path_at: Option<syn::Path> = None;
let mut awaited: Option<syn::Path> = None;
let mut context: Vec<syn::Path> = Vec::new();
let mut context_at: Option<syn::Path> = None;
let mut error: Option<DeclaredError> = None;
let mut error_at: Option<syn::Path> = None;
let walked = meta.parse_nested_meta(|inner| {
if inner.path.is_ident("path") {
path_at = Some(inner.path.clone());
match value::parse_literal::<syn::Path>(&inner, HANDLER_PATH) {
Ok(written) => attribute::set_once(
&mut path,
written,
&inner.path,
"`path` is declared more than once in `handler(…)` — one exchange runs one function",
errors,
),
Err(e) => refuse_value(&inner, e, errors),
}
return Ok(());
}
if inner.path.is_ident("async") {
attribute::set_once(
&mut awaited,
inner.path.clone(),
&inner.path,
"`async` is declared more than once in `handler(…)` — one handler wears one face",
errors,
);
attribute::skip_entry(&inner);
return Ok(());
}
if inner.path.is_ident("context") {
if context_at.is_some() {
errors.push(syn::Error::new_spanned(
&inner.path,
"`context(…)` is declared more than once in `handler(…)` — one block holds every \
resource this handler is granted, and a second one could only add to a list that is \
already there",
));
attribute::skip_entry(&inner);
return Ok(());
}
context_at = Some(inner.path.clone());
return granted(&inner, &mut context, errors);
}
if inner.path.is_ident("error") {
if error_at.is_some() {
errors.push(syn::Error::new_spanned(
&inner.path,
"`error(…)` is declared more than once in `handler(…)` — one exchange fails one way, and \
the shape of that way IS the handler's return type",
));
attribute::skip_entry(&inner);
return Ok(());
}
error_at = Some(inner.path.clone());
error = declared_error(&inner, errors);
return Ok(());
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `handler(…)` — the block IS the signature, and it takes `path = \"…\"` \
(who), `async` (which face), `context(…)` (the arguments) and `error(…)` (the failing half \
of the return)",
&["path", "async", "context", "error"],
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
let path = match path {
Some(path) => path,
None => {
if path_at.is_none() {
errors.push(syn::Error::new_spanned(&meta.path, HANDLER_NO_PATH));
}
return None;
}
};
Some(HandlerModel {
path,
awaited: awaited.is_some(),
context,
error,
})
}
fn granted(
meta: &syn::meta::ParseNestedMeta<'_>,
context: &mut Vec<syn::Path>,
errors: &mut Errors,
) -> syn::Result<()> {
if !attribute::has_block(meta) || attribute::empty_group(meta) {
errors.push(attribute::unknown(meta, CONTEXT_EMPTY, &[]));
return Ok(());
}
meta.parse_nested_meta(|inner| {
if !inner.path.is_ident("resource") {
errors.push(attribute::unknown(&inner, CONTEXT_LINE, &["resource"]));
return Ok(());
}
if !attribute::has_block(&inner) || attribute::empty_group(&inner) {
errors.push(attribute::unknown(&inner, CONTEXT_LINE, &[]));
return Ok(());
}
let held;
syn::parenthesized!(held in inner.input);
match held
.parse::<syn::LitStr>()
.and_then(|written| written.parse::<syn::Path>())
{
Ok(path) => context.push(path),
Err(e) => errors.push(syn::Error::new(e.span(), CONTEXT_LINE)),
}
Ok(())
})
}
fn declared_error(
meta: &syn::meta::ParseNestedMeta<'_>,
errors: &mut Errors,
) -> Option<DeclaredError> {
if !attribute::has_block(meta) || attribute::empty_group(meta) {
errors.push(attribute::unknown(meta, ERROR_EMPTY, &[]));
return None;
}
let mut ty: Option<syn::Path> = None;
let mut message: Option<syn::LitStr> = None;
let mut code: Option<syn::LitStr> = None;
let mut code_at: Option<syn::Path> = None;
let mut shape_at: Option<syn::Path> = None;
let walked = meta.parse_nested_meta(|inner| {
if inner.path.is_ident("type") {
shape_at = Some(inner.path.clone());
if message.is_some() {
errors.push(attribute::named(&inner, ERROR_BOTH.to_owned()));
return Ok(());
}
match value::parse_literal::<syn::Path>(&inner, ERROR_TYPE) {
Ok(path) => attribute::set_once(
&mut ty,
path,
&inner.path,
"`type` is declared more than once in `error(…)` — one exchange fails as one type",
errors,
),
Err(e) => refuse_value(&inner, e, errors),
}
return Ok(());
}
if inner.path.is_ident("message") {
shape_at = Some(inner.path.clone());
if ty.is_some() {
errors.push(attribute::named(&inner, ERROR_BOTH.to_owned()));
return Ok(());
}
match value::literal(&inner, ERROR_MESSAGE) {
Ok(sentence) => attribute::set_once(
&mut message,
sentence,
&inner.path,
"`message` is declared more than once in `error(…)` — one canned failure is one sentence",
errors,
),
Err(e) => refuse_value(&inner, e, errors),
}
return Ok(());
}
if inner.path.is_ident("code") {
match value::literal(&inner, ERROR_CODE) {
Ok(word) => {
code_at = Some(inner.path.clone());
attribute::set_once(
&mut code,
word,
&inner.path,
"`code` is declared more than once in `error(…)` — one failure renders under one \
heading",
errors,
);
}
Err(e) => refuse_value(&inner, e, errors),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `error(…)` — it takes `type = \"…\"` OR `message = \"…\"`, and `code = \
\"…\"` may head either",
&["type", "message", "code"],
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
match (ty, message) {
(Some(ty), _) => Some(DeclaredError::Rich { ty, code }),
(None, Some(message)) => Some(DeclaredError::Canned { message, code }),
(None, None) if shape_at.is_some() => None,
(None, None) => {
errors.push(code_at.as_ref().map_or_else(
|| syn::Error::new_spanned(&meta.path, ERROR_EMPTY),
|at| syn::Error::new_spanned(at, ERROR_CODE_ALONE),
));
None
}
}
}
fn refuse_value(meta: &syn::meta::ParseNestedMeta<'_>, error: syn::Error, errors: &mut Errors) {
errors.push(error);
attribute::skip_entry(meta);
}
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
const WHY: &str = "a mutation node takes no generic parameter — the declaration mints ONE command \
vocabulary and states ONE record for it, and a parameter is not a type until \
it is substituted";
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 mutation node must be a struct with named fields — a field's NAME is the command's name, \
the arm it mints in the vocabulary and the word the wire publishes, and a positional one \
has none of them",
)),
},
syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
&input.ident,
"`#[ingraph::mutation]` supports structs only — a node's FIELDS are its exchanges, and \
variants are a choice between things rather than a list of them",
)),
}
}
fn no_handler(field: &syn::Ident) -> String {
format!(
"`{field}` declares no `handler` — a field of a mutation node IS an exchange, and an exchange \
nobody runs is a command with no behaviour. Write `handler = \"path::to::fn\"` for the plain \
form, or `handler(path = \"…\", …)` where the rest of the signature has something to say"
)
}
const RENAME_WORD: &str = "`rename` is the word this exchange is PUBLISHED under, in a string literal — a schema name is \
not a Rust identifier, and the two grammars disagree about which words are legal";
const HANDLER_EMPTY: &str = "`handler` names nothing — write `handler = \"path::to::fn\"` for the plain form, or \
`handler(path = \"…\", …)` where the rest of the signature has something to say";
const HANDLER_NO_PATH: &str = "`handler(…)` names no `path` — the block IS the signature, and every other word in it describes \
a function that has to exist first";
const HANDLER_PATH: &str = "the function an exchange runs is named in a string literal — `handler = \"path::to::fn\"` or \
`handler(path = \"…\")` — because the word names a PATH this declaration cannot resolve and the \
compiler resolves where the expansion lands";
const CONTEXT_EMPTY: &str = "`context()` grants nothing — a handler that reaches for a resource writes \
`context(resource(\"…\"))`, and one that reaches for none omits the word, which is the signature \
with the request and nothing beside it";
const CONTEXT_LINE: &str = "a handler's `context(…)` is the RESOURCES it was granted, one `resource(\"…\")` line each — \
quoted, because the word names a type this declaration cannot resolve. Nothing else reaches a \
handler that way: the request arrives as the argument the exchange's own type named";
const ERROR_EMPTY: &str = "`error()` declares no failure — a field that CAN fail names how (`type = \"…\"` for an error the \
application owns, `message = \"…\"` for a sentence this declaration writes), and a field that \
cannot omits the word, which is the signature with no `Result` in it";
const ERROR_BOTH: &str = "`type` and `message` are the two shapes of ONE word — a failure is a type the application owns \
OR a sentence this declaration writes, and an exchange claiming both leaves its handler's return \
type undecided";
const ERROR_CODE_ALONE: &str = "`code` heads a failure and this one heads nothing — write it beside `type = \"…\"` or `message = \
\"…\"`, which are the two things there are to head. A field that cannot fail omits `error(…)` \
entirely";
const ERROR_TYPE: &str = "`error(type = \"…\")` names the error this exchange fails as — quoted, because the word names a \
TYPE this declaration cannot resolve and the compiler resolves where the expansion lands";
const ERROR_MESSAGE: &str =
"`error(message = \"…\")` is the whole sentence a canned failure renders, in a string literal";
const ERROR_CODE: &str =
"`error(code = \"…\")` is the heading a failure renders under, in a string literal";