ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The RELATION half of an expansion: the forward id equations, the pairing they prove, and the
//! reverse audits that read that pairing back.
//!
//! # Two derives that cannot see each other, and one piece of evidence between them
//!
//! A MEMBERSHIP is the same shape one direction shorter, which is why it lives here rather than
//! beside a family of its own: an interface's declaration names its members and cannot prove one
//! agreed, so the record's `implements(…)` emits `impl Implements<Interface>` and the interface's
//! own expansion asserts the bound. A relation needs the referring FIELDS crossing that boundary; a
//! membership needs only the fact, so the evidence carries nothing.
//!
//! A relation is declared at BOTH ends and expanded at neither: the forward half is
//! `#[ingraph(ref = "…")]` on the source's field, the reverse half is `derived(…)` on the target's
//! container, and the two expansions run over two declarations with no way to read one another. So
//! the forward side emits EVIDENCE — `impl Related<Target> for Source`, carrying the referring
//! fields as a type-level list and their names as a const — and the reverse side emits AUDITS that
//! consume it. Everything the compiler then refuses is refused at the declaration that got it
//! wrong, which is what neither derive could do on its own.
//!
//! # What is emitted, and what each piece refuses
//!
//! | emitted | at | refuses |
//! |---|---|---|
//! | `impl Implements<Interface>` | the record, per `implements(…)` entry | nothing; it is the evidence |
//! | `refers_to::<Value, Target>` | the source, per `ref` field | a field that does not carry the target's id (`E0271`) |
//! | `impl Related<Target> for Source` | the source, per TARGET | nothing; it is the evidence |
//! | `one_field_points_back::<Source, Me>` | the target, per shorthand entry | a source that points here through none, or through several (`E0277`) |
//! | `refers_through(…COLUMNS, "…")` | the target, per full entry | a `field = "…"` the source does not declare (`E0080`) |
//!
//! The forward equation is a plain type equation and nothing more, which is the whole of why the
//! `ref` grammar needs no artifact for it: what a referring field carries is
//! `<Target as Identifiable>::Id`, and the target's own impl already answers that. The ID rather
//! than the key because a field is ONE COLUMN and an id is a TABLE-WIDE address — every table's is
//! unique — where a lineage-bearing record's key is a whole ancestry path no column could hold. The
//! one fact no projection can conjure is which columns point back, and that is the one impl.
//!
//! `Identifiable` rather than the entity binding, because the equation spends exactly that
//! capability: a target's key, lineage and row form say nothing about the column pointing at it. The
//! refusal a mismatched `ref` gets therefore names the small trait, which is the one that failed.
//!
//! # ONE impl per (source, target) PAIR
//!
//! Two `ref`s at one target give ONE impl whose `Fields` has two members. Grouping is by the
//! target's SPELLING, because a macro holds tokens: two spellings of one type — `media::Video`
//! beside a `use`d `Video` — group apart and collide as `E0119` at the expansion. A declaration
//! writes its target one way, and nothing here can see that two ways meet.
//!
//! # The artifacts are minted INSIDE the record's anonymous const
//!
//! One struct per referring field, named `<Record><Field>Ref`, declared beside the impls rather
//! than beside the emitted types. That placement is what keeps a relation from costing the declaring
//! scope a name: the artifacts are reachable only as `Related::Fields`' members, which is the only
//! place anything asks for them, and they are covered by neither `missing_docs` nor the emitted-name
//! collision rule because neither reaches inside the const.
//!
//! Each is `struct …Ref(());` rather than a bare unit, because a VALUE of an evidence type answers
//! nothing and nothing may mint one: the private field seals construction in the SHAPE, where the
//! const's scope seals it only in the placement. The two are not the same promise — a type that
//! moves keeps its shape and loses its scope, and the day the wire round moves these out to be
//! nameable a bare unit would silently become constructible.
//!
//! They carry the RECORD's visibility even so, and that is `E0446` rather than tidiness: the
//! associated type binding on a public record's impl is public interface, so an artifact less
//! visible than the record cannot be named there. Measured. They derive
//! [`Debug`](core::fmt::Debug) because every type this emitter mints does and a consumer cannot add
//! a derive to a generated one — not because a lint asks: `missing_debug_implementations` reaches
//! nothing inside the const, since nothing there is nameable from outside the crate, and a
//! `deny` over a corpus of these reported the declarations' own records and none of the artifacts.
//!
//! What they buy is the refusal's own evidence. `Fields` prints in the shorthand's `E0277` as
//! `(VideoTrackVideoIdRef, VideoTrackCoverIdRef)`, which names the source and both of its offending
//! fields — where a tuple of framework-generic markers would have printed one type twice.
//!
//! Two field names with ONE upper-camel spelling — `video_id` beside `videoId` — mint one artifact
//! name twice and are a duplicate definition inside the expansion. That is the class
//! `RecordModel::emitted_methods` refuses for METHOD names, and it is not refused here because
//! nothing has asked: this crate takes a rule when something live wants it.

use heck::ToUpperCamelCase as _;
use quote::{format_ident, quote};

use crate::model::{Derived, Field, RecordModel, Through};

impl RecordModel {
  /// Every relation this declaration states, from both ends.
  ///
  /// Emitted into the record's anonymous const, with the impls, because all of it is impls,
  /// artifacts and anonymous constants — nothing here is API.
  ///
  /// Reachable from the crate rather than from `emit` alone, so the acceptance can read the
  /// relation half on its own: the audits emit no TYPE, so a walk over the emitted file cannot see
  /// most of what this writes.
  pub(crate) fn relations(&self) -> proc_macro2::TokenStream {
    let equations = self.fields.iter().filter_map(|field| {
      let reference = field.reference.as_ref()?;
      let refers_to = self.framework(&["transform"], "refers_to");
      let value = self.referring_value(field);
      let target = &reference.target;
      Some(quote!(const _: fn() = #refers_to::<#value, #target>;))
    });
    let pairs = self.pairs().into_iter().map(|(target, fields)| {
      let record = &self.record;
      let related = self.framework(&["transform"], "Related");
      let marker = self.framework(&["transform"], "Reference");
      let field_name = self.framework(&["field"], "FieldName");
      let artifacts: Vec<syn::Ident> = fields
        .iter()
        .map(|field| self.artifact(&field.column.source))
        .collect();
      let names: Vec<String> = fields
        .iter()
        .map(|field| field.column.source.to_string())
        .collect();
      let vis = &self.vis;
      quote! {
        #(
          #[derive(::core::fmt::Debug)]
          #vis struct #artifacts(());

          #[automatically_derived]
          impl #marker for #artifacts {}
        )*

        #[automatically_derived]
        impl #related<#target> for #record {
          type Fields = (#(#artifacts,)*);

          const COLUMNS: &'static [&'static #field_name] = &[#(#field_name::new(#names)),*];
        }
      }
    });
    let reverse = self.derived.iter().map(|entry| self.audit(entry));
    let memberships = self.implements.iter().map(|interface| {
      let record = &self.record;
      let implements = self.framework(&["transform"], "Implements");
      quote! {
        #[automatically_derived]
        impl #implements<#interface> for #record {}
      }
    });
    quote! {
      #(#equations)*
      #(#pairs)*
      #(#reverse)*
      #(#memberships)*
    }
  }

  /// The referring fields, grouped by the TARGET each names, in declaration order.
  ///
  /// Grouped rather than emitted one impl apiece, because the impl is a per-PAIR fact: two fields
  /// naming one target are one relation with two ways through it, and two impls would be `E0119`.
  fn pairs(&self) -> Vec<(&syn::Path, Vec<&Field>)> {
    let mut pairs: Vec<(&syn::Path, Vec<&Field>)> = Vec::new();
    for field in &self.fields {
      let Some(reference) = &field.reference else {
        continue;
      };
      let spelling = tight(&reference.target);
      match pairs
        .iter_mut()
        .find(|(target, _)| tight(target) == spelling)
      {
        Some((_, fields)) => fields.push(field),
        None => pairs.push((&reference.target, vec![field])),
      }
    }
    pairs
  }

  /// The type the id equation is checked against: the field's own, or what it HOLDS.
  ///
  /// The projection is written `<T as State<Extracted<Inner>>>::Output` and never read off the
  /// declaration's tokens, which is the same rule an element marker resolves under and for the same
  /// reason: `type Ids = Vec<Uuid7>` holds an element that no token walk can see, and a downstream
  /// container joins the layer by writing that one impl.
  fn referring_value(&self, field: &Field) -> proc_macro2::TokenStream {
    let ty = &field.column.ty;
    if field
      .reference
      .as_ref()
      .is_none_or(|reference| reference.through == Through::Value)
    {
      return quote!(#ty);
    }
    let state = self.framework(&["state"], "State");
    let extracted = self.framework(&["state"], "Extracted");
    let inner = self.framework(&["state"], "Inner");
    quote!(<#ty as #state<#extracted<#inner>>>::Output)
  }

  /// One REVERSE position's audit, in whichever of the two forms the declaration wrote.
  ///
  /// The shorthand's is a BOUND, because *how many fields point back* is an arity question and the
  /// evidence answers it as a type. The full form's is a CONSTANT, because *which field* is a name
  /// and a name is not a type on stable Rust — so the check is an evaluation over the evidence's own
  /// `COLUMNS`, and its refusal carries the sentence written here.
  ///
  /// Both name the SOURCE at the span the declaration wrote it: the target path is parsed out of a
  /// string literal, which respans to the literal, so the refusal lands on the `derived` entry
  /// rather than on the derive.
  fn audit(&self, entry: &Derived) -> proc_macro2::TokenStream {
    let record = &self.record;
    let source = &entry.source;
    let Some(field) = &entry.field else {
      let one = self.framework(&["transform"], "one_field_points_back");
      return quote!(const _: fn() = #one::<#source, #record>;);
    };
    let related = self.framework(&["transform"], "Related");
    let refers_through = self.framework(&["transform"], "refers_through");
    let named = field.value();
    let why = format!(
      "`{source}` declares no `ref` field called `{named}` naming `{record}` — \
       `derived({position}(type = \"…\", field = \"…\"))` selects one of the SOURCE's own `ref` \
       fields, and the source's declaration is where they are written",
      source = tight(source),
      position = entry.name,
    );
    // At the LITERAL's span, so the constant's refusal lands on the name it could not find.
    // `E0080` reports at the const item rather than at a bound's argument, so unlike every other
    // audit here the span has to be put on the item itself.
    quote::quote_spanned! {field.span()=>
      const _: () = ::core::assert!(
        #refers_through(<#source as #related<#record>>::COLUMNS, #named),
        #why
      );
    }
  }

  /// What one referring field's artifact is called: `<Record><Field>Ref`.
  ///
  /// Named after the field rather than numbered, because the name is what the shorthand's refusal
  /// SHOWS — see this module's note on where the artifacts live.
  ///
  /// Reachable from the crate, not private to this module, for the reason
  /// [`emitted_methods`](RecordModel::emitted_methods) is asked of the model: a check that wants to
  /// know which types an emission declares asks the emitter rather than keeping a second copy of the
  /// rule.
  pub(crate) fn artifact(&self, field: &syn::Ident) -> syn::Ident {
    format_ident!(
      "{record}{field}Ref",
      record = self.record,
      field = field.to_string().to_upper_camel_case(),
    )
  }
}

/// A path as a MESSAGE spells it — `quote!`'s spacing removed, so `media::VideoTrack` reads as it
/// was written rather than as `media :: VideoTrack`.
fn tight(path: &syn::Path) -> String {
  quote!(#path).to_string().replace(' ', "")
}