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
//! What an ATTRIBUTE macro does that a derive cannot: it owns the item it sits on.
//!
//! A derive is handed a copy and may only append. An attribute macro is handed the item and emits
//! whatever it likes in its place — so the declaration a user writes and the declaration the
//! compiler sees are allowed to differ, which is the whole reason this family pivoted. Two things
//! need it, and neither is expressible under a derive:
//!
//! * the INJECTED PROJECTION FIELD, `__ig_key__: <Upstream as Transformer>::Key`, which is how a
//!   derived index carries an identity it does not mint;
//! * the VISIBILITY CONVENTION, which stops being the author's pen: a field written with no
//!   visibility at all gets `pub(crate)`, because a declaration's fields are read by the emitted
//!   code and by the crate around it, and making every author write the word was a convention
//!   nothing enforced.
//!
//! What this module does NOT do is decide anything. It echoes the host, strips what the macro
//! consumed, and hands the arguments to the same grammar the derives already parsed — one form
//! change, no rules moved.

use quote::ToTokens as _;

use crate::errors::Errors;

/// The attribute this family's field markers are written in, and the one an echo consumes.
const ATTRIBUTE: &str = "ingraph";

/// The macro's own arguments, as the ATTRIBUTE LIST the grammar already reads.
///
/// `#[ingraph::record(sqlite)]` and the derive's `#[ingraph(sqlite)]` carry the
/// same tokens in the same shape, so the arguments are wrapped back into one synthetic attribute and
/// every rule downstream is the rule that was already there. The pivot is a change of ENTRY POINT
/// and not of grammar, and this is the line that keeps it one.
///
/// Empty arguments produce no attribute rather than an empty one: `#[ingraph::operator]` is the
/// declaration that says nothing, and a walk over an empty list would have to special-case it.
pub(crate) fn options(args: proc_macro2::TokenStream) -> Vec<syn::Attribute> {
  if args.is_empty() {
    return Vec::new();
  }
  vec![syn::parse_quote!(#[ingraph(#args)])]
}

/// The record-level attribute, written where it used to live.
///
/// A named MIGRATION rather than a silent strip: under the derive the options sat in an
/// `#[ingraph(…)]` beside it, and an author who moves a declaration across will bring one. The
/// tokens are still legal, so nothing else would report this — the attribute would be stripped by
/// the echo and the options would vanish without a word.
pub(crate) fn refuse_a_moved_option_block(attrs: &[syn::Attribute], errors: &mut Errors) {
  for attr in attrs.iter().filter(|attr| attr.path().is_ident(ATTRIBUTE)) {
    errors.push(syn::Error::new_spanned(
      attr,
      "the declaration's own options are this macro's ARGUMENTS now — write them inside the \
       attribute's parentheses, as `#[ingraph::record(sqlite)]`. A separate \
       `#[ingraph(…)]` beside it is the derive's spelling, and nothing reads it here",
    ));
  }
}

/// The host, re-emitted: the author's item with what the macro consumed taken out and the
/// visibility convention stamped in.
///
/// EVERYTHING ELSE SURVIVES VERBATIM — the user's own derives, their `cfg`s, their doc comments,
/// their generics, their field order. An attribute macro replaces the item it sits on, so anything
/// this function drops is dropped from the program, and the list of what it deliberately drops is
/// exactly one thing: the `#[ingraph(…)]` markers it read.
///
/// The VISIBILITY rule is per field and one-directional. A field written with no visibility gets
/// `pub(crate)`; a field written with any visibility at all — `pub`, `pub(super)`, or `pub(crate)`
/// spelled by hand — keeps what it says. So the convention has a default and never an override:
/// nothing here can narrow what an author widened, which is the property that makes stamping safe
/// to do silently.
pub(crate) fn echo(input: &syn::DeriveInput) -> proc_macro2::TokenStream {
  rewrite(input, None)
}

/// The host with ONE field added — the injection, and the whole reason an attribute macro was
/// needed.
///
/// TWO declarations reach it, and they inject for the same reason at two grains. A derived index
/// mints no id, so the two members its entity binding has to answer — the key, and the id inside it
/// — have nothing in the declaration to be read from; γ′ is what they are read from, and a derive
/// could not have put it there. A resource written with a BUILTIN KIND WORD names an engine this
/// framework ships, so the engine itself is not the author's to write; the injected field is where
/// the expansion puts the one it mints.
///
/// The field is the EMITTER's own mint, handed in whole rather than described, so its name, its type
/// and its visibility are decided in the one place that also reads them back — see
/// `IndexModel::carried_key` and `ResourceKind::engine_field`.
///
/// It goes on the END rather than the front, and the position is load-bearing exactly once: a
/// derived index's constructor takes the key FIRST, so the two orders differ, and a caller who
/// confuses a positional struct literal with the constructor is writing something the injection has
/// already made impossible to compile.
///
/// # A UNIT declaration GROWS the brace it has none of
///
/// `pub struct Ft;` is the shape a builtin resource is written in — the author states that the type
/// is the engine and nothing else — so there is no field list to append to, and the injection makes
/// one. That is the injection saying what it means rather than a special case: the declaration the
/// author wrote and the declaration the compiler sees are allowed to differ, and here they differ by
/// exactly the field the macro owns.
pub(crate) fn echo_carrying(
  input: &syn::DeriveInput,
  carried: syn::Field,
) -> proc_macro2::TokenStream {
  rewrite(input, Some(carried))
}

/// The host of a REWRITE — the author's item REPLACED by the transparent wrapper the macro owns.
///
/// This is the one thing only an attribute macro can do, taken to its end: the declaration a user
/// writes and the declaration the compiler sees are allowed to differ, and here they differ
/// completely. What the author wrote is a MANIFEST — the shape of `remote`, restated so this
/// framework can read it — and what the compiler sees is one unnamed position holding that type.
///
/// `#[repr(transparent)]` is the emission's own, and it is load-bearing: it is what makes the
/// reference family emitted beside this a fact of the LANGUAGE rather than a layout claim. An
/// author's own `#[repr(…)]` is refused before this is reached — see
/// [`crate::remote::refuse_a_representation`].
///
/// Every OTHER item attribute is forwarded verbatim and in order, which is the family's law rather
/// than this position's exception: an attribute this grammar does not own is not this grammar's to
/// read. The author's `#[derive(…)]` lands on the wrapper, where a 1-tuple's derives delegate to
/// the field — which is exactly what makes `Borrow`'s `Eq`/`Hash` agreement below hold.
///
/// The field is PRIVATE. Everything that reaches the wrapped value goes through an emitted door —
/// `Deref`, `AsRef`, `Borrow`, `From` — so a public position would be a second, unversioned one.
pub(crate) fn transparent(
  input: &syn::DeriveInput,
  remote: &syn::Path,
) -> proc_macro2::TokenStream {
  let attrs = crate::remote::forwarded(&input.attrs);
  let vis = &input.vis;
  let name = &input.ident;
  quote::quote! {
    #(#attrs)*
    #[repr(transparent)]
    #vis struct #name(#remote);
  }
}

/// The host of a declaration that is a VOCABULARY rather than DATA — echoed with the `dead_code`
/// lint turned off over it, and with the reason written into the attribute.
///
/// A mutation node is the case, and it is not a workaround. Its fields are EXCHANGES: each one's
/// type states what is sent and what comes back, and the words beside it state who runs it. Nothing
/// ever holds a value of the node, because there is nothing a value of it could mean — the emission
/// reads the fields' TYPES and the resolvers it writes take their arguments off the wire. So rustc's
/// *never constructed* is a true observation about a thing that is true of the whole tier, reported
/// inside an expansion the author cannot edit and about a shape the framework asked them to write.
///
/// The lint is turned off HERE — on the echoed host, as narrowly as the tool allows — rather than by
/// the emission naming the fields in some audit, which was the other candidate: an audit would make
/// the silence a side effect of an unrelated item, and a reader finding it would have no way to tell
/// it was deliberate. The `reason` is what makes this one self-describing.
pub(crate) fn echo_vocabulary(input: &syn::DeriveInput) -> proc_macro2::TokenStream {
  let host = rewrite(input, None);
  quote::quote! {
    #[allow(
      dead_code,
      reason = "a mutation node is a VOCABULARY and not data: nothing constructs one, because its \
                fields are exchanges whose types the expansion reads and whose values arrive off \
                the wire"
    )]
    #host
  }
}

/// One body for both: strip, stamp, and append whatever the macro is adding.
///
/// The injection lands AFTER the stamp, and the order is not incidental. The stamp is a rule about
/// what an AUTHOR wrote — a field with no visibility gets `pub(crate)` — and a field the author did
/// not write is not that; it arrives already spelled, and running the convention over it would make
/// the mint's own decision depend on a rule about somebody else's pen.
fn rewrite(input: &syn::DeriveInput, carried: Option<syn::Field>) -> proc_macro2::TokenStream {
  let mut host = input.clone();
  host.attrs.retain(|attr| !attr.path().is_ident(ATTRIBUTE));
  match &mut host.data {
    // The stamp is the STRUCT's alone. A variant's fields carry the enum's own visibility and may
    // not qualify it at all — `pub(crate)` on one is rejected by rustc as an unnecessary qualifier
    // — so an enum host has its markers taken out and nothing else touched.
    syn::Data::Struct(data) => {
      strip(data.fields.iter_mut(), true);
      if let Some(carried) = carried {
        inject(data, carried);
      }
    }
    syn::Data::Enum(data) => {
      for variant in &mut data.variants {
        variant
          .attrs
          .retain(|attr| !attr.path().is_ident(ATTRIBUTE));
        strip(variant.fields.iter_mut(), false);
      }
    }
    syn::Data::Union(data) => strip(data.fields.named.iter_mut(), true),
  }
  host.to_token_stream()
}

/// Put the minted field into the declaration, growing the brace where there is none to put it in.
///
/// A NAMED host takes it at the end. A UNIT host has no field list at all, so one is made and the
/// terminating `;` goes with it — a struct with a brace and a semicolon is not a declaration, and
/// leaving the token would be this function emitting something that does not parse.
///
/// A TUPLE host is left alone, which is the honest answer rather than an omission: the field arrives
/// NAMED, and the two callers that mint one both refuse a host they cannot put a named field in
/// before they ever ask for one. Appending it here would mean inventing a positional form of
/// somebody else's mint.
fn inject(data: &mut syn::DataStruct, carried: syn::Field) {
  match &mut data.fields {
    syn::Fields::Named(named) => named.named.push(carried),
    syn::Fields::Unit => {
      let mut named = syn::punctuated::Punctuated::new();
      named.push(carried);
      data.fields = syn::Fields::Named(syn::FieldsNamed {
        brace_token: syn::token::Brace::default(),
        named,
      });
      data.semi_token = None;
    }
    syn::Fields::Unnamed(_) => {}
  }
}

/// One field list: the markers taken out, and — where the host is one whose fields carry a
/// visibility of their own — the convention stamped in.
fn strip<'a>(fields: impl Iterator<Item = &'a mut syn::Field>, stamp: bool) {
  for field in fields {
    field.attrs.retain(|attr| !attr.path().is_ident(ATTRIBUTE));
    if stamp && matches!(field.vis, syn::Visibility::Inherited) {
      field.vis = syn::parse_quote!(pub(crate));
    }
  }
}

/// A DERIVE-SHAPED declaration split into what the attribute form takes separately: the item, and
/// the `#[ingraph(…)]` attributes beside it read as the macro's arguments.
///
/// For the unit suites alone, and it earns its place there. Every assertion below the entry points
/// is about the GRAMMAR — which words a block takes, what each refusal says — and the pivot moved
/// none of that; it moved where the tokens arrive. Splitting here is what lets those suites keep
/// spelling a declaration in one piece, so a test that changed is a test whose RULE changed. What
/// the entry point itself does is asserted where it can only be asserted: by the corpus, which
/// compiles real attribute-form declarations.
#[cfg(test)]
pub(crate) fn split(input: &syn::DeriveInput) -> (syn::DeriveInput, Vec<syn::Attribute>) {
  let mut host = input.clone();
  let (options, rest): (Vec<syn::Attribute>, Vec<syn::Attribute>) = host
    .attrs
    .into_iter()
    .partition(|attr| attr.path().is_ident(ATTRIBUTE));
  host.attrs = rest;
  (host, options)
}