ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The CONTRACT: two traits, the per-member impls of the first, and the ties that hold a member to
//! the promise before either is reached.
//!
//! # `<I>Fields` is the DOMAIN contract, and it is STORED-ONLY
//!
//! One method per stored field, on every member and on the interface itself. What it hands back is
//! a projection of the member's own column — so a member's impl is FIELD ACCESS and nothing more,
//! which is where the teeth are: a member missing the column is `E0609` naming it, and a member
//! holding a different type is `E0308` at the same span.
//!
//! A COMPUTED field is not here. It is a query-layer construct — derived in order to be answered,
//! and what answers a query is the wire output — so putting one on the domain trait would make
//! every member's domain type owe a method its rows have no column for and its pipeline never asks
//! for. That is the ruling rather than a staging.
//!
//! # `<I>Derivations` is DECLARED and implemented nowhere
//!
//! The computed subset, at the same names, returning OWNED values because a derivation produces
//! rather than holds. Its implementors are the members' wire OUTPUT types — reached as
//! `<<M as Transformer>::Graphql as Graphql>::Output`, never as a name this crate builds — and the
//! impls are HAND-WRITTEN: an author writing a derivation writes their own glue, so there is no
//! adapter under this trait and no escape machinery beside it. What consumes it is the interface's
//! own output face, which is the find half's.
//!
//! # The TIES come first, and the order is the diagnostic
//!
//! Three per member, before any impl of the contract: the membership its declaration agreed to, the
//! v1 fence saying a member is a stored record, and the wire-face tie the derivations layer stands
//! on. rustc reports in emission order, so a type that is not a member at all is told THAT rather
//! than being told about a field it does not have.
//!
//! # Everything but the two traits is inside the anonymous const
//!
//! The traits are named in signatures a member writes, so they land in the declaring scope and take
//! part in the collision rule. The impls and the ties name nothing anybody has to spell, so they sit
//! where they collide with nothing — the placement [`crate::emit::relate`] already uses for the
//! relation half.

use quote::quote;

use crate::{
  interface::{InterfaceField, InterfaceModel},
  union::UnionMember,
};

impl InterfaceModel {
  /// The two traits, the ties, and the impls that make a member answer.
  pub(crate) fn contract(&self) -> proc_macro2::TokenStream {
    let fields = self.fields_trait();
    let derivations = self.derivations_trait();
    let ties = self.members.iter().map(|member| self.ties(member));
    let members = self.members.iter().map(|member| self.member_impl(member));
    let delegation = self.delegating_impl();
    quote! {
      #fields
      #derivations

      const _: () = {
        #(#ties)*
        #(#members)*
        #delegation
      };
    }
  }

  /// `pub trait <I>Fields` — the stored tier, as the projections a member hands back.
  fn fields_trait(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = self.fields_name();
    let interface = &self.name;
    let doc = format!(
      "What every member of [`{interface}`] carries.\n\nOne method per STORED field of the \
       declaration's contract. A member's own implementation is field access, so a member missing a \
       column is refused at the column and a member holding another type is refused at its \
       type.\n\nComputed fields are NOT here: a derived value is answered from the wire output \
       rather than from a row, and [`{derivations}`] is the face that carries them.",
      derivations = self.derivations_name()
    );
    let methods = self.stored().map(|field| {
      let signature = self.signature(field);
      let doc = format!("The `{}` field of this [`{interface}`].", field.name);
      quote! {
        #[doc = #doc]
        #signature;
      }
    });
    quote! {
      #[doc = #doc]
      #vis trait #name {
        #(#methods)*
      }
    }
  }

  /// `pub trait <I>Derivations` — the computed tier, declared for a hand to implement.
  fn derivations_trait(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = self.derivations_name();
    let interface = &self.name;
    let doc = format!(
      "What every member of [`{interface}`] DERIVES.\n\nOne method per computed field of the \
       declaration's contract, returning an owned value because a derivation produces rather than \
       holds.\n\nImplemented BY HAND, on the members' wire OUTPUT types — a derived value is \
       answered from the output rather than from a row, so the type that owes these methods is \
       `<<M as Transformer>::Graphql as Graphql>::Output` for each member `M`. Nothing generates \
       one: an author writing a derivation writes their own glue, so there is no adapter under this \
       trait."
    );
    let methods = self.computed().map(|field| {
      let signature = self.signature(field);
      let doc = format!(
        "The `{}` value this [`{interface}`] member derives.",
        field.name
      );
      // A `# Errors` section only where the declaration said the derivation can refuse — the
      // `missing_errors_doc` lint asks for one exactly there, and a section over an infallible
      // method would be a sentence about a `Result` the signature does not have.
      let errors = field.tier.fallible().then(|| {
        let refusal = format!(
          "# Errors\n[`{error}`] — whatever the implementor refuses with, which the declaration \
           named at `graphql(computed(error = \"…\"))`.",
          error = tight(&self.computed_error())
        );
        quote!(#[doc = ""] #[doc = #refusal])
      });
      quote! {
        #[doc = #doc]
        #errors
        #signature;
      }
    });
    quote! {
      #[doc = #doc]
      #vis trait #name {
        #(#methods)*
      }
    }
  }

  /// One field's SIGNATURE, in whichever tier it is.
  ///
  /// The house getter law, applied to what the declaration said: a `copy` field is handed back by
  /// value, a `String` as a `str` borrow, and anything else as a borrow of its own type. A COMPUTED
  /// field is handed back OWNED whatever it says, because there is nothing to borrow it out of.
  fn signature(&self, field: &InterfaceField) -> proc_macro2::TokenStream {
    let name = &field.name;
    let ty = &field.ty;
    if field.tier.fallible() {
      let error = self.computed_error();
      return quote!(fn #name(&self) -> ::core::result::Result<#ty, #error>);
    }
    if field.tier.computed() {
      return quote!(fn #name(&self) -> #ty);
    }
    if field.copy {
      return quote!(fn #name(&self) -> #ty);
    }
    if is_string(ty) {
      return quote!(fn #name(&self) -> &::core::primitive::str);
    }
    quote!(fn #name(&self) -> &#ty)
  }

  /// The three TIES one member is held to, before anything reads its columns.
  fn ties(&self, member: &UnionMember) -> proc_macro2::TokenStream {
    let interface = &self.name;
    let ty = &member.ty;
    let implements = self.framework(&["transform"], "implements");
    let stores_rows = self.framework(&["transform"], "stores_rows");
    let wire = self.framework(&["transform"], "has_a_wire_face");
    quote! {
      const _: fn() = #implements::<#ty, #interface>;
      const _: fn() = #stores_rows::<#ty>;
      const _: fn() = #wire::<#ty>;
    }
  }

  /// ONE member's implementation of the contract: field access, once per stored field.
  ///
  /// # Where the two teeth land, and why the span is the FIELD's
  ///
  /// A member that does not carry the column is `E0615` — *attempted to take value of method*,
  /// rather than `E0609`, because the contract's own method of that name is in scope on the member
  /// by the time rustc looks. The sentence still names the member and the column, which is what a
  /// reader needs; the `E0609` reading is unreachable while the trait and its impl are one
  /// expansion.
  ///
  /// A member that carries it at ANOTHER type is `E0308`. Both are respanned at the field the
  /// INTERFACE declared, because that is the token a reader can edit — the derive's own span points
  /// at `#[ingraph::interface(…)]`, which names no field at all.
  ///
  /// The name the access spells is the MEMBER's, where a member block moved it; the method's name
  /// is the interface's either way, so a caller writes one name whatever member it is holding.
  fn member_impl(&self, member: &UnionMember) -> proc_macro2::TokenStream {
    let name = self.fields_name();
    let ty = &member.ty;
    let methods = self.stored().map(|field| {
      let at = field.name.span();
      let signature = self.signature(field);
      // The METHOD keeps the interface's name and the ACCESS takes the member's, which is the whole
      // of what a member block moves: a caller writing the contract writes one name whatever member
      // it is holding.
      let column = field.column(&member.ident);
      let body = if field.copy {
        quote::quote_spanned!(at=> self.#column)
      } else {
        quote::quote_spanned!(at=> &self.#column)
      };
      quote::quote_spanned! {at=>
        #[inline]
        #signature {
          #body
        }
      }
    });
    quote! {
      #[automatically_derived]
      impl #name for #ty {
        #(#methods)*
      }
    }
  }

  /// The interface's OWN implementation: one match per method, delegating to whichever member is
  /// held.
  ///
  /// Qualified through the trait rather than called as an inherent method, because a member may
  /// carry a method of the same name for its own reasons and the delegation must reach the
  /// contract's.
  fn delegating_impl(&self) -> proc_macro2::TokenStream {
    let name = self.fields_name();
    let interface = &self.name;
    let methods = self.stored().map(|field| {
      let signature = self.signature(field);
      let column = &field.name;
      let arms = self.members.iter().map(|member| {
        let variant = &member.ident;
        let ty = &member.ty;
        quote!(Self::#variant(member) => <#ty as #name>::#column(member),)
      });
      quote! {
        #[inline]
        #signature {
          match self { #(#arms)* }
        }
      }
    });
    quote! {
      #[automatically_derived]
      impl #name for #interface {
        #(#methods)*
      }
    }
  }
}

/// Whether a declared type is spelled `String`.
///
/// SYNTACTIC, and the failure is benign in the one direction it can fail: an alias hiding a
/// `String` takes the plain borrow, which is a working getter over a working type. Nothing here can
/// resolve an alias, and a rule whose wrong answer is still correct code is one a macro may take.
fn is_string(ty: &syn::Type) -> bool {
  let syn::Type::Path(path) = ty else {
    return false;
  };
  path.qself.is_none()
    && path.path.segments.len() == 1
    && path
      .path
      .segments
      .last()
      .is_some_and(|segment| segment.ident == "String" && segment.arguments.is_none())
}

/// Tokens with their spacing removed, so a sentence about a type reads as it was written.
pub(super) fn tight(tokens: &proc_macro2::TokenStream) -> String {
  tokens.to_string().replace(' ', "")
}