use ingraph_codegen::error::{
Binding, BindingAt, ErrorModel, ErrorRoad, RESERVED, Rendering, VariantModel, VariantShape,
};
use crate::{attribute, errors::Errors, value};
#[cfg(test)]
mod tests;
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
road: ErrorRoad,
) -> syn::Result<ErrorModel> {
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
wordless(arguments, road, &mut errors);
concrete(&input.generics, road, &mut errors);
let variants = match arms(input, road) {
Ok(variants) => variants,
Err(terminal) => return Err(errors.seal(terminal)),
};
let mut minted: Vec<(String, syn::Ident)> = Vec::new();
let variants = variants
.iter()
.map(|variant| arm(variant, road, &mut minted, &mut errors))
.collect();
errors.into_result(ErrorModel {
name: input.ident.clone(),
road,
variants,
})
}
fn wordless(arguments: &[syn::Attribute], road: ErrorRoad, errors: &mut Errors) {
for written in arguments {
errors.push(syn::Error::new_spanned(
written,
format!(
"`#[ingraph::{word}]` takes no arguments — every word it reads is written on a VARIANT \
(`code` and `error`). It needs no `crate = \"…\"` either: the whole expansion names \
`::core` and nothing of this framework's",
word = road.word(),
),
));
}
}
fn concrete(generics: &syn::Generics, road: ErrorRoad, errors: &mut Errors) {
let why = format!(
"`#[ingraph::{word}]` takes no generic parameter — the expansion writes ONE `Display` over ONE \
type, and what a parameter would owe that impl (a bound per field a template renders) is a \
decision this macro would be making on an author's behalf. A generic error writes its own \
`Display`, which is exactly as legal",
word = road.word(),
);
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 arms(
input: &syn::DeriveInput,
road: ErrorRoad,
) -> syn::Result<&syn::punctuated::Punctuated<syn::Variant, syn::Token![,]>> {
match &input.data {
syn::Data::Enum(data) => Ok(&data.variants),
syn::Data::Struct(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
&input.ident,
format!(
"`#[ingraph::{word}]` supports enums only — an error type's VARIANTS are the ways it can \
fail, and each one is what a `code` names. A failure with exactly one shape is an enum \
with one variant, which costs a word and buys the vocabulary",
word = road.word(),
),
)),
}
}
fn arm(
variant: &syn::Variant,
road: ErrorRoad,
minted: &mut Vec<(String, syn::Ident)>,
errors: &mut Errors,
) -> VariantModel {
let mut code: Option<syn::LitStr> = None;
let mut template: Option<syn::LitStr> = None;
let mut code_at: Option<syn::Path> = None;
let mut template_at: Option<syn::Path> = None;
attribute::walk(&variant.attrs, errors, |meta, errors| {
if meta.path.is_ident("code") {
code_at = Some(meta.path.clone());
match value::literal(&meta, CODE_WORD) {
Ok(word) => attribute::set_once(
&mut code,
word,
&meta.path,
"`code` is declared more than once on this variant — one failure is recognised by one \
word",
errors,
),
Err(e) => refuse_value(&meta, e, errors),
}
return Ok(());
}
if meta.path.is_ident("error") {
template_at = Some(meta.path.clone());
match value::literal(&meta, ERROR_WORD) {
Ok(sentence) => attribute::set_once(
&mut template,
sentence,
&meta.path,
"`error` is declared more than once on this variant — one failure reads as one sentence",
errors,
),
Err(e) => refuse_value(&meta, e, errors),
}
return Ok(());
}
errors.push(attribute::unknown(
&meta,
"unknown entry on a leaf error's variant — it takes `code = \"…\"` (what a client matches on) \
and `error = \"…\"` (what a person reads), and nothing else",
&["code", "error"],
));
Ok(())
});
let code = match code {
Some(code) => {
screaming(&code, errors);
reserved(&code, errors);
unique(&code, &variant.ident, minted, errors);
code
}
None => {
if code_at.is_none() {
errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{arm}` declares no `code` — every variant of a leaf error carries one, because the \
code is what a client matches on and the head of everything the variant renders as. \
Write `#[ingraph(code = \"SOME_WORD\", error = \"…\")]`",
arm = variant.ident,
),
));
}
syn::LitStr::new("__INGRAPH_UNDECLARED", variant.ident.span())
}
};
let shape = match &variant.fields {
syn::Fields::Unit => VariantShape::Unit,
syn::Fields::Unnamed(_) => VariantShape::Tuple,
syn::Fields::Named(_) => VariantShape::Named,
};
let rendering = match &template {
Some(template) => rendering(&code, template, variant, road, errors),
None => {
if template_at.is_none() {
errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{arm}` declares no `error` — the word is the sentence this failure renders as, after \
its code and a colon. A variant with nothing to say to a person is a code with no \
message under it",
arm = variant.ident,
),
));
}
Rendering {
template: code.value(),
bound: Vec::new(),
}
}
};
VariantModel {
name: variant.ident.clone(),
code,
rendering,
shape,
}
}
fn screaming(code: &syn::LitStr, errors: &mut Errors) {
let word = code.value();
let legal = !word.is_empty()
&& word
.bytes()
.all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
&& word.as_bytes().first().is_some_and(u8::is_ascii_uppercase)
&& !word.ends_with('_');
if !legal {
errors.push(syn::Error::new_spanned(
code,
format!(
"`{word}` is not `SCREAMING_SNAKE_CASE` — a code is a machine-read constant, spelled in \
GraphQL's own convention for one: upper-case letters, digits and underscores, opening on a \
letter and not closing on an underscore"
),
));
}
}
fn reserved(code: &syn::LitStr, errors: &mut Errors) {
let word = code.value();
if RESERVED.contains(&word.as_str()) {
errors.push(syn::Error::new_spanned(
code,
format!(
"`{word}` is one of the framework's own wire codes and is reserved — a client matching on \
it is asking about a refusal this framework raises, and an application error wearing the \
word would answer that question wrongly. The code space below it is open: mint any other \
`SCREAMING_SNAKE_CASE` word"
),
));
}
}
fn unique(
code: &syn::LitStr,
arm: &syn::Ident,
minted: &mut Vec<(String, syn::Ident)>,
errors: &mut Errors,
) {
let word = code.value();
match minted.iter().find(|(held, _)| held == &word) {
Some((_, first)) => errors.push(syn::Error::new_spanned(
code,
format!(
"`{word}` is already the code of `{first}` — two variants under one word would tell a \
client one thing about two different mistakes, so a vocabulary is a contract only while it \
is injective"
),
)),
None => minted.push((word, arm.clone())),
}
}
fn rendering(
code: &syn::LitStr,
template: &syn::LitStr,
variant: &syn::Variant,
road: ErrorRoad,
errors: &mut Errors,
) -> Rendering {
let mut written = String::new();
let mut bound: Vec<Binding> = Vec::new();
let mut implicit = 0_usize;
let text = template.value();
let mut rest = text.as_str();
written.push_str(&code.value());
written.push_str(": ");
while let Some(at) = rest.find(['{', '}']) {
let (before, from) = rest.split_at(at);
written.push_str(before);
let mut characters = from.chars();
let opener = characters.next().unwrap_or('{');
if from.starts_with("{{") || from.starts_with("}}") {
written.push(opener);
written.push(opener);
rest = &from[2..];
continue;
}
if opener == '}' {
errors.push(syn::Error::new_spanned(template, UNPAIRED));
return Rendering {
template: written,
bound,
};
}
let Some(close) = from.find('}') else {
errors.push(syn::Error::new_spanned(template, UNCLOSED));
return Rendering {
template: written,
bound,
};
};
let inside = &from[1..close];
let (named, spec) = inside
.split_once(':')
.map_or((inside, ""), |(named, spec)| (named, spec));
if let Some(at) = placeholder(named, variant, template, road, &mut implicit, errors) {
let held = hold(&at, &mut bound);
written.push('{');
written.push_str(&held.to_string());
if !spec.is_empty() {
written.push(':');
written.push_str(spec);
}
written.push('}');
}
rest = &from[close + 1..];
}
written.push_str(rest);
Rendering {
template: written,
bound,
}
}
fn placeholder(
named: &str,
variant: &syn::Variant,
template: &syn::LitStr,
road: ErrorRoad,
implicit: &mut usize,
errors: &mut Errors,
) -> Option<BindingAt> {
let arity = variant.fields.len();
if named.is_empty() || named.bytes().all(|byte| byte.is_ascii_digit()) {
let at = if named.is_empty() {
let at = *implicit;
*implicit += 1;
at
} else {
named.parse::<usize>().ok()?
};
if !matches!(variant.fields, syn::Fields::Unnamed(_)) || at >= arity {
errors.push(syn::Error::new_spanned(
template,
format!(
"`{{{named}}}` names field {at} of `{arm}`, which has {arity} — a positional placeholder \
reads a TUPLE variant's fields, and a variant with named fields is read by those names",
arm = variant.ident,
),
));
return None;
}
return Some(BindingAt::Position(at));
}
let held = variant
.fields
.iter()
.find_map(|field| field.ident.clone().filter(|ident| ident == named));
if held.is_none() {
errors.push(syn::Error::new_spanned(
template,
format!(
"`{arm}` has no field called `{named}` — a leaf error's template reads the variant's own \
fields, by name where it has them and by position (`{{0}}`) where it does not. \
`#[ingraph::{word}]` checks that here rather than leaving it to fail inside the expansion",
arm = variant.ident,
word = road.word(),
),
));
}
held.map(BindingAt::Named)
}
fn hold(at: &BindingAt, bound: &mut Vec<Binding>) -> syn::Ident {
if let Some(held) = bound
.iter()
.find(|binding| &binding.at == at)
.map(|binding| binding.held.clone())
{
return held;
}
let held = match at {
BindingAt::Position(position) => quote::format_ident!("__ingraph_at_{position}"),
BindingAt::Named(name) => quote::format_ident!("__ingraph_named_{name}"),
};
bound.push(Binding {
held: held.clone(),
at: at.clone(),
});
held
}
fn refuse_value(meta: &syn::meta::ParseNestedMeta<'_>, error: syn::Error, errors: &mut Errors) {
errors.push(error);
attribute::skip_entry(meta);
}
const CODE_WORD: &str =
"`code = \"…\"` is the word a client matches this failure by, in a string literal";
const ERROR_WORD: &str =
"`error = \"…\"` is the sentence this failure renders as, in a string literal";
const UNPAIRED: &str = "this template holds a `}` that opens nothing — a literal brace is written \
`}}`, exactly as it is in any format string";
const UNCLOSED: &str = "this template holds a `{` that is never closed — a placeholder is \
`{0}`, `{name}` or `{}`, and a literal brace is written `{{`";