ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
//! Validating a MEMBER SET: the shape two derives share, and the prose each of them owns.
//!
//! A union IS its member set and an interface is a member set with a promise over it, so both
//! declare the same Rust shape — one variant per member, each carrying that member and nothing
//! else — and both refuse the same six ways of breaking it: a struct, an enum with no variants, a
//! variant carrying no member, one carrying several, one carrying its member in a named field, and
//! any generic parameter. Two more are about the SET rather than about a variant: one type reached
//! through two variants, and two variants whose words derive one method.
//!
//! # The WALK is shared and the REASONS are not
//!
//! Which rule runs where, at which span, over which variant is one decision, and it lives here.
//! WHY a rule holds is the declaring derive's: GraphQL's *a union type must include one or more
//! unique member types* is the union's whole argument for two of these refusals, and an interface
//! refuses the same shapes because a promise stated twice over one member is stated once. So
//! [`Family`] carries the sentences, and a derive that adopts this walk states its own law rather
//! than borrowing one that is not about it.
//!
//! The alternative was one copy of the walk per derive, which is how two front ends come to disagree
//! about which variant a refusal is spanned at.
//!
//! The KNOB naming the emitted refusal is here for the same reason one step over: the refusal is the
//! union seam's own emission, so a derive equipped through that seam takes the same word for it —
//! [`UNWRAP_ERROR`] — and the migration off the old spelling is stated once rather than twice.

use std::collections::BTreeMap;

use ingraph_codegen::union::{self, Face, UnionMember};
use quote::ToTokens as _;

use crate::{attribute, errors::Errors};

/// The word the UNWRAP REFUSAL's knob takes.
///
/// `unwrap_error` and not `error`, because `error` is the CONVERSION CELL's word — one per leg,
/// inside a database's block, naming what a fallible crossing refuses with. Two knobs sharing one
/// word would be told apart by depth alone, which is what the axis law exists to stop.
pub(crate) const UNWRAP_ERROR: &str = "unwrap_error";

/// The migration the OLD spelling gets, in the shape every migration in this grammar takes: the
/// word that moved, where it went, and the one sentence saying why.
const RENAMED: &str = "`error` names CONVERSION CELLS now — the unwrap refusal's knob is \
                       `unwrap_error(rename = \"…\")`. One word per thing typed: a cell says what a \
                       fallible crossing refuses with, and this says what a wrong-variant unwrap \
                       answers with";

/// The knob naming the type a wrong-variant unwrap answers with — read for BOTH member sets.
///
/// `None` when the entry is neither spelling, so a caller falls through to whatever else its own
/// grammar takes. Shared because the KNOB is shared: the refusal is the union seam's own emission,
/// so a derive equipped through that seam takes the same word for it and the migration is stated
/// once.
pub(crate) fn refusal_knob(
  meta: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<syn::Ident>,
  errors: &mut Errors,
) -> Option<syn::Result<()>> {
  if meta.path.is_ident(UNWRAP_ERROR) {
    return Some(attribute::rename_block(meta, slot, UNWRAP_ERROR, errors));
  }
  if meta.path.is_ident("error") {
    // The OLD spelling, matched exactly and answered by name — there is no near miss in a word this
    // seam recognises.
    errors.push(attribute::unknown(meta, RENAMED, &[]));
    return Some(Ok(()));
  }
  None
}

/// One derive's own words for the rules this walk enforces.
///
/// Every field is a clause the shared sentence is completed with, so a refusal reads as one
/// sentence rather than as a template with a reason bolted on.
pub(crate) struct Family {
  /// The WHOLE SPELLING of the word a declaration is written with —
  /// `#[derive(ingraph::Union)]`, `#[ingraph::interface]`.
  ///
  /// The spelling rather than the bare name, because the two member sets are no longer written the
  /// same way: a union REWRITES nothing, so it is a derive, and an interface is an attribute
  /// macro. A template that wrapped a bare word in `#[ingraph::…]` would have to grow a fork per
  /// family; the fork lives here instead, where each family says how it is spelled and the sentence
  /// quotes it.
  ///
  /// It is NOT [`Family::noun`]: the noun is what a declaration IS, and this is what a reader types.
  pub(crate) derive: &'static str,
  /// The declaration's noun — `union`, `interface`.
  pub(crate) noun: &'static str,
  /// The noun POSSESSIVE and capitalised, mid-sentence — `A union's`, `An interface's`.
  pub(crate) possessive: &'static str,
  /// Why a struct declares none: the clause after `supports enums only — `.
  pub(crate) not_an_enum: &'static str,
  /// Why an enum with no variants declares none: the clause after `declares no <noun> — `.
  pub(crate) empty: &'static str,
  /// Why a variant may carry only ONE: the sentence after `carries <n>. `.
  pub(crate) several: &'static str,
  /// Why the member is carried POSITIONALLY: the sentence between `names its payload. ` and the
  /// spelling that fixes it.
  pub(crate) positional: &'static str,
  /// What a variant's `#[ingraph(…)]` is refused with: the clause after `on a <noun>'s variant — `.
  pub(crate) variant_entry: &'static str,
  /// Why two variants may not carry one type: the clause after `carry ONE member type — `.
  pub(crate) duplicate: &'static str,
  /// Why a parameter is not a member: the clause after `generic <noun>s are not supported — `.
  pub(crate) generic: &'static str,
}

/// A member set is CONCRETE.
///
/// A member is the TYPE a variant carries, and a parameter is not one until it is substituted — so
/// the set the derive is about does not exist yet.
pub(crate) fn concrete(family: &Family, generics: &syn::Generics, errors: &mut Errors) {
  let why = format!(
    "generic {noun}s are not supported — {generic}",
    noun = family.noun,
    generic = family.generic
  );
  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));
  }
}

/// The declaration's members — one per variant, each the single unnamed payload it carries.
///
/// A variant of the wrong shape is ACCUMULATED rather than terminal, so one compile names every
/// offending variant instead of the first; the model is discarded either way, because
/// [`Errors::into_result`] refuses to hand one back once anything was recorded.
///
/// # Errors
/// The refusal that STOPS the pass — a declaration that is not an enum, or an enum with no
/// variants — after which there is nothing left to check about variants.
pub(crate) fn members(
  family: &Family,
  input: &syn::DeriveInput,
  errors: &mut Errors,
) -> syn::Result<Vec<UnionMember>> {
  let syn::Data::Enum(data) = &input.data else {
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "`{derive}` supports enums only — {not_an_enum}",
        derive = family.derive,
        not_an_enum = family.not_an_enum
      ),
    ));
  };

  if data.variants.is_empty() {
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "an enum with no variants declares no {noun} — {empty}",
        noun = family.noun,
        empty = family.empty
      ),
    ));
  }

  let mut parsed = Vec::with_capacity(data.variants.len());
  for variant in &data.variants {
    bare(family, &variant.attrs, errors);
    match &variant.fields {
      syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => parsed.push(UnionMember {
        ident: variant.ident.clone(),
        ty: fields
          .unnamed
          .first()
          .expect("a one-field list has a first field")
          .ty
          .clone(),
      }),
      syn::Fields::Unnamed(fields) if fields.unnamed.is_empty() => {
        errors.push(carries_nothing(family, &variant.ident, &variant.fields));
      }
      syn::Fields::Unnamed(fields) => errors.push(syn::Error::new_spanned(
        &variant.fields,
        format!(
          "`{derive}` takes ONE member per variant — `{ident}` carries {carried}. \
           {several}",
          derive = family.derive,
          ident = variant.ident,
          carried = fields.unnamed.len(),
          several = family.several,
        ),
      )),
      syn::Fields::Named(_) => errors.push(syn::Error::new_spanned(
        &variant.fields,
        format!(
          "`{derive}` takes the member POSITIONALLY — `{ident}` names its payload. \
           {positional} Write `{ident}(…)`",
          derive = family.derive,
          ident = variant.ident,
          positional = family.positional,
        ),
      )),
      syn::Fields::Unit => errors.push(carries_nothing(family, &variant.ident, &variant.ident)),
    }
  }
  Ok(parsed)
}

/// The refusal a variant with no payload gets, spanned wherever that variant's emptiness shows.
///
/// The method it names is asked of the emitter's own vocabulary rather than spelled here, for the
/// reason the refusal type's name is: a derived name written on this side is a second copy of what
/// the emission writes.
fn carries_nothing(family: &Family, ident: &syn::Ident, at: impl quote::ToTokens) -> syn::Error {
  let unwrap = Face::Unwrap.name(&union::word(ident));
  syn::Error::new_spanned(
    at,
    format!(
      "`{derive}` takes variants that CARRY their member — `{ident}` carries none. \
       {possessive} variant IS one member type, so the payload is the whole of what the variant is \
       for: one with none names no member, and `{unwrap}` would have nothing to hand back. A \
       variant that is only a NAME is a vocabulary's, which `#[derive(ingraph::Enum)]` describes",
      derive = family.derive,
      possessive = family.possessive,
    ),
  )
}

/// A member set's variants take no `#[ingraph(…)]` entries at all.
///
/// Refused rather than ignored, for the reason every unrecognised entry in this grammar is: an
/// entry nobody reads is a rule its author believes they declared.
fn bare(family: &Family, attrs: &[syn::Attribute], errors: &mut Errors) {
  let why = format!(
    "unknown entry in `#[ingraph(…)]` on a {noun}'s variant — {variant_entry}",
    noun = family.noun,
    variant_entry = family.variant_entry
  );
  attribute::walk(attrs, errors, |meta, errors| {
    // A member set's variant takes NO entries at all, so the empty vocabulary is the position's
    // real answer rather than an omission: there is no word here to have nearly written.
    errors.push(attribute::unknown(&meta, &why, &[]));
    Ok(())
  });
}

/// The two things a member SET can get wrong: one type reached through two variants, and two
/// variants deriving one method name.
///
/// Both are refused with both variants named — the second would otherwise be a duplicate definition
/// inside the expansion, at a span the declaration cannot edit.
pub(crate) fn collisions(family: &Family, members: &[UnionMember], errors: &mut Errors) {
  // The type as its TOKENS spell it, which is as far as a macro can see: `Media` and
  // `media::Media` are one type and two token streams, so a declaration that reaches one member
  // through two paths is not caught here. The refusal names the two VARIANTS rather than the type
  // for the same reason — rendering a type back into a sentence would be a spelling this layer has
  // no authority over, and the pair of variants is what a reader has to look at anyway.
  let mut carried: BTreeMap<String, &syn::Ident> = BTreeMap::new();
  for member in members {
    let ty = member.ty.to_token_stream().to_string();
    if let Some(first) = carried.get(&ty) {
      errors.push(syn::Error::new_spanned(
        &member.ident,
        format!(
          "`{ident}` and `{first}` carry ONE member type — {duplicate}",
          ident = member.ident,
          duplicate = family.duplicate,
        ),
      ));
    } else {
      carried.insert(ty, &member.ident);
    }
  }

  let mut words: BTreeMap<String, &syn::Ident> = BTreeMap::new();
  for member in members {
    let word = member.word().to_string();
    if let Some(first) = words.get(&word) {
      errors.push(syn::Error::new_spanned(
        &member.ident,
        format!(
          "`{}` and `{first}` both derive `{}` — the emitted face would be two methods of one \
           name, seven times over",
          member.ident,
          Face::Predicate.name(&member.word())
        ),
      ));
    } else {
      words.insert(word, &member.ident);
    }
  }
}