use std::collections::BTreeMap;
use ingraph_codegen::{
delegate::Delegate,
enumeration::{
EnumModel, EnumVariant, Escape, IntegerWidth, Namespace, Remote, StorageForm, TEXT_FIELD,
},
method::{Emitted, Origin},
model::GraphqlKind,
};
use crate::{
attribute::{self, set_once},
errors::Errors,
value, wire,
};
#[cfg(test)]
mod tests;
const WORD: &str = "#[derive(ingraph::Enum)]";
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 REMOTE_PATH: &str = "`#[ingraph(remote = \"…\")]` must be a path to the vocabulary this one \
mirrors, in a string literal";
const REMOTE_ONCE: &str =
"`remote` is declared more than once — one declaration mirrors one vocabulary";
const TOTAL_DOOR: &str = "from";
const REFUSABLE_DOOR: &str = "try_from";
const ESCAPE_SHAPE: &str = "`other` is a MARKER, and where it carries anything it carries a BLOCK — `other(from = \"…\")` or \
`other(try_from = \"…\")`, naming the gate a word this mirror does not name goes through. A bare \
`other` says the upstream's own parse is total, and `other = \"…\"` says nothing this grammar \
reads";
const EMPTY_DOOR: &str = "`other(…)` names the GATE a word this mirror does not name goes through — `from = \"…\"` where \
that gate cannot refuse, `try_from = \"…\"` where it can. An empty block names neither, and a \
BARE `other` is already how a declaration says the upstream's own parse is total";
const UNKNOWN_DOOR: &str = "unknown entry in `other(…)` — an escape opens ONE door, named `from = \"…\"` where the gate \
cannot refuse or `try_from = \"…\"` where it can";
const ESCAPE_ONCE: &str = "`other` is declared more than once on this variant";
const NO_GATE_WITHOUT_AN_UPSTREAM: &str = "`other(…)` names the gate a word goes through to become an UPSTREAM value, and this declaration \
has no upstream — it mirrors nothing, so its words are its own. Its door is the roster walked \
under the framework's fold, which is TOTAL by construction: a word no member answers to becomes \
this escape, `FromStr::Err` is `core::convert::Infallible`, and there is no refusal for a gate \
to be the way around. A BARE `#[ingraph(other)]` is the whole marker here; \
`#[ingraph(remote = \"…\")]` on the enum is what gives the cells something to be a gate ONTO";
const DOOR_PATH: &str = "`other(from = \"…\")` and `other(try_from = \"…\")` take a PATH to the gate function, in a \
string literal — `\"upstream::Codec::other\"` and the like. The gate is called where the \
upstream's own parse turned a word away, and a name the upstream has not got is `E0599` at this \
token";
#[derive(Clone, Copy, PartialEq, Eq)]
struct Mode {
mirrors: bool,
open: bool,
}
impl Mode {
const fn stores_a_word(self) -> bool {
self.mirrors || self.open
}
}
fn declares_an_escape(input: &syn::DeriveInput) -> bool {
let syn::Data::Enum(data) = &input.data else {
return false;
};
let mut found = false;
for variant in &data.variants {
for attr in variant
.attrs
.iter()
.filter(|attr| attr.path().is_ident("ingraph"))
{
let _ = attr.parse_nested_meta(|meta| {
found |= meta.path.is_ident("other");
attribute::skip_entry(&meta);
Ok(())
});
}
}
found
}
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<EnumModel> {
let mut errors = Errors::default();
let Options {
krate,
forms,
faces,
wire_name,
error,
remote,
delegates,
delegate,
} = options(&input.attrs, &mut errors);
let mode = Mode {
mirrors: remote.is_some(),
open: declares_an_escape(input),
};
let width = (!mode.stores_a_word())
.then(|| width(&input.attrs, &forms, &mut errors))
.flatten();
concrete(&input.generics, &mut errors);
let variants = match variants(input, &forms, mode, &mut errors) {
Ok(variants) => variants,
Err(terminal) => return Err(errors.seal(terminal)),
};
one_word_everywhere(mode, &faces, &mut errors);
escapes(mode, &variants, &mut errors);
if mode.mirrors {
refuse_a_waived_entry_that_publishes_nothing(&delegates, &mut errors);
} else {
borrowed(delegate.as_ref(), &mut errors);
}
the_refusal_a_parse_answers_with(mode, &variants, error.as_ref(), &mut errors);
collisions(&variants, &forms, mode, &mut errors);
match wire_name.as_ref() {
Some(word) => wire::refuse_invalid_name(&word.value(), word, &mut errors),
None => wire::refuse_invalid_name(
&syn::ext::IdentExt::unraw(&input.ident).to_string(),
&input.ident,
&mut errors,
),
}
let model = EnumModel {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
vis: input.vis.clone(),
name: input.ident.clone(),
width,
variants,
forms,
wire_name: wire_name.map(|word| word.value()),
error,
remote: remote.map(|path| Remote { path, delegates }),
};
refusal_name(&model, &mut errors);
published_fields(&model, &mut errors);
emitted_methods(&model, &mut errors);
errors.into_result(model)
}
struct Options {
krate: Option<syn::Path>,
forms: BTreeMap<Namespace, StorageForm>,
faces: Vec<syn::Path>,
wire_name: Option<syn::LitStr>,
error: Option<syn::Ident>,
remote: Option<syn::Path>,
delegates: Vec<Delegate>,
delegate: Option<syn::Path>,
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut krate = None;
let mut forms = BTreeMap::new();
let mut faces = Vec::new();
let mut wire_name = None;
let mut error = None;
let mut remote = None;
let mut delegates = Vec::new();
let mut delegate = None;
let mut seen: BTreeMap<Namespace, ()> = BTreeMap::new();
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
Ok(path) => set_once(&mut krate, path, &meta.path, CRATE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("remote") {
match value::parse_literal::<syn::Path>(&meta, REMOTE_PATH) {
Ok(path) => set_once(&mut remote, path, &meta.path, REMOTE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident(crate::delegate::WORD) {
if delegate.is_none() {
delegate = Some(meta.path.clone());
}
return crate::delegate::block(&meta, &mut delegates, &MIRROR, errors);
}
if meta.path.is_ident("error") {
return attribute::rename_block(&meta, &mut error, "error", errors);
}
if let Some(namespace) = namespace(&meta.path) {
if seen.insert(namespace, ()).is_some() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{}(…)` is declared more than once — one declaration names one form for one face",
namespace.as_str()
),
));
}
let mut form = None;
let mut about_a_form = !attribute::has_block(&meta) || attribute::empty_group(&meta);
let walked = attribute::options(&meta, |inner| {
if inner.path.is_ident("rename") {
return the_wire_name(&inner, namespace, &mut wire_name, errors);
}
about_a_form = true;
match this_form(&inner.path) {
Some(named) => set_once(
&mut form,
named,
&inner.path,
"a face takes ONE form — a second is a second answer to one question",
errors,
),
None => errors.push(attribute::unknown(
&inner,
&format!(
"unknown entry in `{}(…)` — a face takes one of {}{}",
namespace.as_str(),
listed(&StorageForm::ALL.map(StorageForm::as_str)),
if namespace == Namespace::Graphql {
", and `rename = \"…\"`, the name a SCHEMA publishes this vocabulary under"
} else {
""
}
),
&if namespace == Namespace::Graphql {
StorageForm::ALL
.map(StorageForm::as_str)
.into_iter()
.chain(core::iter::once("rename"))
.collect::<Vec<_>>()
} else {
StorageForm::ALL.map(StorageForm::as_str).to_vec()
},
)),
}
Ok(())
});
if about_a_form {
faces.push(meta.path.clone());
}
if let Some(form) = form {
forms.insert(namespace, form);
}
return walked;
}
errors.push(attribute::unknown(
&meta,
&format!(
"unknown entry in `#[ingraph(…)]` on an enum — a vocabulary takes `crate = \"…\"`, \
`remote = \"…\"`, `delegate(fn …)`, `error(rename = \"…\")` and one block per face, {}. \
The wire face's block takes a `rename = \"…\"` beside its form, which is what a SCHEMA \
calls this vocabulary",
listed(&Namespace::ALL.map(Namespace::as_str))
),
&["crate", "remote", "delegate", "error"]
.into_iter()
.chain(Namespace::ALL.map(Namespace::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
Options {
krate,
forms,
faces,
wire_name,
error,
remote,
delegates,
delegate,
}
}
const MIRROR: crate::delegate::Delegation<'static> = crate::delegate::Delegation {
receiver: "a delegated method BORROWS its receiver — `&self` forwards onto a materialized \
upstream value, and `&mut self` writes the mutation back through this mirror's own \
`From`. There is no `self` for one to consume, the mirror being the caller's rather \
than the upstream's, and a signature with no receiver has nothing to forward from",
exclusive: "a published delegate takes `&self` — a resolver READS, and a `&mut self` entry's body \
materializes the upstream value, mutates it and writes a NEW value back into the row \
it was called on. Drop the `#[graphql(…)]` to keep the method, or take the receiver \
by shared reference to keep the field",
};
fn the_wire_name(
option: &syn::meta::ParseNestedMeta<'_>,
namespace: Namespace,
slot: &mut Option<syn::LitStr>,
errors: &mut Errors,
) -> syn::Result<()> {
if namespace != Namespace::Graphql {
errors.push(attribute::named(
option,
format!(
"`{ns}` STORES this vocabulary and does not name it — a column holds one member at a time, \
so a face over a database has a per-variant WORD and no type name of its own. What this \
face's `rename` moves is a VARIANT's stored word, written on the variant: \
`#[ingraph({ns}(rename = \"…\"))]`. The name a SCHEMA publishes the vocabulary under is \
`graphql(rename = \"…\")`, one face over",
ns = namespace.as_str(),
),
));
attribute::skip_entry(option);
return Ok(());
}
match value::literal(option, attribute::SDL_NAME) {
Ok(word) => set_once(
slot,
word,
&option.path,
"`rename` is declared more than once in `graphql(…)` — one declaration has one schema name",
errors,
),
Err(e) => errors.push(e),
}
Ok(())
}
fn namespace(path: &syn::Path) -> Option<Namespace> {
Namespace::ALL
.into_iter()
.find(|namespace| path.is_ident(namespace.as_str()))
}
fn this_form(path: &syn::Path) -> Option<StorageForm> {
StorageForm::ALL
.into_iter()
.find(|form| path.is_ident(form.as_str()))
}
pub(crate) fn listed(words: &[&str]) -> String {
words
.iter()
.map(|word| format!("`{word}`"))
.collect::<Vec<_>>()
.join(", ")
}
fn width(
attrs: &[syn::Attribute],
forms: &BTreeMap<Namespace, StorageForm>,
errors: &mut Errors,
) -> Option<IntegerWidth> {
let stored_as_a_number = Namespace::ALL.into_iter().any(|namespace| {
forms
.get(&namespace)
.copied()
.unwrap_or_else(|| namespace.default_form())
== StorageForm::Integer
});
let mut width = None;
for attr in attrs.iter().filter(|attr| attr.path().is_ident("repr")) {
let _ = attr.parse_nested_meta(|meta| {
let Some(word) = meta.path.get_ident().map(ToString::to_string) else {
return Ok(());
};
if !IntegerWidth::is_repr_word(&word) {
attribute::skip_entry(&meta);
return Ok(());
}
match IntegerWidth::named(&word) {
Some(named) => width = Some(named),
None if stored_as_a_number => errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`#[repr({word})]` is not a width a vocabulary can be stored at — the framework's \
carrier table covers {}, and no wider: MySQL alone has a native `u64`, no dialect \
carries a 128-bit integer, and `usize`/`isize` name no fixed width for a column to \
be. Declare a width every dialect holds, or give each face the `text` form",
listed(&IntegerWidth::ALL.map(IntegerWidth::as_str))
),
)),
None => {}
}
Ok(())
});
}
width
}
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
const WHY: &str = "generic vocabularies are not supported — every row this derive emits names \
the enum itself, and a parameter has no type until it is substituted; a unit \
variant has no field to carry one in either";
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 variants(
input: &syn::DeriveInput,
forms: &BTreeMap<Namespace, StorageForm>,
mode: Mode,
errors: &mut Errors,
) -> syn::Result<Vec<EnumVariant>> {
let syn::Data::Enum(data) = &input.data else {
return Err(syn::Error::new_spanned(
&input.ident,
if mode.mirrors {
format!(
"`{WORD}` with `remote = \"…\"` supports enums only — a mirror RESTATES its upstream's \
variants, one for one, and a struct has none to restate"
)
} else {
format!(
"`{WORD}` supports enums only — a vocabulary is a closed set of names, and a struct \
declares no such set"
)
},
));
};
if data.variants.is_empty() {
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"an enum with no variants declares no vocabulary — there is no value to store, no member \
to ask for, and the emitted filter would guard a column no row could ever hold. A schema \
could not carry it either: GraphQL's own rule is that *an Enum type must define one or \
more unique enum values*, so `{WORD}` has nothing to emit for one"
),
));
}
let mut parsed = Vec::with_capacity(data.variants.len());
for variant in &data.variants {
let mut read = names(variant, forms, mode, errors);
match (&variant.fields, read.escape.is_some()) {
(syn::Fields::Unit, false) => {}
(syn::Fields::Unnamed(fields), true) if fields.unnamed.len() == 1 => {
read.carrier = Some(fields.unnamed[0].ty.clone());
}
(_, true) => errors.push(syn::Error::new_spanned(
&variant.ident,
if mode.mirrors {
format!(
"`{}` is marked `#[ingraph(other)]` and must carry EXACTLY ONE unnamed field — the \
WORD of an upstream value this mirror does not name. Any text carrier that is \
`From<&str>` and `AsRef<str>` holds one, `Utf8Bytes` and `SmolStr` among them, and the \
compiler names the obligation at the field's own type",
variant.ident
)
} else {
format!(
"`{}` is marked `#[ingraph(other)]` and must carry EXACTLY ONE unnamed field — the \
WORD this vocabulary does not name. Any text carrier that is `From<&str>` and \
`AsRef<str>` holds one, `Utf8Bytes` and `SmolStr` among them, and the compiler names \
the obligation at the field's own type",
variant.ident
)
},
)),
(_, false) => errors.push(syn::Error::new_spanned(
&variant.ident,
match (mode.mirrors, mode.open) {
(false, false) => format!(
"`{WORD}` takes UNIT variants only — `{}` carries data. A vocabulary this crate \
declares is a CLOSED SET: the filter is membership over the variants, the stored form \
is one name or one discriminant, and a wire value is one word in a document — a \
payload fits none of the three. TWO ways out, and which one is right depends on what \
the payload IS: a WORD this vocabulary does not name is the ESCAPE, and \
`#[ingraph(other)]` on this variant is what says so — it opens the vocabulary, and the \
field becomes the word it carries. Anything else is a UNION, and \
`#[derive(ingraph::Union)]` is the word for one",
variant.ident
),
(false, true) => format!(
"`{}` carries data, and this vocabulary already has its escape. A roster's members are \
NAMES — the stored form is one word, the filter is membership over them and the list a \
client reads is `VARIANTS` — so the one variant that may carry anything is the \
`#[ingraph(other)]` one, and what it carries is the word this vocabulary does not \
name",
variant.ident
),
(true, _) => format!(
"`{}` carries data. A mirror RESTATES its upstream's variants — IDENTIFIERS, nothing \
else, the words being the upstream's own — so the one variant that may carry anything \
is the `#[ingraph(other)]` escape, and what it carries is a word",
variant.ident
),
},
)),
}
parsed.push(read);
}
Ok(parsed)
}
fn names(
variant: &syn::Variant,
forms: &BTreeMap<Namespace, StorageForm>,
mode: Mode,
errors: &mut Errors,
) -> EnumVariant {
let mut rename = None;
let mut upstream = None;
let mut escape: Option<(syn::Path, Escape)> = None;
let mut names: BTreeMap<Namespace, String> = BTreeMap::new();
let mut seen: BTreeMap<Namespace, ()> = BTreeMap::new();
attribute::walk(&variant.attrs, errors, |meta, errors| {
if meta.path.is_ident("rename") {
if mode.mirrors {
match value::parse_literal::<syn::Ident>(
&meta,
"`rename = \"…\"` must be an identifier, in a string literal — on a mirror it names the \
UPSTREAM variant this one restates, not a word: the words are the upstream's own",
) {
Ok(named) => set_once(
&mut upstream,
named,
&meta.path,
"`rename` is declared more than once — one variant restates one upstream variant",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
match value::literal(
&meta,
"`rename = \"…\"` must be a string literal — the word every face defaults to",
) {
Ok(word) => set_once(
&mut rename,
word.value(),
&meta.path,
"`rename` is declared more than once — one declaration names one canonical word",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("other") {
if attribute::has_value(&meta) {
errors.push(attribute::named(&meta, ESCAPE_SHAPE.to_owned()));
return Ok(());
}
if !mode.mirrors && attribute::has_block(&meta) {
errors.push(attribute::named(
&meta,
NO_GATE_WITHOUT_AN_UPSTREAM.to_owned(),
));
set_once(
&mut escape,
(meta.path.clone(), Escape::Total),
&meta.path,
ESCAPE_ONCE,
errors,
);
return Ok(());
}
let posture = door(&meta, errors);
set_once(
&mut escape,
(meta.path.clone(), posture),
&meta.path,
ESCAPE_ONCE,
errors,
);
return Ok(());
}
if let Some(namespace) = namespace(&meta.path) {
if mode.stores_a_word() {
errors.push(attribute::named(
&meta,
if mode.mirrors {
format!(
"`{face}(…)` spells this variant for ONE face, and a mirror spells it one way \
everywhere — the upstream's own word, through its `Display`. A word written here \
would be a second source for a grammar that has one",
face = namespace.as_str()
)
} else {
format!(
"`{face}(…)` spells this variant for ONE face, and an OPEN vocabulary spells it one \
way everywhere. What forces that is the ESCAPE: it carries a runtime word and has no \
per-face spelling for a face to differ in, so a word written here would be one this \
vocabulary could store for a named member and not for an unnamed one. \
`#[ingraph(rename = \"…\")]` moves the word in every face at once",
face = namespace.as_str()
)
},
));
return Ok(());
}
if seen.insert(namespace, ()).is_some() {
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{}(…)` is declared more than once on this variant — one declaration names one word \
for one face",
namespace.as_str()
),
));
}
let mut renamed: Option<syn::LitStr> = None;
let walked = attribute::options(&meta, |inner| {
if inner.path.is_ident("rename") {
match value::literal(
&inner,
"`rename = \"…\"` must be a string literal — the word this face spells the variant as",
) {
Ok(word) => set_once(
&mut renamed,
word,
&inner.path,
"`rename` is declared more than once in one face — a face spells a variant one way",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
&format!(
"unknown entry in `{}(…)` on a variant — a face takes `rename = \"…\"`",
namespace.as_str()
),
&["rename"],
));
Ok(())
});
if let Some(word) = renamed {
let form = forms
.get(&namespace)
.copied()
.unwrap_or_else(|| namespace.default_form());
if form == StorageForm::Integer {
errors.push(syn::Error::new_spanned(
&word,
format!(
"`{face}` stores the discriminant, so it has no name to rename — that face's form is \
`{form}`{by}. Declare `#[ingraph({face}(text))]` on the enum to give it a word, or \
drop this rename",
face = namespace.as_str(),
form = form.as_str(),
by = if forms.contains_key(&namespace) {
", as this declaration says"
} else {
" by default"
},
),
));
}
if namespace == Namespace::Graphql {
wire::refuse_invalid_name(&word.value(), &word, errors);
}
names.insert(namespace, word.value());
}
return walked;
}
errors.push(attribute::unknown(
&meta,
&format!(
"unknown entry in `#[ingraph(…)]` on a variant — it takes `rename = \"…\"`, `other` and one \
block per face, {}",
listed(&Namespace::ALL.map(Namespace::as_str))
),
&["rename", "other"]
.into_iter()
.chain(Namespace::ALL.map(Namespace::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
if let Some((at, _)) = escape.as_ref()
&& (upstream.is_some() || rename.is_some())
{
errors.push(syn::Error::new_spanned(
at,
if mode.mirrors {
format!(
"`{}` is marked `#[ingraph(other)]` and renamed — the escape mirrors no upstream \
variant, so there is none for `rename` to name. It is the variant an upstream word this \
mirror does not know lands in, and that word is carried rather than spelled here",
variant.ident
)
} else {
format!(
"`{}` is marked `#[ingraph(other)]` and renamed — the escape has no canonical word for \
`rename` to move. It is the variant a word this vocabulary does not name lands in, and \
that word is the one it CARRIES: `as_str` hands it back, a column stores it and a cursor \
pages past it. The roster's own members are what `rename` spells",
variant.ident
)
},
));
}
EnumVariant {
ident: variant.ident.clone(),
rename,
names,
upstream,
escape: escape.map(|(_, posture)| posture),
carrier: None,
}
}
fn door(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> Escape {
if !attribute::has_block(meta) {
return Escape::Total;
}
if attribute::empty_group(meta) {
errors.push(attribute::named(meta, EMPTY_DOOR.to_owned()));
return Escape::Total;
}
let mut declared: Option<(&'static str, Escape)> = None;
let walked = meta.parse_nested_meta(|inner| {
let refusable = if inner.path.is_ident(TOTAL_DOOR) {
false
} else if inner.path.is_ident(REFUSABLE_DOOR) {
true
} else {
errors.push(attribute::unknown(
&inner,
UNKNOWN_DOOR,
&[TOTAL_DOOR, REFUSABLE_DOOR],
));
return Ok(());
};
let word = if refusable {
REFUSABLE_DOOR
} else {
TOTAL_DOOR
};
let gate = match value::parse_literal::<syn::Path>(&inner, DOOR_PATH) {
Ok(gate) => gate,
Err(e) => {
errors.push(e);
return Ok(());
}
};
match declared.as_ref() {
Some((first, _)) if *first == word => errors.push(syn::Error::new_spanned(
&inner.path,
format!("`{word}` is declared more than once on this escape — one escape opens one door"),
)),
Some((first, _)) => errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{first}` and `{word}` are both declared on this escape — a door either can refuse a \
word or it cannot, and there is no third answer. `{TOTAL_DOOR}` keeps this mirror OPEN, \
its gate answering with an upstream value; `{REFUSABLE_DOOR}` makes it HALF-OPEN, \
casting this vocabulary's own `ParseError` around what the gate turns away"
),
)),
None => {
declared = Some((
word,
if refusable {
Escape::TryGate(gate)
} else {
Escape::Gate(gate)
},
));
}
}
Ok(())
});
if let Err(e) = walked {
errors.push(e);
}
declared.map_or(Escape::Total, |(_, posture)| posture)
}
fn one_word_everywhere(mode: Mode, faces: &[syn::Path], errors: &mut Errors) {
if !mode.stores_a_word() {
return;
}
for face in faces {
let named = face
.get_ident()
.map_or_else(|| "this face".to_owned(), ToString::to_string);
errors.push(syn::Error::new_spanned(
face,
if mode.mirrors {
format!(
"`{named}(…)` names a FORM for one face, and a mirror has none to name: what it stores \
is the upstream's own rendering, the same word in every face. An upstream discriminant \
is not this crate's to depend on — a release may renumber it — and the \
`#[ingraph(other)]` escape has none at all"
)
} else {
format!(
"`{named}(…)` names a FORM for one face, and an OPEN vocabulary has none to name: what \
it stores is its own word, the same one in every face. The `#[ingraph(other)]` escape is \
what settles it — the word it carries is a runtime value with no discriminant behind it, \
so a face storing numbers could hold the members and not the one that is not a member. \
Drop the escape and this vocabulary is CLOSED, where the form knobs are"
)
},
));
}
}
fn escapes(mode: Mode, variants: &[EnumVariant], errors: &mut Errors) {
let mut escapes = variants.iter().filter(|variant| variant.escape.is_some());
let Some(first) = escapes.next() else {
return;
};
for extra in escapes {
errors.push(syn::Error::new_spanned(
&extra.ident,
format!(
"`{}` and `{first}` are both marked `#[ingraph(other)]` — {who} has ONE escape, and two \
would be two answers to where a word this vocabulary does not name goes",
extra.ident,
first = first.ident,
who = if mode.mirrors {
"a mirror"
} else {
"a vocabulary"
},
),
));
}
}
fn the_refusal_a_parse_answers_with(
mode: Mode,
variants: &[EnumVariant],
error: Option<&syn::Ident>,
errors: &mut Errors,
) {
let Some(at) = error else {
return;
};
let escape = variants.iter().find_map(|variant| variant.escape.as_ref());
if escape.is_none_or(Escape::refuses) {
return;
}
errors.push(syn::Error::new(
at.span(),
if mode.mirrors {
format!(
"`error(rename = \"…\")` names the refusal type a parse answers with, and this mirror has \
none: the `#[ingraph(other)]` escape says every word parses — the upstream's own parse \
where the marker is bare, the gate's signature where `other({TOTAL_DOOR} = \"…\")` names \
one — so `FromStr::Err` is `core::convert::Infallible` and this expansion declares no type \
beside the enum for the knob to move. `other({REFUSABLE_DOOR} = \"…\")` is the posture \
whose door CAN refuse, and the one this knob is for"
)
} else {
"`error(rename = \"…\")` names the refusal type a parse answers with, and this vocabulary \
has none: the `#[ingraph(other)]` escape says every word parses — a word no member answers \
to becomes the escape carrying its folded spelling — so `FromStr::Err` is \
`core::convert::Infallible` and this expansion declares no type beside the enum for the knob \
to move. Drop the escape and the vocabulary is CLOSED, which is where a parse can refuse and \
where this knob is for"
.to_owned()
},
));
}
fn published_fields(model: &EnumModel, errors: &mut Errors) {
for kind in GraphqlKind::ALL {
let mut taken: BTreeMap<String, ()> = BTreeMap::new();
taken.insert(TEXT_FIELD.to_owned(), ());
for delegate in model.promoted(kind) {
let at = published_at(delegate, kind);
if delegate.signature.inputs.len() > 1 {
errors.push(syn::Error::new(
at,
format!(
"a published `delegate(fn …)` takes its receiver and nothing else — `{kind}` renders it \
as a FIELD, and a field's arguments are a grammar this axis has not got. Drop the \
`#[graphql(…)]` to keep the method as Rust",
kind = kind.as_str(),
),
));
continue;
}
let Some(word) = delegate.word(kind) else {
continue;
};
if taken.insert(word.clone(), ()).is_none() {
continue;
}
errors.push(syn::Error::new(
at,
if word == TEXT_FIELD {
format!(
"this field would be called `{TEXT_FIELD}`, which is the word a promoted mirror \
publishes its own SLUG at — an object cannot render AS a word, so the word is a field \
and the name is taken. `#[graphql({kind}(rename = \"…\"))]` moves this one",
kind = kind.as_str(),
)
} else {
format!(
"two published methods are both called `{word}` — a schema has one namespace for an \
object's fields, and lower camel case folds two Rust spellings into one word. \
`#[{kind}(rename = \"…\")]` tells them apart",
kind = kind.as_str(),
)
},
));
}
}
}
fn published_at(delegate: &Delegate, kind: GraphqlKind) -> proc_macro2::Span {
delegate
.wire
.iter()
.find(|skin| skin.kind == kind)
.and_then(|skin| skin.rename.as_ref())
.map_or_else(|| delegate.signature.ident.span(), syn::LitStr::span)
}
fn refuse_a_waived_entry_that_publishes_nothing(delegates: &[Delegate], errors: &mut Errors) {
for delegate in delegates
.iter()
.filter(|entry| entry.on_self.is_some() && entry.wire.is_empty())
{
let method = &delegate.signature.ident;
errors.push(syn::Error::new_spanned(
method,
format!(
"`{method}` publishes nothing and `on = self` waives its forwarding half, so the entry has \
no reader. Without the word a plain entry earns its keep — it mints the method that \
materializes the upstream and calls it there — and with it the method is already yours, on \
your own `impl`, leaving the seat's whole content the field of the promoted object. Write \
`#[graphql(<backend>)]` on the entry to publish it, or drop the entry: the method is \
reached exactly as before either way"
),
));
}
}
fn borrowed(delegate: Option<&syn::Path>, errors: &mut Errors) {
let Some(at) = delegate else {
return;
};
errors.push(syn::Error::new_spanned(
at,
"`delegate(…)` forwards a method onto a MIRRORED upstream value, and this declaration mirrors \
nothing — the methods of a vocabulary this crate declares are its own to write, in an `impl` \
beside it. `#[ingraph(remote = \"…\")]` on the enum is what gives this word something to \
forward to",
));
}
fn refusal_name(model: &EnumModel, errors: &mut Errors) {
let Some(at) = model.error.as_ref() else {
return;
};
if model.error() != model.name {
return;
}
errors.push(syn::Error::new(
at.span(),
format!(
"the refusal type would be named `{name}`, which is already the vocabulary's own name — the \
expansion declares it beside the enum, so it needs a name of its own",
name = model.name
),
));
}
fn collisions(
variants: &[EnumVariant],
forms: &BTreeMap<Namespace, StorageForm>,
mode: Mode,
errors: &mut Errors,
) {
if mode.mirrors {
let mut taken: BTreeMap<String, &syn::Ident> = BTreeMap::new();
for variant in variants.iter().filter(|variant| variant.escape.is_none()) {
let upstream = variant.upstream().to_string();
match taken.get(&upstream) {
Some(first) => errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{}` and `{first}` both restate `{upstream}` — the mirror's `From` would carry two \
arms for one upstream variant, and the second names a value the first already took",
variant.ident
),
)),
None => {
taken.insert(upstream, &variant.ident);
}
}
}
predicates(variants, errors);
return;
}
if mode.open {
let mut taken: BTreeMap<String, &syn::Ident> = BTreeMap::new();
for variant in variants.iter().filter(|variant| variant.escape.is_none()) {
let word = variant.folded();
match taken.get(&word) {
Some(first) => errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{}` and `{first}` are both `{word}` — a roster spells each member once, or a word \
read back names two of them and the door hands out whichever comes first",
variant.ident
),
)),
None => {
taken.insert(word, &variant.ident);
}
}
}
predicates(variants, errors);
return;
}
let mut faces = vec![(
"the canonical".to_owned(),
false,
variants.iter().map(EnumVariant::canonical).collect(),
)];
faces.extend(
Namespace::ALL
.into_iter()
.filter(|namespace| {
*namespace == Namespace::Graphql
|| forms
.get(namespace)
.copied()
.unwrap_or_else(|| namespace.default_form())
== StorageForm::Text
})
.map(|namespace| {
(
format!("the `{}`", namespace.as_str()),
namespace == Namespace::Graphql,
variants
.iter()
.map(|variant| variant.name(namespace))
.collect::<Vec<_>>(),
)
}),
);
for (face, on_the_wire, words) in faces {
let mut taken: BTreeMap<&str, &syn::Ident> = BTreeMap::new();
for (variant, spelled) in variants.iter().zip(&words) {
let Some(first) = taken.get(spelled.as_str()) else {
taken.insert(spelled, &variant.ident);
continue;
};
let sentence = if on_the_wire {
format!(
"`{}` and `{first}` are both `{spelled}` on the wire — a GraphQL enum's values are \
UNIQUE, and a document naming this one would have two variants to mean",
variant.ident
)
} else {
format!(
"`{}` and `{first}` are both `{spelled}` in {face} namespace — a face spells each \
variant once, or a value read back names two of them",
variant.ident
)
};
errors.push(syn::Error::new_spanned(&variant.ident, sentence));
}
}
predicates(variants, errors);
}
fn emitted_methods(model: &EnumModel, errors: &mut Errors) {
let emitted = model.emitted_methods();
let mut taken: Vec<&Emitted> = Vec::new();
for candidate in &emitted {
if let Some(first) = taken.iter().find(|earlier| {
earlier.name == candidate.name
&& (matches!(earlier.origin, Origin::Delegate(_))
|| matches!(candidate.origin, Origin::Delegate(_)))
}) {
let fix = if matches!(first.origin, Origin::Delegate(_)) {
"Rename one of them, or drop the second: two entries of one name are two methods of one \
name, and the seat restates a method rather than declaring it twice."
} else {
"Rename the entry: it RESTATES a method you wrote, where a predicate is built from a \
variant's own name and `remote` and `VARIANTS` are words the mode fixes."
};
let why = format!(
"`{owner}` would declare `{name}` twice — {first}, and {second} — and rustc reports that \
duplicate inside the expansion, where nothing names the entry that caused it. {fix}",
owner = candidate.owner_name,
name = candidate.name,
first = first.origin,
second = candidate.origin,
);
errors.push(
match candidate.origin.column().or_else(|| first.origin.column()) {
Some(at) => syn::Error::new_spanned(at, why),
None => syn::Error::new_spanned(&candidate.owner_name, why),
},
);
}
taken.push(candidate);
}
}
fn predicates(variants: &[EnumVariant], errors: &mut Errors) {
let mut predicates: BTreeMap<String, &syn::Ident> = BTreeMap::new();
for variant in variants {
let predicate = variant.predicate().to_string();
if let Some(first) = predicates.get(&predicate) {
errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{}` and `{first}` both derive `{predicate}` — the emitted predicates would be two \
methods of one name",
variant.ident
),
));
} else {
predicates.insert(predicate, &variant.ident);
}
}
}