ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What a SEARCH RECIPE declared: the members it fuses, the towers it binds to them, and the seats
//! a caller broadcasts one question into.
//!
//! ```ignore
//! #[ingraph::search(shared(text(type = "String")), dedup(hash), limit = 20)]
//! pub struct TravelSearch {
//!   #[ingraph(weight = 1.0, depth = 50, tower(zh(type = "crate::ZhQuery", shared)))]
//!   subs: Subs,
//!   #[ingraph(weight = 2.0, depth = 100,
//!     tower(text(type = "crate::ClipText", shared, floor = "crate::floors::SEM_TEXT")),
//!     tower(image(type = "crate::ClipImage", shared)))]
//!   shots: Shots,
//! }
//! ```
//!
//! # FIELDS ARE MEMBERS, which is what deleted the word-count door laws
//!
//! A recipe LISTS what it fuses. A field's NAME is the member's name and its TYPE is the index that
//! member reads, so there is nothing here that mints a name, nothing that counts words to decide how
//! many members a door has, and nothing to trim: the arity is the declaration's own field list. That
//! is the same collapse the tower grammar made one layer down, where fields became steps.
//!
//! # THE MODEL IS ONE CLOCK, and the compiler is the other
//!
//! Everything here is what the DECLARATION SAID. A tower is carried as the TYPE PATH the word
//! named, never as a name this pass mangled out of one and never as a fact it went looking for:
//! whether that type is a tower, what it is asked, what it answers and what knobs it seats are
//! questions only the compiler can answer, and the emission asks them as projections off
//! `DeclaredTower` and `SearchTower` where it can see them. A model that resolved a path would be
//! guessing across the expansion wall — the wall the `Declared…` record family exists to be
//! shouted over.
//!
//! # ABSENCE IS A ROAD at every number here
//!
//! `weight`, `depth`, `limit` and both `floor`s are [`Option`], and [`None`] never means a value
//! this pass invented. It means the declaration named none, and the tier below it answers: the
//! resolution order is request > this recipe > the election's own field > its container > the
//! framework's own number. A model that defaulted a number here would be a recipe silently
//! outranking an election that had a better answer.

use core::num::NonZeroU32;

use quote::quote;

use crate::index::Dedup;

mod bind;
mod fuse;
mod record;
#[cfg(test)]
mod tests;
mod wire;

/// A validated search recipe, ready to emit.
///
/// PLAIN — no `Copy`, no comparison — for [`super::tower::TowerModel`]'s reason: a model is carried
/// once, from the pass that validated it to the pass that emits it.
#[derive(Debug, Clone)]
pub struct SearchModel {
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  pub krate: syn::Path,
  /// The declared type — what the recipe's own faces are minted on.
  pub name: syn::Ident,
  /// The declaration's own visibility, which everything minted beside it takes.
  pub vis: syn::Visibility,
  /// **THE BROADCAST SEATS** — `shared(text(type = "String"), …)`, in declaration order.
  ///
  /// EMPTY where the head wrote no `shared(…)` at all, which is the recipe whose arms are each
  /// asked their own question. A seat is what a caller fills once for the whole recipe, and the
  /// arms that read it say so with their own `shared` word.
  ///
  /// SEVERAL are a CHOICE and never a companion: the published field asks with one `@oneOf` object
  /// and a client fills exactly one seat, so a value that rides WITH a question — a language tag, a
  /// locale — is a field of a seat's own TYPE rather than a seat beside it. Written as a seat it
  /// would be unaskable beside the question it belongs to. The grammar's own note carries the
  /// boundary in full; see `ingraph-derive`'s `search` module.
  pub seats: Vec<SeatModel>,
  /// How this recipe's fused doors tell two roots apart — `dedup(hash)`.
  ///
  /// NOT an [`Option`], and that is the graph root's own shape one grain down: the absent word is
  /// [`Dedup::Hash`] rather than a deferral, because every key an emitted node mints derives
  /// [`Hash`](core::hash::Hash) and the join a recipe has always had is the one an unwritten word
  /// still names.
  pub dedup: Dedup,
  /// How many roots the recipe's own door answers with when nothing asks otherwise — `limit = 20`.
  ///
  /// [`None`] where the word was OMITTED, and it is a deferral rather than a default: the tier
  /// order is request > recipe > election field > container > the framework's own number, so a
  /// recipe that names none lets the declaration below it answer. Writing the framework's 20 in
  /// here would make an unwritten word outrank an election that wrote its own.
  pub limit: Option<NonZeroU32>,
  /// WHICH BACKEND DRESSES THIS RECIPE — `graphql(async_graphql)`, or [`None`] where it named none.
  ///
  /// The retrieving family's presence law at the recipe grain: a recipe with no block emits its
  /// whole Rust surface — the record, the packages, the evidence enums and the door — and mints no
  /// schema. That is what a fused read a deployment drives from Rust wants, and it is also what
  /// keeps the wire face's own demands off a recipe that publishes nothing: the seams a resolver
  /// reaches its members through ([`FusedEngine`], [`FusedCitizen`], [`WireRoot`]) are asked for
  /// only where a field is published.
  ///
  /// [`FusedEngine`]: https://docs.rs/ingraph
  /// [`FusedCitizen`]: https://docs.rs/ingraph
  /// [`WireRoot`]: https://docs.rs/ingraph
  pub graphql: Option<crate::model::GraphqlKind>,
  /// The members, in declaration order. NEVER EMPTY: a recipe with no member is refused at the
  /// front end, there being nothing to ask and nothing to fuse.
  pub members: Vec<MemberModel>,
}

impl SearchModel {
  /// EVERYTHING a recipe mints: the record it states across the expansion wall, and the fusion unit
  /// its door runs.
  ///
  /// The recipe REPLACES its own declaration, as every attribute macro does, so the host struct is
  /// echoed by the front end and what arrives here is only what is added beside it.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let record = self.record();
    let seats = self.seat_markers();
    let bindings = self.bindings();
    let fuse = self.fuse();
    let wire = self.wire();
    quote! {
      #record
      #seats
      #bindings
      #fuse
      #wire
    }
  }

  /// **WHETHER THIS RECIPE PUBLISHES A QUERY FIELD AT ALL.**
  ///
  /// Two conditions, and neither counts past zero. A recipe has to have NAMED a backend — the
  /// presence law — and it has to broadcast into AT LEAST ONE seat, because the wire road's question
  /// is the seat a client fills and a recipe with none has nothing for that argument to be.
  ///
  /// SEVERAL seats used to fail here too, and the `@oneOf` member seats are what retired that arm:
  /// the published field's question becomes a choice — one input field per seat, exactly one filled —
  /// and the members whose arms bought that seat answer the request. A recipe with ONE seat publishes
  /// the bare argument it always did, which is the additive law read at the schema.
  #[must_use]
  pub fn mounts(&self) -> bool {
    self.graphql.is_some() && !self.seats.is_empty()
  }

  /// **WHETHER THE PUBLISHED QUESTION IS A CHOICE** — several declared seats, so the field asks with
  /// one `@oneOf` argument rather than with the seat itself.
  ///
  /// The fork every wire-side emitter reads, written once: a single-seat recipe's whole face is what
  /// it was before the choice existed, byte for byte, and this is the one predicate that says so.
  #[must_use]
  pub fn chooses(&self) -> bool {
    self.seats.len() > 1
  }

  /// Whether any member binds any tower at all.
  ///
  /// The question the question layer asks first: a recipe whose members are all plain coordinate
  /// members has no arm to publish and no tower to walk, and is the one-member text search the
  /// retiring `ask` family used to spell.
  #[must_use]
  pub fn bound(&self) -> bool {
    self.members.iter().any(|member| !member.arms.is_empty())
  }
}

/// ONE BROADCAST SEAT — the head's `shared(<name>(type = "…"))`.
///
/// The name and the type are the whole of it, and they answer two different parties: the NAME is
/// what an arm writes `shared` against, and the TYPE is what a caller of the whole recipe hands
/// over once.
#[derive(Debug, Clone)]
pub struct SeatModel {
  /// The seat's name, as the head wrote it — the word an arm's `shared` is resolved against.
  pub name: syn::Ident,
  /// What a caller hands this seat, as the word named it.
  ///
  /// A TYPE and never a kind: a seat is a question a caller asks, and this framework's questions
  /// are the application's own types.
  pub ty: syn::Type,
}

/// ONE MEMBER — the field, the index it reads, and the defaults the recipe declares for its route.
#[derive(Debug, Clone)]
pub struct MemberModel {
  /// The field that names this member — its ONE name, and the span every refusal about it is
  /// reported at.
  pub field: syn::Ident,
  /// The INDEX this member reads, as the field declared it.
  ///
  /// Carried as the type it was written as and never resolved: whether it is an index, what it is
  /// addressed by and whether its coordinates meet this member's arms are the emission's questions,
  /// asked where the compiler can answer them.
  pub ty: syn::Type,
  /// This member's coefficient in the recipe's fold — `weight = 2.0`, and this word's FIRST
  /// declaration-side home.
  ///
  /// [`None`] where the word was omitted, under which the member takes the request layer's own
  /// `Route::DEFAULT_WEIGHT` — the multiplicative identity, so a recipe where nobody weighted
  /// anything runs the unweighted fold exactly rather than an approximation of it.
  pub weight: Option<f64>,
  /// How deep this member's route is asked when nothing asks otherwise — `depth = 100`.
  ///
  /// [`None`] where the word was omitted, on [`SearchModel::limit`]'s road: it defers rather than
  /// defaults, and a declared ceiling CAPS whatever it says wherever it is spent.
  pub depth: Option<NonZeroU32>,
  /// The FLOOR this member's route is read at, as a const PATH — `floor = "crate::floors::SEM"`.
  ///
  /// A PATH and never a literal, which is §4's law rather than this grammar's taste: a floor is a
  /// value in the ENGINE's own currency, an open type this framework never sees, so there is
  /// nothing here that could parse one. A const is a value its own crate already built.
  ///
  /// [`None`] where the word was omitted, under which the read has no declared floor and whatever
  /// the request names is the only one.
  pub floor: Option<syn::Path>,
  /// The towers bound to this member, in declaration order — EMPTY for a plain coordinate member.
  ///
  /// Each is one ARM of this member's question, and its name is that arm's name.
  pub arms: Vec<ArmModel>,
}

/// ONE BOUND TOWER — `tower(text(type = "crate::ClipText", shared, floor = "…"))`.
///
/// The arm of a member's question that carries a tower's own question, and the row the emission
/// spends every projection off: what the tower is asked, what it answers, whether its walk is
/// awaited and what it seats are all read through [`ArmModel::tower`] rather than guessed from
/// [`ArmModel::name`].
#[derive(Debug, Clone)]
pub struct ArmModel {
  /// The arm's name, as the word named it — the variant this arm mints, and the seat name its
  /// `shared` is resolved against.
  pub name: syn::Ident,
  /// The TOWER this arm walks, as the `type = "…"` word wrote it.
  ///
  /// A TYPE PATH, and the whole reason the record family exists: the recipe's own expansion cannot
  /// see this tower's fields, so what it does with the path is project off it —
  /// `<Ty as SearchTower>::Question`, `<Ty as DeclaredTower>::StepOptions` — and the compiler resolves
  /// what neither declaration could.
  pub tower: syn::Type,
  /// Where this arm's question comes from when the caller broadcast one — the `shared` word.
  ///
  /// [`None`] where the arm wrote no `shared`, under which the arm is asked its own question and
  /// nothing else.
  pub shared: Option<SharedBinding>,
  /// The FLOOR this arm's read is taken at, as a const PATH — [`MemberModel::floor`]'s law at the
  /// arm's own grain.
  pub floor: Option<syn::Path>,
}

/// WHERE AN ARM'S QUESTION COMES FROM when the recipe was asked once — the resolved `shared` word.
///
/// Two halves, because the word decides two things: WHICH seat feeds this arm, and HOW the seat's
/// type becomes the tower's question.
#[derive(Debug, Clone)]
pub struct SharedBinding {
  /// The head seat this arm reads, resolved from the declaration's OWN tokens.
  ///
  /// By NAME where a seat of the arm's name exists, and the SOLE seat where a recipe declared
  /// exactly one — the resource axis's own sole-default law, one layer up. It is a resolution and
  /// not a derivation: both halves are written in this declaration, so nothing here reaches past
  /// the expansion wall, and a `shared` that matches no seat is refused rather than resolved.
  pub seat: syn::Ident,
  /// HOW the seat's type becomes this tower's question.
  pub bridge: SharedBridge,
}

/// THE BRIDGE a broadcast seat crosses to reach one arm's question — the word inside `shared`.
///
/// A CLOSED framework vocabulary, because what it names is which of two conversions the emission
/// demands and which of two shapes a hook has. The types on either side are the application's and
/// stay open; the crossing is the framework's.
///
/// The variants are NOT called `From` and `TryFrom`, and the reason is measured rather than stylistic
/// — see the runtime record's own `Bridge`, whose note carries the six goldens that moved on that
/// word. One vocabulary across the two crates, so the reason lands once and the names never diverge.
#[derive(Debug, Clone)]
pub enum SharedBridge {
  /// `shared` — the crossing that cannot fail, demanded as [`From`].
  Total,
  /// `shared(try)` — the crossing that can, demanded as [`TryFrom`], whose failure surfaces through
  /// the member's own refusal variant.
  Fallible,
  /// `shared(with = "path::to::hook")` — a function of the author's, taking the seat and answering
  /// this arm's question.
  ///
  /// HOOKS BEAT TRAITS: a crossing an application wrote is not obliged to be expressible as an impl
  /// it is allowed to write, the orphan rule being what it is.
  Hook(syn::Path),
  /// `shared(try_with = "path::to::hook")` — the fallible hook, [`Hook`](Self::Hook)'s twin.
  FallibleHook(syn::Path),
}

impl SharedBridge {
  /// The WORD this bridge was written as, for the refusals and the record that spell it.
  #[must_use]
  pub const fn word(&self) -> &'static str {
    match self {
      Self::Total => "shared",
      Self::Fallible => "try",
      Self::Hook(_) => "with",
      Self::FallibleHook(_) => "try_with",
    }
  }

  /// Whether this crossing can FAIL — the half the emission spends on the refusal variant.
  #[must_use]
  pub const fn fallible(&self) -> bool {
    matches!(self, Self::Fallible | Self::FallibleHook(_))
  }

  /// The author's own function where the word named one.
  #[must_use]
  pub const fn hook(&self) -> Option<&syn::Path> {
    match self {
      Self::Hook(path) | Self::FallibleHook(path) => Some(path),
      Self::Total | Self::Fallible => None,
    }
  }
}