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 `#[repr(transparent)]` tuple wrapper into the id model the emitter consumes.
//!
//! ```text
//! #[derive(ingraph::Id)]
//! #[repr(transparent)]
//! pub struct TrackId(uuid::Uuid);
//! ```
//!
//! # THE SHAPE IS THE WHOLE GRAMMAR, and there is no kit word here
//!
//! `#[derive(ingraph::NewType)]` chooses: every face it writes is a face its author named. This
//! device does not, and the asymmetry is the two doors' subjects. A newtype is a VALUE, and which
//! faces a value wants is a decision about the product; an id is an ADDRESS, and the register an
//! address needs is a MEASURED set — the one `findit`'s `MediaId` and `mediagraph`'s `VolumeId` each
//! hand-wrote, to the impl, independently. A word per face here would be a question whose answer is
//! always *all of them*.
//!
//! So the only option this device takes is `crate = "…"`, which is not a face at all: it is where the
//! expansion's own paths resolve.
//!
//! # THREE LAWS, each refused BY NAME
//!
//! **TUPLE WRAPPER.** One unnamed field and nothing else. A named-field struct is refused rather than
//! read, where `#[derive(ingraph::NewType)]` reads both spellings: the casts below are about
//! POSITION ZERO, `Self(inner)` is how every emitted row builds one, and a device that took a name
//! would be writing a second shape of every body for a spelling that buys nothing at an address.
//!
//! **`#[repr(transparent)]`.** Required, and VERIFIED — the attribute has to be on the declaration.
//! It is what makes `from_ref` sound, and stating it as a requirement rather than as prose is what
//! turns layout identity into the compiler's guarantee.
//!
//! **NO PARAMETERS.** An id is a concrete address. A generic wrapper would put an uncovered type
//! parameter in `From<Self> for Inner` (`E0210`), leave the minted reading's parameter unused
//! (`E0392`), and give the emitted `Debug` a name that is not the one a reader was shown — three
//! refusals inside an expansion, in place of one sentence here.

use ingraph_codegen::id::IdModel;

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

#[cfg(test)]
mod tests;

/// This device's own name, for the sentences that name it.
const DERIVE: &str = "#[derive(ingraph::Id)]";

/// What `crate = "…"` has to be.
const CRATE_PATH: &str =
  "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";

/// The refusal for a crate named twice.
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";

/// The one word this device takes, which is the vocabulary a near miss is measured against.
const BUILT: [&str; 1] = ["crate"];

/// Validate a decorated struct into the model the emitter consumes.
///
/// # Errors
///
/// A [`syn::Error`] carrying EVERY rule the pass could still see violated, each spanned at the token
/// that violated it, so one compile reports the whole declaration's problems.
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<IdModel> {
  let mut errors = Errors::default();
  let krate = options(&input.attrs, &mut errors);

  concrete(input, &mut errors);
  transparent(input, &mut errors);

  let inner = match held(input) {
    Ok(inner) => inner,
    Err(terminal) => return Err(errors.seal(terminal)),
  };

  let model = IdModel {
    vis: input.vis.clone(),
    subject: input.ident.clone(),
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    inner,
  };
  errors.into_result(model)
}

/// THE ONE VALUE this wrapper holds — its type, read off position zero.
///
/// TERMINAL, because every emitted row spells that type: a declaration with no inner has no model to
/// build, and continuing past it would report the same absence once per row.
fn held(input: &syn::DeriveInput) -> syn::Result<syn::Type> {
  let syn::Data::Struct(data) = &input.data else {
    let shape = match &input.data {
      syn::Data::Enum(_) => {
        "this declaration is an ENUM, whose content is its ALTERNATIVES — so there is no one value \
         for a key duty to read. A vocabulary is already a key by another road: \
         `#[derive(ingraph::Enum)]` writes the transparency row along with the rest of a \
         vocabulary's citizenship"
      }
      _ => {
        "this declaration is a UNION, whose content is whichever field was last written — a fact no \
         `unsafe`-free read can recover, and an identity nothing can compare. There is no road for \
         one here and none is planned"
      }
    };
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "{DERIVE} equips a WRAPPER — one type holding one value, transparently — and {shape}."
      ),
    ));
  };

  let syn::Fields::Unnamed(fields) = &data.fields else {
    let (shape, fix) = match &data.fields {
      syn::Fields::Named(_) => (
        "holds a NAMED field",
        "write it as a tuple struct — `struct Name(Inner);` — which is the same declaration with \
         the name dropped",
      ),
      _ => (
        "holds NOTHING",
        "a type with no value in it addresses nothing, and there is no field for the key duties to \
         read",
      ),
    };
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "{DERIVE} equips a TUPLE wrapper — `struct Name(Inner);` — and this one {shape}. The casts \
         this device writes are about POSITION ZERO and every emitted row builds one as \
         `Self(inner)`, so the shape is the device's own rather than a preference: {fix}."
      ),
    ));
  };

  let mut held = fields.unnamed.iter();
  let (Some(field), None) = (held.next(), held.next()) else {
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "{DERIVE} equips a wrapper holding EXACTLY ONE value, and this one holds {count}. The \
         transparency assertion it writes says this type IS the value inside it — at the same \
         equality, the same order and the same stored form — and a declaration with two values has \
         two answers and no rule for picking between them. A key spanning several columns is a KEY \
         STRUCT, which a record mints from its own `#[ingraph(id)]` and lineage columns rather than \
         from a wrapper.",
        count = fields.unnamed.len(),
      ),
    ));
  };
  Ok(field.ty.clone())
}

/// `#[repr(transparent)]`, present — the ADMISSION REQUIREMENT, checked rather than trusted.
fn transparent(input: &syn::DeriveInput, errors: &mut Errors) {
  if input.attrs.iter().any(is_transparent) {
    return;
  }
  errors.push(syn::Error::new_spanned(
    &input.ident,
    format!(
      "the Id derive's admission requires `#[repr(transparent)]`, and this declaration carries no \
       such attribute. It is not ceremony: {DERIVE} writes `from_ref`, which VIEWS a `&Inner` as a \
       `&Self`, and the only thing that makes that view sound is the two types having one layout. \
       Written down, layout identity is the compiler's guarantee; left to the default \
       representation it is a hope about a `repr(Rust)` type, which is explicitly free to be laid \
       out otherwise. Add `#[repr(transparent)]` above the declaration."
    ),
  ));
}

/// Whether one attribute is a `repr` naming `transparent`.
///
/// The list is walked rather than string-matched, so `#[repr(transparent)]` and
/// `#[repr(align(16), transparent)]` are one answer — a representation is a SET, and a device
/// reading only the first entry would refuse a declaration that says the thing it asks for.
fn is_transparent(attr: &syn::Attribute) -> bool {
  if !attr.path().is_ident("repr") {
    return false;
  }
  let mut found = false;
  // The walk's own refusal is discarded: an ill-formed `repr` is rustc's to report, and a second
  // sentence about it here would be this device describing an attribute it does not own.
  let _ = attr.parse_nested_meta(|entry| {
    if entry.path.is_ident("transparent") {
      found = true;
    }
    // Swallow whatever an entry carries — `align(16)` has a group this walk is not reading.
    if entry.input.peek(syn::token::Paren) {
      let content;
      syn::parenthesized!(content in entry.input);
      let _ = content.parse::<proc_macro2::TokenStream>();
    }
    Ok(())
  });
  found
}

/// NO PARAMETERS — an id is a concrete address.
fn concrete(input: &syn::DeriveInput, errors: &mut Errors) {
  if input.generics.params.is_empty() {
    return;
  }
  errors.push(syn::Error::new_spanned(
    &input.generics,
    format!(
      "{DERIVE} equips a CONCRETE wrapper, and this declaration is generic. An id is an address: it \
       is stored, rendered into a path segment, published under its own name in a schema and \
       compared against a column — and every one of those is a fact about ONE type rather than \
       about a family of them. The three rows that break are worth naming: `From<Self> for Inner` \
       puts an uncovered parameter in the self position (`E0210`), the minted `<Name>Wire` reading \
       carries a parameter nothing uses (`E0392`), and the emitted `Debug` prints a name that is \
       not the one a reader was shown. Wrap the concrete type instead, or take \
       `#[derive(ingraph::NewType)]`, which is the device for a generic value."
    ),
  ));
}

/// Walk the struct-level attribute. `crate = "…"` is the whole of it.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Option<syn::Path> {
  let mut krate: Option<syn::Path> = None;

  attribute::walk(attrs, errors, |meta, errors| {
    // `crate` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
    // arrives here as an ordinary one-segment path.
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
        Ok(path) => attribute::set_once(&mut krate, path, &meta.path, CRATE_ONCE, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    if let Some(refusal) = candidate(&meta.path) {
      errors.push(attribute::named(&meta, refusal));
      return Ok(());
    }

    errors.push(attribute::unknown(
      &meta,
      "unknown entry in `#[ingraph(…)]` on an id wrapper — this device takes `crate = \"…\"` and \
       nothing else. The register it writes is not chosen: an address needs every face of it, so \
       there is no word here to install one",
      &BUILT,
    ));
    Ok(())
  });

  krate
}

/// A word the NEWTYPE door carries that this one does not — refused BY NAME, pointing at the door
/// that has it.
///
/// The refuse-until house law, read across two devices instead of across two rounds: a word an
/// author plausibly reaches for here exists, just not at this door, and telling them it is unknown
/// would be the one thing that is not true of it.
fn candidate(path: &syn::Path) -> Option<String> {
  let word = if path.is_ident("graphql") {
    "`graphql(<backend>(…))` is `#[derive(ingraph::NewType)]`'s word and this device has no seat \
     for it: an id publishes ONE wire face — a scalar under its own name, with its `FromStr` as the \
     door and its `Display` as the rendering — and that face is written unconditionally. A type \
     that wants to choose its wire faces is a VALUE rather than an address; take the newtype door."
  } else if path.is_ident("marker") || path.is_ident("filter") {
    "`marker(<family>)` and `filter` are `#[derive(ingraph::NewType)]`'s words, where they choose \
     which interpretation a field of the type is read under. An id has no choice to make: it is \
     read as a COMPOSITE — one value occupying one column — and this device writes that reading, \
     its filter and the `<Name>Wire` the filter is parameterised by, all three unconditionally."
  } else if path.is_ident("cursor") {
    "`cursor` is `#[derive(ingraph::NewType)]`'s word for a keyset position, and this device writes \
     that row with no word at all: an id is what a page is ordered and resumed by, so a `CursorValue` \
     that had to be asked for would be a face every declaration asks for."
  } else if path.is_ident("sqlite") || path.is_ident("postgres") || path.is_ident("mysql") {
    "the dialect words are `#[derive(ingraph::NewType)]`'s, where they pick which dialects a value \
     is a column in. This device writes ONE set of storage rows for every dialect at once — a \
     `StoredAs<Db>`, a `Carrier<Db>` and an `Assemble` generic in the database, all three routed \
     through `ingraph::IdColumn<Db>` at the INNER — so there is no per-dialect choice here to make. \
     Which form a dialect stores is the inner type's answer through that seam, and a downstream \
     inner joins by writing that one row rather than by naming dialects here."
  } else if path.is_ident("mongo") {
    "`mongo` names the document kit, and this device does not write it. Neither live register wrote \
     one either: `MediaId` and `VolumeId` both stop at the SQL pair, so a document row here would \
     be the first of its kind and unmeasured. The seat is held rather than filled."
  } else if path.is_ident("rename") {
    "`rename = \"…\"` moves the name a SCHEMA publishes, and an id does not take one: the type's \
     own name is the only thing a client can correlate an address with, and both live registers \
     spell `#[Scalar(name = \"<the type>\")]` with nothing beside it."
  } else {
    return None;
  };
  Some(word.to_owned())
}