use ingraph_codegen::{
model::GraphqlKind,
union::{UnionInput, UnionModel, UnionOutput, UnionSkin},
};
use crate::{
attribute,
errors::Errors,
members::{self, Family},
value,
};
#[cfg(test)]
mod graphql_tests;
#[cfg(test)]
mod tests;
const FAMILY: Family = Family {
derive: "#[derive(ingraph::Union)]",
noun: "union",
possessive: "A union's",
not_an_enum: "a union IS its member set, one variant per member, and a struct declares no \
alternatives at all",
empty: "GraphQL's own law is that a union type must include ONE OR MORE unique member types, and \
Rust's is that an enum with no variants has no value to be",
several: "A union is a choice BETWEEN member types, so an alternative holding two of them is a \
member type nobody declared; the wire shape a declared union renders as takes a \
single-value tuple variant, at both positions a schema has for one. Declare the pair \
as a type of its own and carry that",
positional: "A variant's one member is the whole of what it holds, so there is nothing for a \
field name to tell it apart from, and the wire shape a declared union renders as \
takes a single-value tuple variant.",
variant_entry: "a variant takes none. A member is named by the TYPE it carries, and nothing in \
this half spells a word for one",
duplicate: "GraphQL's law is that a union type must include one or more UNIQUE member types, so \
a schema built from this would name that member twice and no query could say which \
variant it meant",
generic: "a union's members are the TYPES its variants carry, and a parameter is not one until \
it is substituted; the uniqueness a member set must have cannot be decided before \
that, since `Pick<A, B>` is one member twice at `A = B`",
};
const POSITIONS: [&str; 2] = ["output", "input"];
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<UnionModel> {
let mut errors = Errors::default();
let Options {
krate,
error,
graphql,
} = options(&input.attrs, &mut errors);
members::concrete(&FAMILY, &input.generics, &mut errors);
let members = match members::members(&FAMILY, input, &mut errors) {
Ok(members) => members,
Err(terminal) => return Err(errors.seal(terminal)),
};
members::collisions(&FAMILY, &members, &mut errors);
let model = UnionModel {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
vis: input.vis.clone(),
name: input.ident.clone(),
members,
error,
graphql,
};
emitted_names(&model, &mut errors);
errors.into_result(model)
}
#[derive(Default)]
struct Options {
krate: Option<syn::Path>,
error: Option<syn::Ident>,
graphql: Vec<UnionSkin>,
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut options = Options::default();
let mut graphql_at: Option<syn::Path> = None;
attribute::walk(attrs, errors, |meta, errors| {
if let Some(walked) = members::refusal_knob(&meta, &mut options.error, errors) {
return walked;
}
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.graphql, errors);
}
errors.push(attribute::unknown(
&meta,
"unknown entry in `#[ingraph(…)]` on a union — it takes `unwrap_error(rename = \"…\")`, \
`graphql(…)` and `crate = \"…\"`. A union declares no storage and no words: its members are \
TYPES, and what a declaration adds to them is which SCHEMA POSITIONS the union is rendered at",
&["unwrap_error", "graphql", "crate"],
));
Ok(())
});
options
}
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";
fn backends(
meta: &syn::meta::ParseNestedMeta<'_>,
graphql: &mut Vec<UnionSkin>,
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.iter().any(|skin| skin.kind == 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(positions(&inner, kind, errors));
Ok(())
});
if graphql.is_empty() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`graphql` names no backend — write `graphql({first}(output))`. Without the block a union \
keeps its whole Rust surface — the member questions, the unwrap family and the refusal are \
all there — 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,
errors: &mut Errors,
) -> UnionSkin {
let mut output: Option<syn::Path> = None;
let mut input: Option<syn::Path> = None;
let mut rename: Option<syn::LitStr> = None;
let mut output_rename: Option<syn::LitStr> = None;
let walked = attribute::options(meta, |entry| {
if entry.path.is_ident("output") {
attribute::set_once(
&mut output,
entry.path.clone(),
&entry.path,
&declared_twice("output"),
errors,
);
return attribute::options(&entry, |option| {
if option.path.is_ident("rename") {
return face_name(
&option,
&mut output_rename,
"`rename` is declared more than once in `output(…)` — one option, one value",
errors,
);
}
errors.push(attribute::unknown(
&option,
"unknown entry in `output(…)` — it takes `rename = \"…\"` and nothing else. What this \
face publishes is the union's MEMBERS, which the declaration already named, so the one \
thing left to say is what a client calls the union itself",
&["rename"],
));
Ok(())
});
}
if entry.path.is_ident("input") {
attribute::set_once(
&mut input,
entry.path.clone(),
&entry.path,
&declared_twice("input"),
errors,
);
return attribute::options(&entry, |option| {
if option.path.is_ident("rename") {
return face_name(
&option,
&mut rename,
"`rename` is declared more than once in `input(…)` — one option, one value",
errors,
);
}
errors.push(attribute::unknown(
&option,
"unknown entry in `input(…)` — it takes `rename = \"…\"` and nothing else",
&["rename"],
));
Ok(())
});
}
errors.push(attribute::unknown(
&entry,
"unknown entry in a union's backend block — it takes `output` and `input`, the two positions \
a schema has for a declared union, and nothing else",
&POSITIONS,
));
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
if output.is_none() && input.is_none() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{kind}` dresses this union for no position — write `{kind}(output)`, `{kind}(input)` or \
both. A backend block naming neither is a face nothing renders, and an entry nobody reads \
is a rule its author believes they declared",
kind = kind.as_str(),
),
));
}
UnionSkin {
kind,
output: output.is_some().then_some(UnionOutput {
rename: output_rename,
}),
input: input.is_some().then_some(UnionInput { rename }),
}
}
fn face_name(
option: &syn::meta::ParseNestedMeta<'_>,
slot: &mut Option<syn::LitStr>,
twice: &str,
errors: &mut Errors,
) -> syn::Result<()> {
match value::literal(option, attribute::SDL_NAME) {
Ok(word) => {
crate::wire::refuse_invalid_name(&word.value(), &word, errors);
attribute::set_once(slot, word, &option.path, twice, errors);
}
Err(e) => errors.push(e),
}
Ok(())
}
fn declared_twice(position: &str) -> String {
format!(
"`{position}` is declared more than once — one word per position, and a schema renders a union \
at each of them once"
)
}
fn emitted_names(model: &UnionModel, errors: &mut Errors) {
if let Some(at) = model.error.as_ref()
&& model.error() == model.name
{
errors.push(syn::Error::new(
at.span(),
format!(
"the refusal type would be named `{name}`, which is already the union's own name — the \
expansion declares it beside the enum, so it needs a name of its own",
name = model.name
),
));
}
for skin in &model.graphql {
let Some(at) = skin
.input
.as_ref()
.and_then(|input| input.rename.as_ref())
.or_else(|| {
skin
.output
.as_ref()
.and_then(|output| output.rename.as_ref())
})
else {
continue;
};
if skin.output.is_none() || skin.input_sdl(&model.name) != skin.output_sdl(&model.name) {
continue;
}
errors.push(syn::Error::new(
at.span(),
format!(
"the input object would be called `{name}`, which is what this union's OUTPUT face already \
publishes — a schema has ONE namespace for type names, so the two faces of one union need \
two of them",
name = skin.output_sdl(&model.name)
),
));
}
}