ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The GRAPHQL ENUM FACE: what a declared vocabulary looks like to a client.
//!
//! One emission, carried by the ONE door — [`EnumModel::emit`](super::EnumModel::emit) — and
//! written from the same [`EnumModel`] the storage rows are. That sharing is structural rather than
//! a convention: the words a face spells a variant with come from [`EnumVariant::name`] under
//! [`Namespace::Graphql`], which is the same function `as_graphql_str` is written from, so the
//! accessor a declaration reads in Rust and the value a client writes in a document cannot come to
//! disagree.
//!
//! # It is emitted for EVERY declaration, and which schema sees it is REACHABILITY
//!
//! There was a second word whose whole job was to say *this vocabulary reaches a schema*, and it was
//! deleted: a schema is walked from its ROOTS, so an enum no wire type names never enters the SDL
//! however many impls it carries. A macro asked to gate that was gating nothing — and the
//! coexistence it bought cost a silent composition-order trap and two entry points onto one model.
//!
//! The whole face sits behind the BINDING GATE, so a build of `ingraph` without `async-graphql`
//! expands it to nothing at all.
//!
//! # What it emits
//!
//! | impl | what it is |
//! |---|---|
//! | `async_graphql::resolver_utils::EnumType` | the name ↔ variant table, in declaration order |
//! | `async_graphql::InputType` | the schema's `enum` type, and the parse a filter operand takes |
//! | `async_graphql::OutputType` | the same type in a RETURN position, and the value a resolver renders |
//! | `ingraph::ToGraphqlOutput` | the OUTPUT CROSSING's row — a vocabulary crosses as ITSELF |
//!
//! The last is the framework's own map rather than async-graphql's, and it is here for the reason
//! the storage rows are: writing it by hand beside every declaration would be a second place for a
//! vocabulary's citizenship to be incomplete. A wire face RETURNS through `ToGraphqlOutput`, so a
//! vocabulary without this row is one no output object can expose — which is the wall this door was
//! folded to remove.
//!
//! **A `Vec` of the vocabulary needs no row of its own**, and that is the output map's marker fork
//! paying here: `ToGraphqlOutput`'s collection rows are written over
//! `ListMarker`/`SetMarker`, so a `Vec<TheirEnum>`
//! reaches a schema through whatever the element's own `DefaultVecMarker` row already says a `Vec`
//! of it is READ as. A second emitted row stood here while the output side carried an
//! element-keyed trait of its own; that trait is gone, and so is the row.
//!
//! # The OUTPUT leg, and the wall that is left
//!
//! `OutputType::resolve` has TWO signatures — an `async fn` under async-graphql's `boxed-trait`
//! feature, an `impl Future` return without it (`async-graphql` 7.2.1, `src/base.rs`, the
//! `#[cfg_attr(feature = "boxed-trait", async_trait::async_trait)]` on the trait) — and a feature of
//! that crate is not one `ingraph` can `cfg` on. The road taken is the one that crate's OWN default
//! resolves: the impl writes `async fn resolve`, which satisfies the RPITIT method exactly.
//!
//! What is left is stated rather than worked around: **a build in which anything enables
//! `async-graphql/boxed-trait` fails to compile this impl**, because `#[async_trait]` rewrites the
//! trait method into a boxed-future one whose generic parameters an impl has to match. An `ingraph`
//! feature could mirror that flip but not close it — the flip may come from any crate in the graph,
//! and feature unification would not tell this expansion which shape it got. `graphql::direction`
//! escapes the same fact by using async-graphql's own derive, which runs inside the library and
//! reads the feature; a derive macro may only APPEND, so that answer is not available to a door that
//! mints impls beside somebody else's enum.
//!
//! # The FILTER's face is the framework's, not this emission's
//!
//! `EnumFilter<T>` is `ingraph`'s own type, so `impl InputType for EnumFilter<T>` is a LOCAL impl
//! there at every `T` — one generic row in `graphql::filter::r#enum` serves every declared enum at
//! once, and no declaration emits anything for it. The emission's whole job is the enum's own face,
//! which is the half only the declaring crate can write.
//!
//! # No prose reaches the schema
//!
//! `description: None` on the type and on every value, written into the registry entry as a FACT of
//! the emission. It is the same posture the hand-written filter faces take and the reason
//! `graphql::direction` hides its own rustdoc behind `cfg_attr(doc, …)`: async-graphql's derives call
//! `get_rustdoc` unconditionally with no key to decline it, so a derived face publishes whatever a
//! declaration happened to document. Nothing here is derived, so nothing here can.

use quote::quote;
use syn::ext::IdentExt as _;

use super::{EnumModel, Namespace};

#[cfg(test)]
mod tests;

impl EnumModel {
  /// The GraphQL faces this vocabulary earns, behind the binding gate.
  ///
  /// Called by [`emit`](EnumModel::emit) and reached no other way: ONE door mints the whole
  /// citizenship, and which schema a vocabulary reaches is REACHABILITY rather than a second word.
  pub(super) fn graphql_face(&self) -> proc_macro2::TokenStream {
    let gate = self.framework(&["gate"], "if_async_graphql");
    let table = self.enum_type();
    let input = self.input_type();
    let output = self.output_type();
    let crossing = self.output_crossing();
    let operand = self.input_crossing();
    quote! {
      const _: () = {
        #gate! {
          #table
          #input
          #output
          #crossing
          #operand
        }
      };
    }
  }

  /// This vocabulary's name as a SCHEMA writes it — the declaration's
  /// [`wire_name`](super::EnumModel::wire_name), else the Rust name unraw'd.
  ///
  /// The `r#` an unrenamed name drops is Rust's escape for a word that collides with ITS grammar and
  /// no part of the name, exactly as [`EnumVariant::canonical`](super::EnumVariant::canonical) reads
  /// it. A word the declaration wrote is carried verbatim and is held to GraphQL's Name grammar at
  /// the front end, at its own span.
  ///
  /// # The knob, and what took it from *deliberately absent* to *here*
  ///
  /// This function carried the sentence *there is no rename knob and the absence is deliberate*
  /// through four rounds, its argument being that a wire type name is a schema commitment and a Rust
  /// rename is not a schema change. **That argument survives, and it is an argument FOR a word of its
  /// own rather than against one** — which is what the rename-parity ruling settled: the two axes stay
  /// separate, and the schema commitment gets a way to be made. Three other names cited this one's
  /// sentence, and all four moved together.
  ///
  /// What the word does NOT do is anything outside the emission. The Rust type keeps its name, the
  /// refusal type keeps `error(rename = "…")`, the stored word keeps the per-variant per-face family,
  /// and a declaration that writes no `graphql(rename = "…")` emits what it emitted before the word
  /// existed, byte for byte.
  ///
  /// Read by the MIRROR face too, whose wire type is a scalar rather than an `enum`, and by the OPEN
  /// vocabulary's, which is a scalar for a different reason: the schema name is the vocabulary's
  /// whichever shape publishes it, so every face shares this one function rather than each spelling
  /// the rule. That sharing is also what bounds the knob to the wire — all four cells of the mode
  /// table reach a schema through here and nowhere else.
  pub(super) fn sdl_name(&self) -> String {
    self
      .wire_name
      .clone()
      .unwrap_or_else(|| self.name.unraw().to_string())
  }

  /// The name ↔ variant table async-graphql parses and renders through.
  ///
  /// In DECLARATION order, which is the order a schema lists the values in — the same order
  /// `VARIANTS` is written in, and for the same reason: a schema rendered from this reads as the enum
  /// does.
  ///
  /// The trait's own bound is what demands `Copy`, `Eq`, `Send` and `'static` of the declared enum —
  /// `EnumType: Sized + Eq + Send + Copy + 'static` — and nothing here restates it. A declaration
  /// missing one gets `E0277` naming the trait and the missing bound, at the enum; a token-level
  /// check for a `#[derive(Copy)]` would refuse a declaration whose `impl Copy` is hand-written,
  /// which is a correct program.
  fn enum_type(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.framework(&[], "async_graphql");
    let items = self.variants.iter().map(|variant| {
      let word = variant.name(Namespace::Graphql);
      let ident = &variant.ident;
      quote! {
        #ag::resolver_utils::EnumItem {
          name: #word,
          value: #name::#ident,
        }
      }
    });
    quote! {
      #[automatically_derived]
      impl #ag::resolver_utils::EnumType for #name {
        fn items() -> &'static [#ag::resolver_utils::EnumItem<#name>] {
          &[#(#items),*]
        }
      }
    }
  }

  /// The schema's `enum` type, and the parse an operand of it takes.
  ///
  /// `parse` and `to_value` are async-graphql's own `resolver_utils` functions over the table above,
  /// which is what the library's `Enum` derive calls too — so a document naming a value this
  /// vocabulary does not have is refused with that library's sentence rather than with a second one
  /// written here.
  ///
  /// It registers through `create_input_type` under `MetaTypeId::Enum`, which is what publishes the
  /// type: a filter field typed `Option<Codec>` reaches this, and the enum lands in the SDL beside
  /// the input object that named it.
  fn input_type(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.framework(&[], "async_graphql");
    let sdl = self.sdl_name();
    let values = self.variants.iter().map(|variant| {
      let word = variant.name(Namespace::Graphql);
      quote! {
        __ingraph_values.insert(
          ::std::string::String::from(#word),
          #ag::registry::MetaEnumValue {
            name: ::std::string::String::from(#word),
            description: ::core::option::Option::None,
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });
    quote! {
      #[automatically_derived]
      impl #ag::InputType for #name {
        type RawValueType = Self;

        #[inline]
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          __ingraph_registry.create_input_type::<Self, _>(
            #ag::registry::MetaTypeId::Enum,
            |_| #ag::registry::MetaType::Enum {
              name: ::std::string::String::from(#sdl),
              description: ::core::option::Option::None,
              enum_values: {
                let mut __ingraph_values = #ag::indexmap::IndexMap::new();
                #(#values)*
                __ingraph_values
              },
              visible: ::core::option::Option::None,
              inaccessible: false,
              tags: ::std::vec::Vec::new(),
              rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
              directive_invocations: ::std::vec::Vec::new(),
              requires_scopes: ::std::vec::Vec::new(),
            },
          )
        }

        fn parse(
          value: ::core::option::Option<#ag::Value>,
        ) -> #ag::InputValueResult<Self> {
          #ag::resolver_utils::parse_enum(::core::option::Option::unwrap_or_default(value))
        }

        fn to_value(&self) -> #ag::Value {
          #ag::resolver_utils::enum_value(*self)
        }

        #[inline]
        fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
          ::core::option::Option::Some(self)
        }
      }
    }
  }

  /// The OUTPUT leg — what a resolver returning this vocabulary needs.
  ///
  /// # Hand-written, and the `async fn` body is the road that was measured
  ///
  /// `OutputType::resolve` has TWO signatures. Without async-graphql's `boxed-trait` feature the
  /// trait declares `fn resolve(…) -> impl Future<Output = ServerResult<Value>> + Send`, and an
  /// `async fn` in an impl satisfies an RPITIT method exactly. WITH that feature the trait is
  /// rewritten by `#[async_trait]` into a boxed-future method whose generic parameters an impl has
  /// to match, and a hand-written `async fn` no longer applies to it.
  ///
  /// A feature of that crate is not one `ingraph` or an expansion can `cfg` on, so this emission
  /// picks the road async-graphql's own default resolves and states the residual wall rather than
  /// working around it: a build in which anything turns on `async-graphql/boxed-trait` fails to
  /// compile this impl. That is REPORTED rather than hidden, and the wall is one an `ingraph`
  /// feature could only mirror rather than close, since the flip may come from any crate in the
  /// graph.
  ///
  /// The two head methods DELEGATE to the input face rather than restating it. A GraphQL enum is one
  /// type in one registry whichever position names it, so a second `create_type_info` here would be
  /// a second entry able to disagree with the first about the values it publishes.
  ///
  /// `resolve` is the same body async-graphql's own `Enum` derive writes — `enum_value` over the
  /// `EnumType` table above — so a value rendered out of a resolver and a value parsed into a filter
  /// are one word from one table.
  fn output_type(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.framework(&[], "async_graphql");
    quote! {
      #[automatically_derived]
      impl #ag::OutputType for #name {
        #[inline]
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          <Self as #ag::InputType>::type_name()
        }

        #[inline]
        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          <Self as #ag::InputType>::create_type_info(__ingraph_registry)
        }

        async fn resolve(
          &self,
          _: &#ag::ContextSelectionSet<'_>,
          _: &#ag::Positioned<#ag::parser::types::Field>,
        ) -> #ag::ServerResult<#ag::Value> {
          ::core::result::Result::Ok(#ag::resolver_utils::enum_value(*self))
        }
      }
    }
  }

  /// The OUTPUT CROSSING's row — what a wire face RETURNS a value of this vocabulary as.
  ///
  /// A vocabulary crosses as ITSELF: the row above gives it an `OutputType`, so a reference to it is
  /// already the form a resolver renders, and the identity row is what says so to the map. No
  /// carrier, and nothing to convert.
  ///
  /// # Why the emission owes it, when the declaring crate could write it
  ///
  /// It is mechanical from the enum's own name, and a declaration is not required to think about
  /// the framework's maps at all — so the door that mints the whole citizenship mints this too, the
  /// same argument that put the storage rows and the cursor codec here.
  ///
  /// **ONE row where there were two.** The second was a `Vec` row on an element-keyed output trait,
  /// and that trait no longer exists: the output map reads the collection fork off the ELEMENT's
  /// `DefaultVecMarker` — the input side's own row, which a vocabulary's filter citizenship already
  /// supplies — so a `Vec<TheirEnum>` column crosses through `ToGraphqlOutput`'s generic collection
  /// rows with nothing emitted here for it.
  fn output_crossing(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let scalar = self.framework(&["graphql"], "ToGraphqlOutput");
    quote! {
      #[automatically_derived]
      impl #scalar for #name {
        type Output<'__ingraph> = &'__ingraph Self;

        #[inline]
        fn to_graphql_output(__ingraph_value: &Self) -> &Self {
          __ingraph_value
        }
      }
    }
  }

  /// The INPUT CROSSING's row — what ONE OPERAND of this vocabulary looks like on the wire.
  ///
  /// The output row's twin, one position over, and it crosses the same way: a vocabulary has an
  /// `InputType` of its own from the row above, so the wire form IS the type and the crossing is the
  /// identity.
  ///
  /// # What owes it, and why the emission does
  ///
  /// A COLLECTION of this vocabulary. `ListFilter<T, VF>` holds `Box<[T]>` in six slots and a bare
  /// `T` in `hasElement`, and what goes on the wire for each is the ELEMENT'S CROSSING — the bound
  /// being this crate's own trait rather than `InputType`, so that an operand whose Rust type has no
  /// wire face (`u128`) or the wrong one (`Vec<u8>` as `[Int!]`) crosses through a carrier. A
  /// declared vocabulary needs no carrier and still owes the row, because the bound asks every
  /// element alike.
  ///
  /// Mechanical from the enum's own name, and a declaration is not required to think about the
  /// framework's maps at all — the same argument that put the output row here.
  fn input_crossing(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let operand = self.framework(&["graphql"], "ToGraphqlInput");
    quote! {
      #[automatically_derived]
      impl #operand for #name {
        type Input = Self;
        type Error = ::core::convert::Infallible;

        #[inline]
        fn cross(__ingraph_value: Self) -> ::core::result::Result<Self, ::core::convert::Infallible> {
          ::core::result::Result::Ok(__ingraph_value)
        }

        #[inline]
        fn carry(__ingraph_value: &Self) -> Self {
          *__ingraph_value
        }
      }
    }
  }
}