ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The ROOT QUERY: `<Root>Query`, the fold of the query units its members emit.
//!
//! ```ignore
//! #[derive(MergedObject, Default)]
//! #[graphql(name = "Query")]
//! pub struct MediaQuery(
//!   <<media::Reel as Transformer>::Graphql as Graphql>::Query,
//!   <<media::Take as Transformer>::Graphql as Graphql>::Query,
//!   <media::Screened as Graphql>::Query,
//! );
//! ```
//!
//! # The join rides the TYPE SYSTEM, and that is the whole mechanism
//!
//! A root holds a field's type PATH and nothing else; what that type's own declaration emitted is
//! written in tokens this derive will never see. So the fold names no unit: it PROJECTS, twice —
//! through `Transformer`'s wire-face member and through that member's own trait — and the compiler
//! resolves the meeting. A member that declared no wire face is `E0277` AT THE PROJECTION, carrying
//! `Graphql`'s own sentence (*declares no wire face — there is no `graphql(…)` block*); a member with
//! a face and no root fields binds `()` there, which is not an object and says so at the fold.
//!
//! # A RETRIEVING MEMBER takes the INTERFACE's road, and that closes the root query-surface gap
//!
//! `#[ingraph(fuse)] shots: Shots` and `#[ingraph(search)] travel: TravelSearch` both name a
//! declaration that implements [`Graphql`] DIRECTLY — a retrieving declaration is not a launchable
//! node and implements no `Transformer`, which is the fourth-tier fact the `fuse` word already rests
//! on. So they join through the same one-hop projection an interface takes.
//!
//! Until this arm existed the fold read TWO lists and a retrieving member wrote the mount word to no
//! effect: an index minted `<Decl>Queries`, bound it at `Graphql::Query`, put it on its own roster —
//! and no emitted root could reach it. Every schema in this workspace mounted such a unit AS the
//! root instead, which is what hid the gap.
//!
//! # An INTERFACE is projected ONCE, and the missing hop is forced rather than chosen
//!
//! A node's unit is reached through `Transformer` first, because a node's wire face is a member of
//! its entity binding. An interface has no entity binding to hold one: `Transformer: Identifiable`,
//! and `Identifiable::id_ref` hands back a `&Self::Id` — an interface's id is a SUM over its members'
//! ids, and a member's VALUE holds no such sum to lend a reference to. So `Transformer` is
//! unimplementable for an interface, which is the B-27 ruling's *an interface-owned id is
//! unspellable* met where it bites.
//!
//! What is left is `Graphql` itself, which the interface's own expansion implements, and the seat is
//! the SAME seat — `Graphql::Query`, folded by the same `MergedObject`. So this is one projection
//! shorter and not a second mounting mechanism: the citizenship a node has is the citizenship an
//! interface has, and only the road to the seat differs.
//!
//! That is the same door `Declared` opened for the launch, one tier over: nobody parses anybody's
//! declaration, and the agreement between two derives is a compile error rather than a convention.
//!
//! # MEMBERSHIP comes from the DECLARATION, because a macro cannot see an impl
//!
//! Only the fields wearing `#[ingraph(query)]` are projected. The alternative — project every node —
//! refuses every graph holding an operator, an index or a journal, none of which has a wire face,
//! and there is no third road: a macro cannot ask whether a type implements anything.
//!
//! The ZERO-FIELD MEMBER question the fold would otherwise raise is therefore moot by construction,
//! and that is what the filter buys rather than a happy accident: a member with no fields would
//! contribute an empty `MetaType::Object` to the merge, and an object with no fields is not a
//! GraphQL type. Nothing can reach the fold without a unit, and a unit always has the single.
//!
//! A ROOT WITH NO MARKED FIELD EMITS NOTHING AT ALL. Presence is the same mechanism one level up: a
//! graph that serves no schema has no root query, rather than one holding nothing.
//!
//! # The SDL name is `Query`, where the Rust name is the root's
//!
//! One schema has one root, so the published name is GraphQL's own convention and carries no
//! deployment's word. The RUST name is per root — two graphs in one crate are two types — and it is
//! the one thing an application spells: `Schema::build(MediaQuery::default(), …)`.
//!
//! # No doc attribute, and that is the emitted faces' rule reaching the root
//!
//! `#[derive(MergedObject)]` calls `get_rustdoc` on the STRUCT, so a doc comment here would publish
//! generated prose as the root type's SDL description. The wire faces avoid the same thing by
//! carrying no doc; this carries none for the same reason, and an `allow` in its place so a
//! declaring crate under `missing_docs` is not warned about a type it did not write.

use quote::{format_ident, quote};

use super::GraphModel;

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

impl GraphModel {
  /// The interfaces whose ROOT FIELDS join this graph's query, in the order the fields were written.
  ///
  /// The node side's `queried` one tier over, read off
  /// [`InterfaceMount::queried`](super::InterfaceMount::queried) rather than kept as a second list:
  /// an interface joins exactly one walk, so the fact and the field it is about are one value.
  fn queried_interfaces(&self) -> impl Iterator<Item = &syn::Type> {
    self
      .interfaces
      .iter()
      .filter(|interface| interface.queried)
      .map(|interface| &interface.ty)
  }

  /// The RETRIEVING MEMBERS whose query units join this graph's query, in field order.
  ///
  /// [`queried_interfaces`](Self::queried_interfaces)' twin at the index tier, read off the same
  /// `#[ingraph(query)]` word and reaching the same seat by the same one-hop projection.
  fn queried_indexes(&self) -> impl Iterator<Item = &syn::Type> {
    self
      .fused
      .iter()
      .filter(|member| member.queried)
      .map(|member| &member.ty)
  }

  /// The root query, behind the binding gate — or nothing at all, for a root no member joined.
  pub(super) fn query(&self) -> proc_macro2::TokenStream {
    if self.queried.is_empty()
      && self.queried_interfaces().next().is_none()
      && self.queried_indexes().next().is_none()
    {
      return proc_macro2::TokenStream::new();
    }
    let krate = &self.krate;
    let vis = &self.vis;
    let name = format_ident!("{}Query", self.name);
    let gate = crate::emit::framework(krate, &["gate"], "if_async_graphql");
    let ag = crate::emit::framework(krate, &[], "async_graphql");
    let shelf = crate::emit::vendored(krate, "async_graphql");
    let transformer = crate::emit::framework(krate, &["transform"], "Transformer");
    let face = crate::emit::framework(krate, &["transform"], "Graphql");
    let registry_root = crate::emit::framework(krate, &["graphql"], "RegistryQueryRoot");
    // NODES first, then interfaces, then the retrieving members, then the root-key registry's own
    // member LAST — whatever order the fields were written in, plus the one member no field wrote.
    // The tuple's order is invisible to a client — `MergedObject` folds every member's fields onto
    // one level — and grouping by tier is what keeps the emission readable beside the lists it is
    // built from.
    //
    // `RegistryQueryRoot` names no node, no interface and no index: it is the framework's own
    // `registry(family:)` field, mounted on EVERY served root exactly as `SqlDoor` is installed on
    // every served schema — see `graphql::registry`'s own module note for why a runtime `family`
    // string needs no per-graph dispatch to reach it. It rides here rather than standing apart
    // because a root that serves no schema at all still serves none of THIS either — the same gate
    // above already decided that, and a registry field with nothing else to keep it company would be
    // one schema this derive publishes that nothing else in this file's `query()` posture allows.
    let members = self
      .queried
      .iter()
      .map(|node| quote!(<<#node as #transformer>::Graphql as #face>::Query,))
      .chain(
        self
          .queried_interfaces()
          .map(|interface| quote!(<#interface as #face>::Query,)),
      )
      .chain(
        self
          .queried_indexes()
          .map(|index| quote!(<#index as #face>::Query,)),
      )
      .chain(core::iter::once(quote!(#registry_root,)));
    let why = "the root query is emitted rather than written, and a doc comment on it would be \
               published as the schema's own description of the root type";
    quote! {
      #gate! {
        #[allow(missing_docs, reason = #why)]
        #[derive(#ag::MergedObject, ::core::default::Default)]
        #[graphql(crate = #shelf, name = "Query")]
        #vis struct #name(#(#members)*);
      }
    }
  }
}