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 an ORIGIN's declaration into the model the emitter consumes.
//!
//! A source declaration says two things and no more: which FACE this origin wears, and which mutation
//! node — if any — is its command vocabulary. Everything else about an origin is written in the
//! `impl` beside it, because everything else about an origin is a TYPE.
//!
//! ```ignore
//! #[ingraph::source(async, mutation(node = "WatchOps"))]
//! pub struct Watch { … }
//! ```
//!
//! # The two words, and why neither could be inferred
//!
//! | word | what it decides |
//! |---|---|
//! | `async` | which of the two faces the bound below names — `Source` or `AsyncSource` |
//! | `mutation(node = "…")` | which node this origin's `Control` line carries, and the wire face that answers it |
//!
//! `async` is the dual-mode law's word-selects-face rule at the one position that has to NAME a
//! trait; and the node word is the declaration half of a double entry whose other half is the
//! author's own `type Mutation`. See the emitter's own note for why both halves exist and what the
//! bound between them refuses.
//!
//! # What this pass can see, and what it cannot
//!
//! It sees TOKENS. So it enforces the SHAPE — no generic parameter, one `mutation` word at most, a
//! `node` inside it — and nothing about whether the path it was handed resolves to anything, or
//! whether the type beneath the attribute implements the face the word named. Both are the
//! EMISSION's, where the compiler can see them.

use ingraph_codegen::source::SourceModel;

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

#[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<SourceModel> {
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let (krate, awaited, node) = options(arguments, &mut errors);
  concrete(&input.generics, &mut errors);

  errors.into_result(SourceModel {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    name: input.ident.clone(),
    awaited,
    node,
  })
}

/// Walk the declaration-level attribute: the face, the mounted node, and where `ingraph` lives.
fn options(
  attrs: &[syn::Attribute],
  errors: &mut Errors,
) -> (Option<syn::Path>, bool, Option<syn::Path>) {
  let mut krate: Option<syn::Path> = None;
  let mut awaited: Option<syn::Path> = None;
  let mut node: Option<syn::Path> = None;
  // The `mutation` WORD, whether or not the block inside it could be read: the single-mount rule is
  // about how many times the word was written, and a block that named nothing has earned its own
  // error already.
  let mut mounted_at: 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) => attribute::set_once(
          &mut krate,
          path,
          &meta.path,
          "`crate` is declared more than once — one declaration names one crate",
          errors,
        ),
        Err(e) => refuse_value(&meta, e, errors),
      }
      return Ok(());
    }

    if meta.path.is_ident("async") {
      attribute::set_once(
        &mut awaited,
        meta.path.clone(),
        &meta.path,
        "`async` is declared more than once — one origin wears one face",
        errors,
      );
      attribute::skip_entry(&meta);
      return Ok(());
    }

    if meta.path.is_ident("mutation") {
      if mounted_at.is_some() {
        errors.push(syn::Error::new_spanned(&meta.path, SECOND_MOUNT));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      mounted_at = Some(meta.path.clone());
      return mount(&meta, &mut node, errors);
    }

    errors.push(attribute::unknown(
      &meta,
      "unknown entry in `#[ingraph::source(…)]` — it takes `async` (which face this origin's body \
       wears), `mutation(node = \"…\")` (the node whose fields are its commands) and `crate = \
       \"…\"`. WHAT it produces, what it takes to build and how it fails are the `impl`'s, being \
       types rather than words",
      &["async", "mutation", "crate"],
    ));
    Ok(())
  });

  (krate, awaited.is_some(), node)
}

/// The `mutation(…)` block — whose whole content is the ONE node this origin mounts.
fn mount(
  meta: &syn::meta::ParseNestedMeta<'_>,
  node: &mut Option<syn::Path>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    errors.push(attribute::unknown(meta, MOUNT_EMPTY, &[]));
    return Ok(());
  }

  // The `node` WORD, kept beside its value for `handler(…)`'s reason one grammar over: a value that
  // could not be read has earned its one error, and the missing-word sentence below would be that
  // error's echo.
  let mut node_at: Option<syn::Path> = None;

  let walked = meta.parse_nested_meta(|inner| {
    if inner.path.is_ident("node") {
      node_at = Some(inner.path.clone());
      match value::parse_literal::<syn::Path>(&inner, MOUNT_NODE) {
        Ok(path) => attribute::set_once(
          node,
          path,
          &inner.path,
          "`node` is declared more than once in `mutation(…)` — one block names one command face",
          errors,
        ),
        Err(e) => refuse_value(&inner, e, errors),
      }
      return Ok(());
    }

    errors.push(attribute::unknown(
      &inner,
      "unknown entry in `mutation(…)` — it names the NODE this origin is controlled through and \
       nothing else. What that node's commands are, which handler runs each and how each fails are \
       the node's own declaration",
      &["node"],
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }

  if node.is_none() && node_at.is_none() {
    errors.push(syn::Error::new_spanned(&meta.path, MOUNT_EMPTY));
  }
  Ok(())
}

/// Record a refusal about an entry's VALUE, and swallow the entry it was written in.
///
/// [`attribute::unknown`]'s law applied to the other half of a grammar, exactly as the mutation
/// grammar's own reader states it: a value reader leaves the token it could not read where it found
/// it, so a walk that resumed there would earn syn's own `expected ,` at the same column.
fn refuse_value(meta: &syn::meta::ParseNestedMeta<'_>, error: syn::Error, errors: &mut Errors) {
  errors.push(error);
  attribute::skip_entry(meta);
}

/// A source declaration takes no generic parameter.
///
/// The emission states ONE bound over ONE type, and a parameter is not a type until it is
/// substituted — so a generic declaration would state a bound about a type nobody has named, and the
/// double entry it exists to hold together would check nothing.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  const WHY: &str = "a source takes no generic parameter — the declaration states ONE bound over \
                     ONE origin, and a parameter is not a type until it is substituted, so a \
                     generic one would check the double entry for nobody";
  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 refusal a SECOND `mutation(…)` earns — the amendment's own sentence, verbatim.
///
/// It refuses to the FUNCTIONALITY rather than to the grammar: a second mount is not nonsense, it is
/// a widening this version did not take, and the sentence says which day it arrives.
const SECOND_MOUNT: &str = "one command face per source — more words go in the node; the day two vocabularies truly \
   diverge, mounts will widen";

/// The refusal a `mutation` written as a bare word, an empty block, or a block with no `node` earns.
const MOUNT_EMPTY: &str = "`mutation` names no node — write `mutation(node = \"path::to::Node\")`. An origin nobody \
   controls omits the word entirely, which is the declaration whose `type Mutation` is `()`";

/// The refusal a `node` that is not a quoted path earns.
const MOUNT_NODE: &str = "`mutation(node = \"…\")` names the node this origin is controlled through — quoted, because \
   the word names a TYPE this declaration cannot resolve and the compiler resolves where the \
   expansion lands";