use ingraph_codegen::{
delegate::{Delegate, DelegateSkin},
model::GraphqlKind,
};
use syn::ext::IdentExt as _;
use crate::{attribute, errors::Errors, value, wire};
pub(crate) const WORD: &str = "delegate";
pub(crate) const ON: &str = "on";
const SIGNATURE: &str = "signature";
const SELF: &str = "self";
const FULL_FORM: &str = "`delegate(…)` is written in ONE of two spellings and never half of each. \
The SHORTHAND is a list of bare signatures — \
`delegate(fn m(&self) -> T, fn n(&self))` — and it says nothing but the \
methods. The FULL FORM names every property of ONE entry: \
`delegate(signature = fn m(&self) -> T, on = self)`, with any \
`#[graphql(…)]` leading it exactly as it leads a bare one. A bare \
signature and a named property in one block is neither. Nothing is lost by \
the split: the seat ACCUMULATES, so an entry that needs a property takes a \
`delegate(…)` block of its own beside the shorthand list";
pub(crate) struct Delegation<'a> {
pub receiver: &'a str,
pub exclusive: &'a str,
}
pub(crate) fn block(
meta: &syn::meta::ParseNestedMeta<'_>,
delegates: &mut Vec<Delegate>,
tier: &Delegation<'_>,
errors: &mut Errors,
) -> syn::Result<()> {
let content;
syn::parenthesized!(content in meta.input);
if opens_a_property(&content) {
let (attrs, signature, on_self) = full(&content, errors)?;
delegated(&attrs, signature, on_self, delegates, tier, errors);
return Ok(());
}
let written = content.parse_terminated(entry, syn::Token![,])?;
for (attrs, signature) in written {
delegated(&attrs, signature, None, delegates, tier, errors);
}
Ok(())
}
fn opens_a_property(content: syn::parse::ParseStream<'_>) -> bool {
let ahead = content.fork();
ahead.call(syn::Attribute::parse_outer).is_ok() && names_a_property(&ahead)
}
fn names_a_property(input: syn::parse::ParseStream<'_>) -> bool {
input.peek(syn::Ident) && input.peek2(syn::Token![=])
}
fn full(
content: syn::parse::ParseStream<'_>,
errors: &mut Errors,
) -> syn::Result<(Vec<syn::Attribute>, syn::Signature, Option<syn::Ident>)> {
let opens = content.span();
let attrs = content.call(syn::Attribute::parse_outer)?;
let mut signature: Option<syn::Signature> = None;
let mut on: Option<syn::Ident> = None;
let mut seen: Vec<syn::Ident> = Vec::new();
while !content.is_empty() {
if !names_a_property(content) {
return Err(syn::Error::new(content.span(), FULL_FORM));
}
let word = content.parse::<syn::Ident>()?;
content.parse::<syn::Token![=]>()?;
let twice = seen.iter().any(|first| first == &word);
if twice {
errors.push(syn::Error::new_spanned(
&word,
format!(
"`{word}` is declared more than once in `delegate(…)` — one entry answers each property \
once, and a second answer to one question is not a second entry: write another \
`delegate(…)` block, which the seat accumulates onto this one"
),
));
}
seen.push(word.clone());
if word == SIGNATURE {
let restated = content.parse::<syn::Signature>()?;
if !twice {
signature = Some(restated);
}
} else if word == ON {
let target = target(content)?;
if !twice {
if target == SELF {
on = Some(target);
} else {
errors.push(syn::Error::new_spanned(&target, off_the_roster(&target)));
}
}
} else {
errors.push(syn::Error::new_spanned(
&word,
format!(
"unknown property in `delegate(…)` — the FULL FORM names the entry's SIGNATURE and where \
its method LIVES, and nothing else. What a client calls a published method is the \
entry's own `#[graphql(<backend>(rename = \"…\"))]`, which LEADS the properties rather \
than sitting among them{suggestion}",
suggestion = crate::suggest::did_you_mean(&word.unraw().to_string(), [SIGNATURE, ON]),
),
));
skip_value(content);
}
if content.is_empty() {
break;
}
content.parse::<syn::Token![,]>()?;
}
let Some(signature) = signature else {
return Err(syn::Error::new(
opens,
format!("`delegate(…)` names no method here — every entry restates one. {FULL_FORM}"),
));
};
Ok((attrs, signature, on))
}
fn skip_value(content: syn::parse::ParseStream<'_>) {
while !content.is_empty() && !content.peek(syn::Token![,]) {
if content.parse::<proc_macro2::TokenTree>().is_err() {
return;
}
}
}
fn target(content: syn::parse::ParseStream<'_>) -> syn::Result<syn::Ident> {
let at = content.span();
content
.call(syn::Ident::parse_any)
.map_err(|_| syn::Error::new(at, off_the_roster_shape()))
}
fn off_the_roster(target: &syn::Ident) -> String {
format!(
"`{ON} = {target}` names no target this seat has. {}",
off_the_roster_shape()
)
}
fn off_the_roster_shape() -> String {
format!(
"`{ON}` takes `{SELF}`, and `{SELF}` is the whole of it: the word says the entry's method is the \
DECLARED type's own, so no forwarding half is minted for it. A place other than that type for \
the call to land — the wrapped value under a name, the materialized upstream, an intermediate a \
wrapper derefs through — is a door and not a plan, and none of them has a consumer yet. Write \
`{ON} = {SELF}`, or drop the property: an entry without one forwards exactly as it did"
)
}
pub(crate) fn entry(
input: syn::parse::ParseStream<'_>,
) -> syn::Result<(Vec<syn::Attribute>, syn::Signature)> {
let attrs = input.call(syn::Attribute::parse_outer)?;
if names_a_property(input) {
return Err(syn::Error::new(input.span(), FULL_FORM));
}
let signature = input.parse::<syn::Signature>()?;
Ok((attrs, signature))
}
fn delegated(
attrs: &[syn::Attribute],
signature: syn::Signature,
on_self: Option<syn::Ident>,
delegates: &mut Vec<Delegate>,
tier: &Delegation<'_>,
errors: &mut Errors,
) {
let Some(exclusive) = receiver(&signature, tier, errors) else {
return;
};
let wire = published(attrs, &signature, exclusive, tier, errors);
delegates.push(Delegate {
signature,
exclusive,
wire,
on_self,
});
}
fn receiver(
signature: &syn::Signature,
tier: &Delegation<'_>,
errors: &mut Errors,
) -> Option<bool> {
let why = tier.receiver;
match signature.inputs.first() {
Some(syn::FnArg::Receiver(syn::Receiver {
kind: syn::ReceiverKind::Reference(_, _, exclusive),
..
})) => Some(exclusive.is_some()),
Some(argument) => {
errors.push(syn::Error::new_spanned(argument, why));
None
}
None => {
errors.push(syn::Error::new_spanned(&signature.ident, why));
None
}
}
}
fn published(
attrs: &[syn::Attribute],
signature: &syn::Signature,
exclusive: bool,
tier: &Delegation<'_>,
errors: &mut Errors,
) -> Vec<DelegateSkin> {
let mut wire = Vec::new();
for attr in attrs {
if !attr.path().is_ident("graphql") {
errors.push(syn::Error::new_spanned(
attr,
"a `delegate(…)` entry takes one attribute — `#[graphql(…)]`, which publishes the method — \
and nothing else. The entry is a SIGNATURE rather than an item: it declares no code for \
another attribute to be about, and the emitted method's own attributes are this \
expansion's",
));
continue;
}
if matches!(attr.meta, syn::Meta::Path(_)) {
errors.push(syn::Error::new_spanned(attr, graphql_names_no_backend()));
continue;
}
let mut written = 0_usize;
let walked = attr.parse_nested_meta(|inner| {
written += 1;
let Some(kind) = crate::parse::graphql_kind(&inner.path) else {
errors.push(attribute::unknown(
&inner,
"unknown backend in `#[graphql(…)]` — a published method is one backend's field, and a \
word naming none of them names no face",
&GraphqlKind::ALL.map(GraphqlKind::as_str),
));
attribute::skip_entry(&inner);
return Ok(());
};
if wire.iter().any(|skin: &DelegateSkin| skin.kind == kind) {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once — one word per backend, because a backend \
publishes this method once and a second word could only re-describe it",
kind = kind.as_str(),
),
));
attribute::skip_entry(&inner);
return Ok(());
}
wire.push(DelegateSkin {
kind,
rename: renamed(&inner, kind, errors),
});
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
if written == 0 {
errors.push(syn::Error::new_spanned(attr, graphql_names_no_backend()));
}
}
if exclusive && !wire.is_empty() {
errors.push(syn::Error::new_spanned(&signature.ident, tier.exclusive));
wire.clear();
}
wire
}
fn graphql_names_no_backend() -> String {
format!(
"`#[graphql]` names no backend — write `#[graphql({first})]`. Without a backend word the \
attribute publishes nothing, and an entry nobody reads is a rule its author believes they \
declared",
first = GraphqlKind::ALL[0].as_str(),
)
}
fn renamed(
meta: &syn::meta::ParseNestedMeta<'_>,
kind: GraphqlKind,
errors: &mut Errors,
) -> Option<syn::LitStr> {
let mut rename = None;
let walked = attribute::options(meta, |option| {
if option.path.is_ident("rename") {
match value::literal(&option, attribute::SDL_NAME) {
Ok(word) => {
wire::refuse_invalid_name(&word.value(), &word, errors);
attribute::set_once(
&mut rename,
word,
&option.path,
"`rename` is declared more than once — one option, one value",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&option,
&format!(
"unknown entry in `{kind}(…)` on a delegated method — it takes `rename = \"…\"` and nothing \
else. What a published method's field IS comes from the signature, so the one thing left \
to say is what a client calls it",
kind = kind.as_str(),
),
&["rename"],
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
rename
}