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 JOURNAL declaration into the model the emitter consumes.
//!
//! ```ignore
//! #[ingraph::journal(root = "MediaId", sqlite)]
//! pub struct VideoJournal;
//! ```
//!
//! # The pass MINTS a declaration and then reads it as an ordinary one
//!
//! Every other front end here reads what an author wrote. This one writes most of it: the host is a
//! MARKER — a unit struct whose name is the only thing in it the author chose — and the four
//! canonical columns are [`ingraph_codegen::journal::columns`]' mint. What this pass does is read
//! the two words it takes, swap the minted fields into the host, and hand the result to
//! [`crate::parse`] under [`NodeKind::Record`] — or under [`NodeKind::Entity`], where it named no
//! store. So the grammar below is small on purpose: every rule
//! about columns, keys, storage blocks and storability is the RECORD's, reached rather than
//! restated, and a journal is refused by the same sentences a record is.
//!
//! # What the grammar takes, and why everything else is refused BY NAME
//!
//! - **`root = "<Type>"`**, required — the chain root the journal is keyed by, spelled as a type in
//!   a string, which is this grammar's rule for every type it names. One journal table per ROOT
//!   FAMILY, so the word is what says which family.
//! - **the STORE WORDS**, bare and passed through VERBATIM — where the rows land, which is the one
//!   thing about a canonical journal a deployment still decides. They used to arrive wrapped in a
//!   `persist(…)` and they sit at the head now, on the record's own unwrap: storage is the essence
//!   of a thing that holds rows, and a journal is one. Nothing here interprets them: this grammar
//!   knows only which WORDS start a store, and the record grammar owns every word inside one, so a
//!   database block, a `table = "…"`, an `alias(…)` and their refusals all arrive unchanged.
//!
//!   A journal that names NO store mounts an [`NodeKind::Entity`] instead of a record, which is the
//!   *pure-compute journal* the word always offered, now with a tier under it: the same four
//!   columns, the same `(root, node)` key and the same `JournalRow` impl, with no table anywhere.
//!   The store words are what choose the rung, so a deployment states its posture once.
//! - **`crate = "…"`** — where `ingraph` lives, exactly as every other word in the family takes it,
//!   and this expansion spends it twice over: the row contract names the framework's trait and the
//!   `at` column is DECLARED as the framework's instant.
//!
//! Everything else is refused by name, and the two families of refusal say two different things. The
//! record's own SHAPE words — `lineage(…)`, `key(…)`, `graphql(…)`, `implements(…)`, `subscribe`,
//! `upstream(…)` — would each decide something the canonical shape has already decided, so their
//! refusal names the HAND path: a journal whose columns, key or wire face are its own is an ordinary
//! record with a `JournalRow` impl on it, which is the path the macro is sugar over and never
//! replaces. The three other STORAGE words are refused for the one-storage law's reason, exactly as
//! a record refuses them.

use ingraph_codegen::{journal::JournalModel, model::NodeKind};

use crate::{
  attribute::{self, named, set_once},
  errors::Errors,
  value,
};

#[cfg(test)]
mod tests;

/// A validated journal: the CANONICAL host this pass minted, and the model emitted beside it.
///
/// The host travels with the model because the caller emits it: an attribute macro replaces the item
/// it sits on, and what replaces a journal's marker struct is the four-column record it mounts.
pub(crate) struct Journal {
  /// The declaration the compiler will see — the author's marker struct with the canonical columns
  /// in it, and the `#[ingraph(…)]` markers this pass read still on the fields for [`crate::host`]
  /// to strip.
  pub(crate) host: syn::DeriveInput,
  /// The model, ready to emit.
  pub(crate) model: JournalModel,
}

/// 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<Journal> {
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let Options {
    root,
    persist,
    krate,
    krate_literal,
  } = options(arguments, &mut errors);
  marker(input, &mut errors);

  let Some(root) = root else {
    return Err(errors.seal(syn::Error::new_spanned(&input.ident, NO_ROOT)));
  };
  let krate = krate.unwrap_or_else(|| syn::parse_quote!(::ingraph));

  let host = mounted(input, &root, &krate);
  // WHICH RUNG the mount lands on is whether a store was named, and nothing else. A journal that
  // names one holds rows and is a `record`; a journal that names none is the same four columns, the
  // same `(root, node)` key and the same `JournalRow` impl with no table anywhere, which is exactly
  // what an `entity` is. The word `journal` is the SHAPE, and the ladder is the STORAGE — reading
  // the store words for the tier is what keeps the two from having to be written twice.
  //
  // It is also what keeps the record's own no-store refusal from reaching a declaration whose author
  // wrote no store word to be told about: that sentence ends in *declare it an entity*, and here the
  // grammar has already done so.
  let kind = if persist.is_some() {
    NodeKind::Record
  } else {
    NodeKind::Entity
  };
  let record = match crate::parse::parse(
    &host,
    &[canonical_options(krate_literal.as_ref(), persist.as_ref())],
    kind,
  ) {
    Ok(model) => model,
    Err(refused) => return Err(errors.seal(refused)),
  };

  errors.into_result(Journal {
    host,
    model: JournalModel { record, root },
  })
}

/// The two words this grammar takes, plus where `ingraph` lives.
#[derive(Default)]
struct Options {
  /// The chain root, as `root = "…"` named it.
  root: Option<syn::Type>,
  /// `persist(…)`'s contents, UNINTERPRETED — the record grammar owns every word inside.
  persist: Option<proc_macro2::TokenStream>,
  /// Where `ingraph` lives, as a path the emission spends.
  krate: Option<syn::Path>,
  /// The same, as the literal the record grammar is handed back — one authority for the path, and
  /// no round trip through a rendered path that could differ from the one that was written.
  krate_literal: Option<syn::LitStr>,
}

/// Walk the declaration-level attribute.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
  let mut options = Options::default();

  attribute::walk(attrs, errors, |meta, errors| {
    if meta.path.is_ident("root") {
      match value::parse_literal::<syn::Type>(&meta, ROOT_TYPE) {
        Ok(root) => set_once(
          &mut options.root,
          root,
          &meta.path,
          "`root` is declared more than once — one journal table is keyed by one root family",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // `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::literal(&meta, CRATE_PATH)
        .and_then(|spelled| Ok((spelled.parse::<syn::Path>()?, spelled)))
      {
        Ok((path, spelled)) => {
          set_once(
            &mut options.krate,
            path,
            &meta.path,
            "`crate` is declared more than once — one declaration names one crate",
            errors,
          );
          options.krate_literal.get_or_insert(spelled);
        }
        Err(e) => errors.push(syn::Error::new(e.span(), CRATE_PATH)),
      }
      return Ok(());
    }

    // THE WRAPPER, refused by name and carrying the migration — the record's own sentence, one
    // grammar over.
    if meta.path.is_ident("persist") {
      errors.push(named(&meta, PERSIST_UNWRAPPED.to_owned()));
      attribute::skip_entry(&meta);
      return Ok(());
    }

    // THE PASSTHROUGH. Each store word and its block are taken RAW and handed to the record grammar,
    // which is the one that knows what a database block, a `table = "…"` and an `alias(…)` mean —
    // reading them here would be a second authority for one storage vocabulary, and the two would
    // drift. What this grammar knows is only which WORDS start one, which it needs anyway to write
    // the refusals below.
    if STORE_WORDS.contains(
      &meta
        .path
        .get_ident()
        .map(ToString::to_string)
        .unwrap_or_default()
        .as_str(),
    ) {
      let word = meta.path.clone();
      let inner = if attribute::has_block(&meta) {
        let inner = attribute::verbatim(&meta)?;
        quote::quote!(#word(#inner))
      } else if attribute::has_value(&meta) {
        let value: syn::LitStr = meta.value()?.parse()?;
        quote::quote!(#word = #value)
      } else {
        quote::quote!(#word)
      };
      let forwarded = options
        .persist
        .get_or_insert_with(proc_macro2::TokenStream::new);
      if !forwarded.is_empty() {
        forwarded.extend(quote::quote!(,));
      }
      forwarded.extend(inner);
      return Ok(());
    }

    for (word, instead) in FIXED {
      if meta.path.is_ident(word) {
        errors.push(named(&meta, format!("`{word}` decides something a CANONICAL journal has already decided: {instead}. {HAND_PATH}")));
        return Ok(());
      }
    }

    for (word, noun) in STORES {
      if meta.path.is_ident(word) {
        errors.push(named(
          &meta,
          format!(
            "a journal holds ROWS — its store words name where they land, and {noun} is its OWN \
             node: declare it with the `{word}` macro, on a type whose `upstream(…)` names this \
             journal. ONE NODE HOLDS ONE STORAGE, so the MACRO IS the storage declaration"
          ),
        ));
        return Ok(());
      }
    }

    errors.push(attribute::unknown(
      &meta,
      UNKNOWN,
      &["root", "crate"]
        .into_iter()
        .chain(STORE_WORDS.iter().copied())
        .collect::<Vec<_>>(),
    ));
    Ok(())
  });

  options
}

/// The record words a canonical journal has no room for, each with what it would have decided.
///
/// Refused BY NAME rather than as unknown entries, for the reason every named refusal in this crate
/// exists: an author who writes one has a concrete idea, and the useful answer is where the idea is
/// already recorded — which for all six is the same place, the shape the word `journal` MEANS.
const FIXED: [(&str, &str); 6] = [
  (
    "lineage",
    "the path is the `root` column, which `root = \"…\"` already names",
  ),
  (
    "key",
    "the key is `(root, node)`, which `key = lineage ⊕ id` already spells over those two columns",
  ),
  (
    "graphql",
    "the wire face rides the four canonical columns, so there is no field for a block to name",
  ),
  (
    "implements",
    "an interface's contract is a promise about COLUMNS, and a journal's four are the framework's \
     rather than a declaration's to agree with",
  ),
  (
    "subscribe",
    "a journal is written by the drive layer through `JournalRow`, so its inputs are observations \
     rather than an upstream node's messages",
  ),
  (
    "upstream",
    "a journal is written by the drive layer through `JournalRow`, so its inputs are observations \
     rather than an upstream node's messages",
  ),
];

/// The three other storage words, and the noun each refusal names.
const STORES: [(&str, &str); 3] = [
  ("fulltext", "a full-text index"),
  ("vector", "an embedding index"),
  ("blob", "an artifact family"),
];

/// The sentence every FIXED refusal ends with — the path that is not going away.
const HAND_PATH: &str = "A journal whose columns, key or wire face are its own is the HAND path, \
                         which this word does not replace: declare an ordinary \
                         `#[ingraph::record(…)]` with whatever columns you want and implement \
                         `JournalRow` on it. The macro is sugar over that contract, so the two are \
                         one seam to every writer";

/// The refusal an unrecognised entry gets, naming the whole grammar.
const UNKNOWN: &str = "unknown `ingraph` journal attribute — a journal takes `root = \"…\"`, its \
                       STORE WORDS (`sqlite`, `postgres`, `mysql`, `mongo`, with `table = \"…\"` \
                       and `rename = \"…\"` beside them) and `crate = \"…\"`, and nothing else: \
                       its four columns (`root`, `node`, `station`, `at`) and its `(root, node)` \
                       key are the word's own, which is what CANONICAL means";

/// The WORDS that start a store, which is the whole of what this grammar knows about storage.
///
/// The two common entries ride the list because they are forwarded the same way and refused the same
/// way; what each one MEANS is still the record grammar's.
const STORE_WORDS: [&str; 6] = ["sqlite", "postgres", "mysql", "mongo", "table", "rename"];

/// The refusal the retired wrapper gets — the record's own sentence, one grammar over.
const PERSIST_UNWRAPPED: &str = "`persist(…)` is gone — a journal names its stores BARE, so write \
                                 `#[ingraph::journal(root = \"…\", sqlite)]` and keep every word \
                                 that was inside each database's own block. Storage is the essence \
                                 of a thing that holds rows, and an essence does not wrap";

/// The refusal a `root` this grammar cannot read gets.
const ROOT_TYPE: &str = "`root = \"…\"` names the chain root this journal is keyed by, as a type in \
                         a string literal";

/// The refusal a `crate` this grammar cannot read gets.
const CRATE_PATH: &str =
  "`#[ingraph::journal(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";

/// The refusal a journal with no root gets.
const NO_ROOT: &str = "a journal needs `root = \"…\"` — there is ONE journal table per ROOT FAMILY, \
                       and the word is what says which family: \
                       `#[ingraph::journal(root = \"media::MediaId\", sqlite)]`. The type \
                       is spelled as a path in a string, which is this grammar's rule for every type \
                       it names";

/// A journal's host is a MARKER — a unit struct, and nothing else.
///
/// The refusal for a struct that carries fields is the teaching one, because an author who wrote
/// them has the right idea and the wrong path: custom columns are exactly what the HAND path is for,
/// and it is still there.
fn marker(input: &syn::DeriveInput, errors: &mut Errors) {
  if !input.generics.params.is_empty() {
    errors.push(syn::Error::new_spanned(
      &input.generics.params,
      "a journal takes no generic parameter — the record it mounts is CONCRETE, because a key \
       column's type is read straight off the declaration, and `root = \"…\"` is how this one's is \
       named",
    ));
  }
  match &input.data {
    syn::Data::Struct(data) if matches!(data.fields, syn::Fields::Unit) => {}
    syn::Data::Struct(_) => errors.push(syn::Error::new_spanned(
      &input.ident,
      format!(
        "a journal's host is a MARKER — write `struct {name};` and nothing inside it. The four \
         canonical columns (`root`, `node`, `station`, `at`) are this word's own mint, so a field \
         written here would be a second author for a shape that is already decided. {HAND_PATH}",
        name = input.ident,
      ),
    )),
    syn::Data::Enum(_) | syn::Data::Union(_) => errors.push(syn::Error::new_spanned(
      &input.ident,
      "a journal's host is a marker STRUCT — `#[ingraph::journal(…)]` mounts a RECORD, and a record \
       is a struct. There is nothing here for a variant or a union field to be",
    )),
  }
}

/// The host the compiler will see: the author's marker with the canonical columns swapped in.
///
/// EVERYTHING ELSE OF THE AUTHOR'S SURVIVES — the name, the visibility, their own derives, their
/// `cfg`s, their doc comments — because the item is cloned and only its BODY is replaced. What is
/// taken out is the one thing this pass consumed: an `#[ingraph(…)]` beside the attribute, which
/// [`crate::host::refuse_a_moved_option_block`] has already reported and which would otherwise be
/// reported a second time by the record pass reading the same host.
fn mounted(input: &syn::DeriveInput, root: &syn::Type, krate: &syn::Path) -> syn::DeriveInput {
  let mut host = input.clone();
  host.attrs.retain(|attr| !attr.path().is_ident("ingraph"));
  host.data = syn::Data::Struct(syn::DataStruct {
    struct_token: syn::token::Struct::default(),
    fields: syn::Fields::Named(ingraph_codegen::journal::columns(root, krate)),
    semi_token: None,
  });
  host
}

/// The record options the mounted declaration is parsed under.
///
/// `lineage(fields(root))` is the whole of what this pass decides about the key: the root is the
/// path and the `node` field carries the id, so `key = lineage ⊕ id` spells `(root, node)`. The
/// other two entries are what the author wrote, handed on unchanged.
fn canonical_options(
  krate: Option<&syn::LitStr>,
  persist: Option<&proc_macro2::TokenStream>,
) -> syn::Attribute {
  let krate = krate.map(|spelled| quote::quote!(, crate = #spelled));
  let persist = persist.map(|inner| quote::quote!(, #inner));
  syn::parse_quote!(#[ingraph(lineage(fields(root)) #krate #persist)])
}