ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! THE LEAF ERROR's midwife: an application's own failure type, dressed to render.
//!
//! ```ignore
//! #[ingraph::mutation_error]
//! pub enum WatchError {
//!   #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
//!   NotADirectory(PathBuf),
//! }
//! ```
//!
//! emits `Display`, [`core::error::Error`] and one reading — `code()` — and NOTHING ELSE. The enum
//! stays the author's: its arms, its payloads, its derives and its visibility are echoed untouched.
//!
//! # IT IS A CONVENIENCE AND NOT A SEAM, which is the ruling and not a hedge
//!
//! A hand-written error is exactly as legal here as a generated one. Nothing in this framework asks
//! a failure type for anything but a `Display` — `error(type = "…")`'s own rendering, and the
//! assembled face's error sum, both spend that and no more — so a type that implements `Display` by
//! hand, or through somebody else's derive, is a first-class declared failure. What this macro buys
//! is the CODE DISCIPLINE below, which a hand-written error simply does not get checked for.
//!
//! # ONE CODE PER VARIANT, and the code IS the head of the sentence
//!
//! Every variant writes a `code`, and the rendering is `CODE: message`. That is the one-code-head
//! law, and it is why the code is mandatory rather than optional: a leaf error's whole job at the
//! wire is to be recognised, and a variant with no word is a refusal a client cannot tell from its
//! neighbour.
//!
//! It is also why a declaration that heads such an error a SECOND time is a mistake. A declared
//! `error(type = "…", code = "…")` puts its own heading in front of whatever the value renders as,
//! so an error minted here — which already carries one — is declared WITHOUT the `code` word. Two
//! headings on one message is two vocabularies with nothing telling a reader which is which.
//!
//! # THE CODE SPACE IS OPEN, and the framework's own words are RESERVED
//!
//! An application mints whatever `SCREAMING_SNAKE_CASE` words it likes: this framework cannot
//! enumerate everybody's failures and does not try. What it does hold is its OWN vocabulary — the
//! [`ErrorCode`](../../ingraph/enum.ErrorCode.html) table, one word per typed refusal that can reach
//! the wire — and a declaration that mints one of those words is refused. A client matching on
//! `UNREACHABLE_SOURCE` would otherwise be told *the change was made and not applied* by an
//! application error that meant something else entirely.
//!
//! [`RESERVED`] is that table's words, carried here because a proc macro cannot depend on the crate
//! it generates code for. The two lists are pinned EQUAL by `ingraph`'s own `graphql::code` fixture
//! — the file a round that adds a word already has to touch, which is what makes the pin catch that
//! round rather than merely catch a rename.
//!
//! # WHAT THE DECLARATION OWES
//!
//! A `Debug`, because [`core::error::Error`] has it as a supertrait — and nothing here emits one,
//! because a `Debug` this emission wrote would collide with the derive most error types already
//! carry. A [`Display`](core::fmt::Display) on every field a template RENDERS; nothing at all on a
//! field it never names, which is bound as `_`.
//!
//! # THE TEMPLATE is a format string over the variant's own fields
//!
//! `{0}` and `{}` name a tuple variant's fields by position; `{name}` names a struct variant's by
//! name. What is emitted is ONE `write_str`-or-`write!` per arm with the head folded in at
//! expansion time, and every argument passed EXPLICITLY by name — implicit capture is the
//! declaring crate's edition to have, and an expansion does not get to assume one.

use proc_macro2::TokenStream;
use quote::{ToTokens as _, quote};

#[cfg(test)]
mod tests;

/// The FRAMEWORK's own wire vocabulary, as words.
///
/// A mirror of [`ErrorCode`](../../ingraph/enum.ErrorCode.html)'s renderings, and it has to be one: a
/// proc macro runs before — and without — the crate whose table this is, so the list cannot be read
/// off the type. The two are pinned equal by `ingraph`'s own vocabulary fixture, which is where a
/// new word is already obliged to be written down.
///
/// Sorted, because the refusal a collision earns names its neighbours and a list a reader can scan
/// is a list a reviewer can check against the table.
pub const RESERVED: &[&str] = &[
  "AMBIGUOUS_PAGE_DIRECTION",
  "OVERSIZED_SKIP",
  "REPEATED_ORDER_SUBJECT",
  "REQUEST_DROPPED",
  "REQUEST_TIMED_OUT",
  "STORE_REFUSED",
  "UNPAGEABLE_ORDER",
  "UNREACHABLE_NODE",
  "UNREACHABLE_SOURCE",
  "UNREADABLE_ROW",
  "UNRENDERABLE_ORDER",
  "UNSUPPORTED_FILTER",
  "UNUSABLE_ADDRESS",
  "UNUSABLE_CURSOR",
  "UNWRITTEN_ARTIFACT",
];

/// WHICH ROAD an error was minted for — the word an author wrote, carried for the sentence.
///
/// The two macros emit the SAME items, and that is deliberate rather than an accident waiting to be
/// deduplicated: what differs is which half of the line a failure belongs to, and a word that says
/// so is what lets a reader of a declaration know whether they are looking at a write path's failure
/// or a read path's. The day the two roads want different faces — a `ToErrorCode` row on one of them
/// — the word is already written and no declaration has to change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorRoad {
  /// `#[ingraph::mutation_error]` — a declared exchange's failure.
  Mutation,
  /// `#[ingraph::query_error]` — a read-path author error.
  Query,
}

impl ErrorRoad {
  /// The attribute an author wrote, as they wrote it.
  #[must_use]
  pub const fn word(self) -> &'static str {
    match self {
      Self::Mutation => "mutation_error",
      Self::Query => "query_error",
    }
  }

  /// What such an error IS, for the sentence a refusal makes.
  #[must_use]
  pub const fn subject(self) -> &'static str {
    match self {
      Self::Mutation => "a declared exchange's failure",
      Self::Query => "a read path's failure",
    }
  }
}

/// A validated leaf-error 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 ErrorModel {
  /// The declared type — the enum both impls are emitted for.
  pub name: syn::Ident,
  /// Which macro minted it.
  pub road: ErrorRoad,
  /// Every variant, in declaration order.
  pub variants: Vec<VariantModel>,
}

/// ONE variant of a leaf error: what it is called, what it is recognised by, and what it says.
#[derive(Debug, Clone)]
pub struct VariantModel {
  /// The variant's own name.
  pub name: syn::Ident,
  /// Its `code = "…"` word — mandatory, and validated `SCREAMING_SNAKE_CASE`.
  pub code: syn::LitStr,
  /// Its `error = "…"` template, ALREADY REWRITTEN so that every placeholder names a binding this
  /// emission introduces, beside the bindings it has to introduce for them.
  pub rendering: Rendering,
  /// How the variant's own fields are bound in a pattern.
  pub shape: VariantShape,
}

/// A variant's fields, as a pattern has to spell them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VariantShape {
  /// `Variant` — nothing to bind.
  Unit,
  /// `Variant(a, b)` — bound by position.
  Tuple,
  /// `Variant { a, b }` — bound by name.
  Named,
}

/// A variant's message, as the emission spends it.
#[derive(Debug, Clone)]
pub struct Rendering {
  /// The template with every placeholder rewritten to name a binding, and the code folded in at the
  /// front — so the whole rendering is ONE literal and nothing at runtime assembles it.
  pub template: String,
  /// The fields the template referred to: the binding each is introduced under, and how the pattern
  /// reaches it.
  pub bound: Vec<Binding>,
}

/// ONE field a template referred to.
#[derive(Debug, Clone)]
pub struct Binding {
  /// The name the template now spells and the pattern introduces.
  pub held: syn::Ident,
  /// WHERE in the variant it is — a position for a tuple variant, a field name for a named one.
  pub at: BindingAt,
}

/// Where a bound field sits in its variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingAt {
  /// A tuple variant's field, by position.
  Position(usize),
  /// A named variant's field, by name.
  Named(syn::Ident),
}

impl ErrorModel {
  /// The whole expansion: what it prints, that it IS an error, and the word it is recognised by.
  #[must_use]
  pub fn emit(&self) -> TokenStream {
    let name = &self.name;
    let display = self.display();
    let coded = self.coded();
    let doc = crate::emit::leading(&format!(
      "The word this failure is recognised by — the head of everything it renders as.\n\nOne per \
       variant and never absent, which is what `#[ingraph::{word}]` checks: {subject} whose \
       variants shared a word would tell a client one thing about two mistakes.",
      word = self.road.word(),
      subject = self.road.subject(),
    ));
    quote! {
      impl ::core::fmt::Display for #name {
        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          #display
        }
      }

      impl ::core::error::Error for #name {}

      impl #name {
        #[doc = #doc]
        #[must_use]
        pub const fn code(&self) -> &'static str {
          #coded
        }
      }
    }
  }

  /// `Display`: one arm per variant, each rendering `CODE: message` from ONE literal.
  fn display(&self) -> TokenStream {
    if self.variants.is_empty() {
      // An UNINHABITED error is matched through the place: there is no value, so there is no arm.
      return quote!(match *self {});
    }
    let arms = self.variants.iter().map(|variant| {
      let pattern = variant.pattern();
      let template = &variant.rendering.template;
      if variant.rendering.bound.is_empty() {
        return quote!(#pattern => ::core::fmt::Formatter::write_str(__ingraph_f, #template));
      }
      // EXPLICIT named arguments, never implicit capture: the `write!` lands in the DECLARING
      // crate, whose edition this expansion does not get to assume.
      let arguments = variant.rendering.bound.iter().map(|binding| {
        let held = &binding.held;
        quote!(#held = #held)
      });
      quote!(#pattern => ::core::write!(__ingraph_f, #template, #(#arguments),*))
    });
    quote!(match self { #(#arms,)* })
  }

  /// `code()`: one arm per variant, answering the word its declaration wrote.
  fn coded(&self) -> TokenStream {
    if self.variants.is_empty() {
      return quote!(match *self {});
    }
    let arms = self.variants.iter().map(|variant| {
      let pattern = variant.blind();
      let code = &variant.code;
      quote!(#pattern => #code)
    });
    quote!(match self { #(#arms,)* })
  }
}

impl VariantModel {
  /// The pattern this variant's arm matches under, binding exactly the fields its template names.
  fn pattern(&self) -> TokenStream {
    let name = &self.name;
    match self.shape {
      VariantShape::Unit => quote!(Self::#name),
      VariantShape::Named => {
        let held = self.rendering.bound.iter().map(|binding| {
          let BindingAt::Named(at) = &binding.at else {
            return TokenStream::new();
          };
          let held = &binding.held;
          quote!(#at: #held,)
        });
        quote!(Self::#name { #(#held)* .. })
      }
      VariantShape::Tuple => {
        // Position by position, so a field the template never named is `_` rather than a binding
        // nothing reads — and the ORDER is what makes each `_` stand for the right field.
        let width = self
          .rendering
          .bound
          .iter()
          .filter_map(|binding| match &binding.at {
            BindingAt::Position(at) => Some(at + 1),
            BindingAt::Named(_) => None,
          })
          .max()
          .unwrap_or(0);
        let held = (0..width).map(|at| {
          self
            .rendering
            .bound
            .iter()
            .find(|binding| binding.at == BindingAt::Position(at))
            .map_or_else(|| quote!(_), |binding| binding.held.to_token_stream())
        });
        quote!(Self::#name(#(#held,)* ..))
      }
    }
  }

  /// The same variant, matched WITHOUT binding anything — what an arm that answers a constant needs.
  fn blind(&self) -> TokenStream {
    let name = &self.name;
    match self.shape {
      VariantShape::Unit => quote!(Self::#name),
      VariantShape::Tuple => quote!(Self::#name(..)),
      VariantShape::Named => quote!(Self::#name { .. }),
    }
  }
}