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
//! **THE SUGAR WORD'S EXPANSION** — `knn(searchable(tower = "…"))` written back out as the
//! `#[ingraph::search]` recipe an author would otherwise have typed, and put through the pipeline
//! that reads a typed one.
//!
//! ```ignore
//! #[ingraph::vector(upstream(node = "Keyframe", clip = "clip"), dedup(hash), graphql(async_graphql))]
//! pub struct Shots {
//!   #[ingraph(embedding, knn(searchable(tower = "crate::ClipText")), toy)]
//!   clip: Embedding<f32, DIM, Clip>,
//! }
//! ```
//!
//! forges, beside the index's own expansion:
//!
//! ```ignore
//! #[ingraph::search(crate = "::ingraph",
//!                   shared(question(type = "<crate::ClipText as ::ingraph::SearchTower>::Question")),
//!                   graphql(async_graphql))]
//! pub struct ShotsClipSearch {
//!   #[ingraph(tower(question(type = "crate::ClipText", shared)))]
//!   shots: Shots,
//! }
//! ```
//!
//! # NOTHING IS UNDER IT, and that is the whole claim
//!
//! This module builds a DECLARATION and hands it to [`super::parse`] and `SearchModel::emit` — the
//! same two functions the attribute macro calls, in the same order, with the host echoed the same
//! way. There is no recipe emitter for a forged recipe, no runtime trait a sugared column has and a
//! hand-written one does not, and no branch anywhere downstream that asks which of the two it is
//! looking at. `sugar/tests.rs` pins the claim by expanding both and comparing the tokens.
//!
//! The consequence a reader should draw from that is the SUPPORT boundary: a sugared column has
//! exactly the recipe words this module writes, and the moment a second one is wanted — a weight, a
//! floor, a second member, a second seat — the answer is to write the recipe, not to grow this
//! grammar. The refusal inside `searchable(…)` says so in as many words.
//!
//! # The four things the word decides, and where each comes from
//!
//! | piece | source |
//! |---|---|
//! | the recipe's NAME, and therefore its wire fields | `{Index}{Field}Search`, in the emission's own camel-join convention |
//! | the shared SEAT's type | the TOWER's, read as `<Tower as SearchTower>::Question` rather than restated |
//! | the arm's binding | `shared`, bare — one seat and one arm of one name, so the resolution is by name |
//! | whether a wire field lands at all | the INDEX's own `graphql(…)` block, passed through |
//!
//! The seat's type is a PROJECTION and not a copy, which is the property that keeps the two
//! declarations from drifting: a tower that changes what it is asked changes this seat with it, and
//! a recipe that had restated the type would have gone quietly wrong at the next edit.

use heck::ToUpperCamelCase as _;
use ingraph_codegen::{
  index::{Elected, IndexModel},
  search::SearchModel,
};
use quote::quote;

#[cfg(test)]
mod tests;

/// Every recipe this declaration's elections asked for, expanded.
///
/// EMPTY where no election wrote the word, which is every declaration written before it existed —
/// the sugar adds items and moves none, so an index that says nothing expands to exactly what it
/// expanded to yesterday.
pub(crate) fn recipes(model: &IndexModel) -> proc_macro2::TokenStream {
  let forged = model
    .embeddings
    .iter()
    .filter_map(|elected| Some(forge(model, elected, elected.tower_road.as_ref()?)));
  quote!(#(#forged)*)
}

/// ONE forged recipe, through the recipe macro's own body.
///
/// The order is `equipped`'s, because it IS `equipped`'s: echo the host, parse, emit. A refusal
/// becomes a `compile_error!` beside the host for the reason every other one does — an attribute
/// macro replaces the item it sits on, so deleting the type would bury the message under every
/// mention of it.
fn forge(model: &IndexModel, elected: &Elected, tower: &syn::Type) -> proc_macro2::TokenStream {
  let (arguments, input) = declaration(model, elected, tower);
  let host = crate::host::echo(&input);
  let expansion = super::parse(&input, &arguments)
    .as_ref()
    .map_or_else(syn::Error::to_compile_error, SearchModel::emit);
  quote!(#host #expansion)
}

/// The two-piece set as TOKENS — the recipe's arguments and the struct they sit on.
///
/// Separate from [`forge`] so a test can read the DECLARATION this word stands for, which is the
/// thing an author has to be able to picture: the equivalence pin compares expansions, and this
/// function is what makes the two sides of it readable side by side.
pub(crate) fn declaration(
  model: &IndexModel,
  elected: &Elected,
  tower: &syn::Type,
) -> (Vec<syn::Attribute>, syn::DeriveInput) {
  let krate = &model.krate;
  let index = &model.index;
  let vis = &model.vis;
  let at = elected.field.span();
  let name = recipe_name(index, &elected.field);
  let member = member_name(index);

  // QUOTED, because that is how the recipe grammar takes a type it did not mint — and the seat's is
  // the tower's own associated type rather than a spelling of it, so the two declarations cannot
  // disagree about what a question is.
  let seat = literal(&quote!(<#tower as #krate::SearchTower>::Question), at);
  let walked = literal(&quote!(#tower), at);
  let krate_word = literal(&quote!(#krate), at);
  let graphql = graphql_word(model);
  let arguments = vec![syn::parse_quote! {
    #[ingraph(crate = #krate_word, shared(question(type = #seat)) #graphql)]
  }];

  let input = syn::parse_quote! {
    #vis struct #name {
      #[ingraph(tower(question(type = #walked, shared)))]
      #member: #index,
    }
  };
  (arguments, input)
}

/// `graphql(<backend>, …)` for the forged recipe — the INDEX's own block, passed through.
///
/// Inherited rather than always written, and never invented: the recipe's wire face is what this
/// word is for, but WHICH backends dress a declaration is a decision its author already made one
/// grain up. An index that dresses nothing forges a recipe that dresses nothing — it still mints
/// the fusion door and the packages, exactly as a hand-written `#[ingraph::search]` with no
/// `graphql(…)` does.
fn graphql_word(model: &IndexModel) -> proc_macro2::TokenStream {
  let Some(block) = model.graphql.as_ref() else {
    return proc_macro2::TokenStream::new();
  };
  let backends = block.backends.iter().map(|backend| {
    let word = syn::Ident::new(backend.kind.as_str(), model.index.span());
    quote!(#word)
  });
  quote!(, graphql(#(#backends),*))
}

/// `{Index}{Field}Search` — the forged recipe's name.
///
/// The emission's own camel-join convention, for the reason `{Index}{Field}{Engine}` and
/// `{Record}By{Field}` take it: a name a declaration can COLLIDE with is refused at the declaration
/// rather than mangled out of reach, and a reader who has to find this type in a schema can spell
/// it. It is also the wire face — `shotsClipSearch` and `shotsClipSearchKeys` are `lower_initial`
/// of exactly this — so a mangled name would have crossed the wire.
fn recipe_name(index: &syn::Ident, field: &syn::Ident) -> syn::Ident {
  quote::format_ident!(
    "{index}{}Search",
    field.to_string().to_upper_camel_case(),
    span = field.span(),
  )
}

/// The forged recipe's ONE member field — the index, under its own name.
///
/// The INDEX's name and not the election's, because a member IS an index: it is what the evidence
/// arm is named after (`{Recipe}{Member}Sighting`), and naming it for the column would tell a reader
/// of that arm that the recipe fuses columns.
fn member_name(index: &syn::Ident) -> syn::Ident {
  quote::format_ident!(
    "{}",
    heck::ToSnakeCase::to_snake_case(index.to_string().as_str()),
    span = index.span(),
  )
}

/// Tokens as the quoted string the recipe grammar reads a type out of.
fn literal(tokens: &proc_macro2::TokenStream, at: proc_macro2::Span) -> syn::LitStr {
  syn::LitStr::new(&tokens.to_string(), at)
}