ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The MUTATION NODE's model and its DECLARATION-SIDE emission: the command vocabulary a source is
//! controlled through, and the record a source's own expansion reads that declaration through.
//!
//! ```ignore
//! #[ingraph::mutation(graphql(async_graphql))]
//! pub struct WatchOps {
//!   #[ingraph(rename = "addWatch",
//!             handler(path = "crate::watch::add", async,
//!                     context(resource("crate::Catalog")),
//!                     error(type = "crate::AddWatchError", code = "ADD_FAILED")))]
//!   add: (AddWatch, AddResponse),
//!
//!   #[ingraph(handler = "crate::watch::reindex")]
//!   reindex: (Reindex, ()),
//! }
//! ```
//!
//! # FIELDS ARE EXCHANGES, which is why there is no list to write
//!
//! One field is one thing an app can say. The field's TYPE answers what that exchange IS — a
//! request, a response, a failure — through `Mutation`, and the words beside the field answer
//! everything a type cannot: who runs it, what the wire calls it, what it was handed, how it fails.
//! So the declaration has no second list of commands anywhere; a vocabulary that could disagree with
//! the fields would be a vocabulary two readings could differ about.
//!
//! # WHAT IS EMITTED HERE, and what waits
//!
//! Six items always, and each answers a reader the others cannot:
//!
//! | item | who reads it |
//! |---|---|
//! | `<Node>Command` | the source's own `run` body, matching on what an app said |
//! | `impl MutationNode for <Node>` | the `Control` line's type, through the source's `Mutation` seat |
//! | `impl DeclaredMutation for <Node>` | everybody who cannot see these tokens |
//! | `<Node>Response` / `<Node>Error` | whatever calls the assembled face |
//! | `<Node>::handle_<node>` | a first-party transport, a test, the source-side caller |
//!
//! And, where the declaration wore a `graphql(…)` word, the WIRE FACE over all of it — the unit a
//! root folds, and one resolver per exchange. [`wire`] is where that lives and where its own rules
//! are written; [`face`] is where the assembled one does. What is worth knowing here is that
//! everything above is emitted either way, so a node with no wire word still has its whole Rust
//! surface — and that the wire and the face SHARE one call per exchange, which is the one place a
//! handler's declared signature is cast.
//!
//! # The declaration record is a RECORD and not a channel
//!
//! `DeclaredMutation`'s table restates what these tokens already say, and that is deliberate:
//! `Declared`'s own note gives the reason one layer over, which is that two expansions cannot read
//! each other's tokens. A source declaring `mutation(node = "WatchOps")` expands in a pass that has
//! never seen `WatchOps`' fields, so what crosses is a trait impl and a projection off it — nobody
//! reads anybody's tokens and the compiler resolves the meeting.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::ext::IdentExt as _;

use crate::model::GraphqlKind;

mod face;
#[cfg(test)]
mod tests;
mod wire;

/// A validated mutation declaration, ready to emit.
///
/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
/// front end later reach the same emitter.
#[derive(Debug, Clone)]
pub struct MutationModel {
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  pub krate: syn::Path,
  /// The declared type — the node the command enum and both impls are emitted for.
  pub name: syn::Ident,
  /// The declaration's own visibility, which the minted command enum wears: a node a caller can
  /// name has commands that caller can build.
  pub vis: syn::Visibility,
  /// The wire backends the `graphql(…)` word named, in the order it named them.
  ///
  /// CARRIED and not yet spent — see the module note. It is a list rather than a flag for the index
  /// grammar's reason: a second backend is a second word inside one block, not a second block.
  pub graphql: Vec<GraphqlKind>,
  /// Every exchange, in declaration order — which is the order the command enum's arms take.
  pub exchanges: Vec<ExchangeModel>,
}

/// ONE field of a mutation node: the exchange, and the words written beside it.
#[derive(Debug, Clone)]
pub struct ExchangeModel {
  /// The field's own name.
  pub field: syn::Ident,
  /// Its type — an exchange, which the emission asserts by projecting `Mutation` off it.
  pub ty: syn::Type,
  /// The `rename = "…"` word, or nothing where the declaration wrote none.
  pub rename: Option<syn::LitStr>,
  /// The `handler(…)` block, which no field may omit.
  pub handler: HandlerModel,
}

/// The `handler(…)` block: the three segments of a signature.
///
/// `path` is WHO, `context` is the argument half, `error` is the failing half of the return. They
/// live in one block because they describe one function, and the `error(…)` word lives INSIDE it for
/// the same reason — an error with no handler to belong to is an error nothing renders.
#[derive(Debug, Clone)]
pub struct HandlerModel {
  /// What runs — the path the declaration wrote.
  pub path: syn::Path,
  /// Whether it wears the `async` word.
  pub awaited: bool,
  /// The resources its `context(resource("…"), …)` block granted, in declaration order.
  pub context: Vec<syn::Path>,
  /// Its `error(…)` word, or nothing — which is the exchange that cannot fail.
  pub error: Option<DeclaredError>,
}

/// The `error(…)` word's two legal shapes, each optionally headed by a code.
///
/// `type` and `message` are MUTUALLY EXCLUSIVE, so they are two arms rather than two options: a
/// declaration that wrote both is refused by the grammar, and a model that could hold both would be
/// a shape the refusal exists to make unreachable.
#[derive(Debug, Clone)]
pub enum DeclaredError {
  /// `error(type = "…")` — the failure is a type the application owns.
  Rich {
    /// The path to that type, as written.
    ty: syn::Path,
    /// The `code = "…"` word, where one was written.
    code: Option<syn::LitStr>,
  },
  /// `error(message = "…")` — the whole failure is the declaration's own sentence.
  Canned {
    /// The sentence.
    message: syn::LitStr,
    /// The `code = "…"` word, where one was written.
    code: Option<syn::LitStr>,
  },
}

impl MutationModel {
  /// The command enum's name — the node's own, with `Command` after it.
  ///
  /// Derived rather than declared, and there is no `command(rename = "…")` word: the node's name IS
  /// the vocabulary's name, and a second word for it would be a name two spellings could disagree
  /// about. A node that wants another name is renamed.
  #[must_use]
  pub fn command_name(&self) -> syn::Ident {
    format_ident!("{}Command", self.name)
  }

  /// Whether EVERY handler here is blocking — the OR law's own const, read the other way round.
  #[must_use]
  pub fn all_sync(&self) -> bool {
    !self
      .exchanges
      .iter()
      .any(|exchange| exchange.handler.awaited)
  }

  /// The whole expansion: the vocabulary, the row that hands it to a source, the record — and, where
  /// the declaration wore a `graphql(…)` word, the wire face over all of it.
  #[must_use]
  pub fn emit(&self) -> TokenStream {
    let command = self.command();
    let node = self.node();
    let declared = self.declared();
    let face = self.assembly();
    let wire = self.wire();
    quote! {
      #command
      #node
      #declared
      #face
      #wire
    }
  }

  /// THE VOCABULARY: one arm per field, carrying that exchange's request.
  ///
  /// The payload is written as the PROJECTION `<Ty as Mutation>::Request` rather than as the request
  /// type itself, which is what makes this emission also the assert: a field whose type is not an
  /// exchange is `E0277` at the field, naming the trait it does not implement, rather than a
  /// resolution failure somewhere inside a resolver nobody has written yet.
  fn command(&self) -> TokenStream {
    let krate = &self.krate;
    let vis = &self.vis;
    let name = self.command_name();
    let arms = self.exchanges.iter().map(|exchange| {
      let variant = exchange.variant();
      let ty = &exchange.ty;
      let doc = format!(
        "What an app says to run the `{field}` exchange.",
        field = exchange.named(),
      );
      quote! {
        #[doc = #doc]
        #variant(<#ty as #krate::__private::source::Mutation>::Request)
      }
    });
    let doc = format!(
      "The command vocabulary of [`{node}`] — one arm per exchange it declared.",
      node = self.name,
    );
    quote! {
      #[doc = #doc]
      #vis enum #name {
        #(#arms),*
      }
    }
  }

  /// THE ROW a source's `Mutation` seat resolves through.
  fn node(&self) -> TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let command = self.command_name();
    quote! {
      impl #krate::__private::source::MutationNode for #name {
        type Command = #command;
      }
    }
  }

  /// THE RECORD: what this declaration said, for the readers that cannot see these tokens.
  fn declared(&self) -> TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let all_sync = self.all_sync();
    let rows = self.exchanges.iter().map(|exchange| exchange.row(krate));
    quote! {
      impl #krate::__private::source::DeclaredMutation for #name {
        const ALL_SYNC: bool = #all_sync;
        const EXCHANGES: &'static [#krate::__private::source::Exchange] = &[
          #(#rows),*
        ];
      }
    }
  }
}

impl ExchangeModel {
  /// The command arm this exchange mints.
  ///
  /// `heck`'s upper camel case and not [`emit::raise_initial`](crate::emit) — the opposite of the
  /// choice a PUBLISHED word gets, and for the same law: a Rust field name is snake case by the
  /// language's own convention rather than by anybody's choice, so re-casing it is a translation and
  /// not a rewrite of somebody's word.
  #[must_use]
  pub fn variant(&self) -> syn::Ident {
    use heck::ToUpperCamelCase as _;

    format_ident!("{}", self.named().to_upper_camel_case())
  }

  /// The field's name as everything but Rust spells it — unraw'd, so a field legally called
  /// `r#type` is `type` in the record and `Type` in the vocabulary.
  #[must_use]
  pub fn named(&self) -> String {
    self.field.unraw().to_string()
  }

  /// This exchange's row in the declaration record — the builder chain, with a call for each word
  /// the declaration actually wrote and nothing for the words it did not.
  fn row(&self, krate: &syn::Path) -> TokenStream {
    let field = self.named();
    let handler = path_word(&self.handler.path);
    let mut row = quote!(#krate::__private::source::Exchange::of(#field, #handler));

    if let Some(rename) = &self.rename {
      row = quote!(#row.renamed(#rename));
    }
    if self.handler.awaited {
      row = quote!(#row.awaited());
    }
    if !self.handler.context.is_empty() {
      let granted = self.handler.context.iter().map(path_word);
      row = quote!(#row.granting(&[#(#granted),*]));
    }
    if let Some(error) = &self.handler.error {
      let fallibility = error.emit(krate);
      row = quote!(#row.failing(#fallibility));
    }
    row
  }
}

impl DeclaredError {
  /// This failure as the record's own three-tier fact.
  fn emit(&self, krate: &syn::Path) -> TokenStream {
    match self {
      Self::Rich { ty, code } => {
        let named = path_word(ty);
        let code = optional(code.as_ref());
        quote!(#krate::__private::source::Fallibility::Rich { named: #named, code: #code })
      }
      Self::Canned { message, code } => {
        let code = optional(code.as_ref());
        quote!(#krate::__private::source::Fallibility::Canned { message: #message, code: #code })
      }
    }
  }
}

/// A path as the record carries it: the words the declaration wrote, with the spacing `quote` adds
/// taken back out.
///
/// The record's strings are for the SENTENCE — see `Exchange`'s own note — so what matters is that
/// `crate::watch::add` reads back as it was written rather than as `crate :: watch :: add`.
fn path_word(path: &syn::Path) -> String {
  quote!(#path).to_string().replace(' ', "")
}

/// A word the declaration MAY have written, as the option it is.
fn optional(word: Option<&syn::LitStr>) -> TokenStream {
  match word {
    Some(word) => quote!(::core::option::Option::Some(#word)),
    None => quote!(::core::option::Option::None),
  }
}