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 shareable-resource declaration into the model the emitter consumes.
//!
//! The smallest front end in this crate, smaller even than the graph root's: a resource declares
//! no storage, no faces and no list. Its whole content is that the type is DECLARED, plus the two
//! words the resource axis added — WHICH BUILTIN ENGINE it is, where it is one of the framework's
//! own, and WHICH FACE its engine impls wear, where it is somebody else's.
//!
//! # What this pass can see, and what it cannot
//!
//! It sees TOKENS, so it enforces the SHAPE and nothing else. Whether the type satisfies the
//! resource CONTRACT is not a token question at all, and it is not left unchecked either: the
//! emission states one bound over the declared type, so a type with no `AsyncResource` impl, or one
//! that is not `Send + Sync`, is `E0277` where the declaration is written.
//!
//! The MODE WORD is the same division from the other side. Whether an author's hand-written faces
//! really are the awaited ones is not a token question either, and the word does not pretend to
//! settle it: it is recorded, the binding spells the face it names, and a word that lied is `E0277`
//! at the binding. Words CHOOSE; bounds PROVE.
//!
//! # Why the shape rule is the generic one, and why a KIND WORD adds a second
//!
//! Every other declaration in this crate is a struct or an enum because the emission reads its
//! FIELDS or its VARIANTS. The FOREIGN form reads neither: a resource is reached through
//! `Shared<R>`, which derefs to the type, so what a member can do with one is the author's own
//! inherent impl. A tuple struct, a unit struct and an enum are all perfectly good resources, so
//! refusing any of them would be this pass inventing a rule the tier does not have.
//!
//! A GENERIC one is refused, and for the graph root's reason one tier over: the emission writes
//! one citizenship impl for one type, and a parameter is not a type until it is substituted — so a
//! generic declaration would either register a different resource per instantiation or need a
//! blanket impl this pass has no way to bound.
//!
//! A BUILTIN one is refused unless it is a UNIT STRUCT, and that rule is the emission's rather than
//! this pass's taste: a kind word MINTS the engine and injects it into the declaration, so a
//! declaration that already holds something would end up carrying two engines with the macro able to
//! name only one of them.

use ingraph_codegen::prefix::EmissionPrefix;
use ingraph_codegen::resource::{ResourceKind, ResourceMode, ResourceModel};

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

#[cfg(test)]
mod kind_tests;
#[cfg(test)]
mod tests;

/// Validate a decorated declaration 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,
  arguments: &[syn::Attribute],
) -> syn::Result<ResourceModel> {
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let Words {
    krate,
    kind,
    asynchronous,
  } = options(arguments, &mut errors);
  concrete(&input.generics, &mut errors);

  if let Some((builtin, at)) = kind.as_ref() {
    if let Some(word) = asynchronous.as_ref() {
      errors.push(syn::Error::new_spanned(
        word,
        format!(
          "`{word}` already knows which face its engine wears — a BUILTIN kind word CARRIES the \
           mode, and `async` beside it is a second opinion that could only disagree with it. The \
           mode word is the FOREIGN form's, where the faces are hand-written and nothing but the \
           declaration can see which ones they are",
          word = builtin.word()
        ),
      ));
    }
    mints_its_own_engine(*builtin, at, input, &mut errors);
  }

  // A BUILTIN's mode is the KIND's, and a foreign one's is the word's — which is the whole of what
  // "the kind word carries the mode knowledge" means, cashed in one expression.
  let kind = kind.map(|(kind, _)| kind);
  let mode = match (kind, asynchronous.is_some()) {
    (Some(kind), _) => kind.mode(),
    (None, true) => ResourceMode::Async,
    (None, false) => ResourceMode::Block,
  };

  errors.into_result(ResourceModel {
    prefix: EmissionPrefix::default(),
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    name: input.ident.clone(),
    kind,
    mode,
  })
}

/// What the declaration-level attribute carried, each word with the token it was written at.
struct Words {
  /// `crate = "…"` — where `ingraph` lives.
  krate: Option<syn::Path>,
  /// The BUILTIN kind word, and where it was written.
  kind: Option<(ResourceKind, syn::Path)>,
  /// The `async` word, where it was written.
  asynchronous: Option<syn::Path>,
}

/// Walk the declaration-level attribute: where `ingraph` lives, which builtin engine this is, and
/// which face its impls wear.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Words {
  let mut krate: Option<syn::Path> = None;
  let mut kind: Option<(ResourceKind, syn::Path)> = None;
  let mut asynchronous: 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,
        "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
      ) {
        Ok(path) => {
          if krate.replace(path).is_some() {
            errors.push(syn::Error::new_spanned(
              &meta.path,
              "`crate` is declared more than once — one declaration names one crate",
            ));
          }
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // THE MODE WORD. A bare declaration is on the BLOCKING face and this is what buys the awaited
    // one — the same lexicon `source(async)`, `handler(async)` and `operator(async)` are written in.
    // It carries nothing, because what the faces DO is the author's impls and the whole content of
    // the word is which pair of them the binding will spell.
    if meta.path.is_ident("async") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(
          &meta,
          "`async` is a bare word here — it names the FACE this resource's engine impls wear, and \
           the impls themselves are the author's own, so there is nothing to configure"
            .to_owned(),
        ));
        return Ok(());
      }
      attribute::set_once(
        &mut asynchronous,
        meta.path.clone(),
        &meta.path,
        "`async` is declared more than once — one declaration wears one face",
        errors,
      );
      return Ok(());
    }

    // THE KIND WORD, and the whole vocabulary is `ResourceKind`'s — so a word cannot be spellable
    // here and unknown to the emitter.
    if let Some(named) = meta.path.get_ident().map(ToString::to_string)
      && let Some(builtin) = ResourceKind::from_word(&named)
    {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(
          &meta,
          format!(
            "`{named}` is a bare word — it names WHICH framework engine this resource is, and how \
             one is tuned is the engine's own options, which reach it through the `[resources.…]` \
             section its mount names rather than through this attribute"
          ),
        ));
        return Ok(());
      }
      attribute::set_once(
        &mut kind,
        (builtin, meta.path.clone()),
        &meta.path,
        "a kind word is declared more than once — one resource is one engine",
        errors,
      );
      return Ok(());
    }

    errors.push(attribute::unknown(&meta, &unknown(), &vocabulary()));
    Ok(())
  });

  Words {
    krate,
    kind,
    asynchronous,
  }
}

/// Every word this grammar takes — what a near miss is measured against.
fn vocabulary() -> Vec<&'static str> {
  let mut words = vec!["crate", "async"];
  words.extend_from_slice(ResourceKind::WORDS);
  words
}

/// The sentence an unrecognised entry earns: what this grammar takes, and where the facts it does
/// NOT take actually live.
///
/// Built rather than written out, the kind-word list being the emitter's — which is what keeps the
/// vocabulary a message TEACHES and the vocabulary the emitter can WRITE the same list, in the one
/// place either of them is named.
fn unknown() -> String {
  let kinds = ResourceKind::WORDS
    .iter()
    .map(|word| format!("`{word}`"))
    .collect::<Vec<_>>()
    .join(", ");
  format!(
    "unknown entry in `#[ingraph(…)]` on a resource — it takes `crate = \"…\"`, the `async` word, \
     and one BUILTIN KIND WORD ({kinds}), and nothing else. How a FOREIGN one is BUILT is the \
     `AsyncResource` impl's (`type Options`, `build`), and where its options come from is the \
     launch's"
  )
}

/// A resource declaration carries no generic parameter.
///
/// The emission writes ONE citizenship impl for ONE type, and a parameter is not a type until it is
/// substituted: a generic declaration would register a different resource per instantiation, and
/// the walk that enumerates citizens has one entry per declaration rather than one per
/// instantiation.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  if generics.params.is_empty() {
    return;
  }
  errors.push(syn::Error::new_spanned(
    &generics.params,
    "a resource takes no generic parameter — the declaration registers ONE type as a citizen of \
     the walk, and a parameter is not a type until it is substituted, so a generic one would name \
     a different resource per instantiation",
  ));
}

/// A BUILTIN declaration holds nothing of its own, because the macro puts the engine there.
///
/// The one rule the kind word adds to a grammar that otherwise admits every shape. It is the
/// EMISSION's rule rather than this pass's preference: the expansion re-emits the declaration
/// carrying the engine it mints, so a declaration that already holds a value would carry two engines
/// with only one of them nameable — and an author who wrote the inner type meant the FOREIGN form,
/// where writing it is exactly right.
fn mints_its_own_engine(
  kind: ResourceKind,
  at: &syn::Path,
  input: &syn::DeriveInput,
  errors: &mut Errors,
) {
  let holds = match &input.data {
    syn::Data::Struct(data) => !matches!(data.fields, syn::Fields::Unit),
    syn::Data::Enum(_) | syn::Data::Union(_) => true,
  };
  if !holds {
    return;
  }
  errors.push(syn::Error::new_spanned(
    at,
    format!(
      "`{word}` MINTS this resource's engine, so the declaration it takes holds nothing of its own \
       — write `struct {name};` and let the expansion put the engine inside it. A declaration that \
       already holds something is the FOREIGN form's shape: drop the kind word, and the engine \
       impls beside it are yours to write",
      word = kind.word(),
      name = input.ident
    ),
  ));
}