ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The ROW EQUATIONS: one per (stored field, database, member), saying the member's row really
//! carries the column at the type the interface pinned.
//!
//! The contract's own impls read a member's DOMAIN struct. That is one half of the promise, and the
//! half a fan-out cannot spend: a query reads ROWS, and a row is per database with its own column
//! names and its own stored types. So each pin is discharged where it is made — at the member's own
//! row, at a concrete backend, at the type the declaration said.
//!
//! # It is a NEVER-RUN function, and the leading underscore is load-bearing
//!
//! Nothing calls these. A function nobody calls is `dead_code` in the crate the expansion lands in —
//! a warning at a span its author cannot edit — and the one thing that silences it without an
//! `#[allow]` is rustc's own convention: an item whose name begins with `_` is not reported.
//! Measured rather than assumed; the same function without the underscore is a denied warning.
//!
//! What the name carries beyond that is WHERE the failure is. `_video_sqlite_mask` names the
//! member, the database and the field, so an `E0308` about it locates itself before a reader has
//! looked at anything else — and the pair of teeth is worth naming: a row that carries no such
//! column is refused at the column, and one carrying it at another type is refused at the type.
//!
//! # The pin has TWO readers, and the WORD is what tells them apart
//!
//! This equation reads the pin as the type the ROW holds; the crossing reads it as the type the
//! comparison is keyed on. For every column those are one type, and for a COLLECTION they are not:
//! a database stores a collection's ELEMENTS at the pinned type and the row holds the `Vec` of
//! them, which is exactly the split a record already carries — its `type` names one element and its
//! row field is the list.
//!
//! A record can tell the two apart because its field declared an interpretation WORD, and an
//! interface pin declares one now — [`InterfaceField::marker`](crate::interface::InterfaceField),
//! read here through [`InterfaceField::collects`]. So the two readings are two spellings of one
//! declared fact rather than one reading used at both sites: `&Vec<V>` here and `V` at the
//! crossing, and a pin with no collection word is `&V` at both as it always was.
//!
//! Before the word there was one reading and it was the wrong one here, which is what
//! `an_interface_operand_crossing_absorbs_a_collections_legs`'s second error pinned — the
//! refuse-until this line replaces.
//!
//! # The KIND is a second fact, and it needs a second equation
//!
//! `Vec<V>` is what a sequence's row holds and it is what a SET's row holds too, so this equation
//! cannot see a member that answered the interface's `list(…)` with a `set(…)` of its own — and the
//! two are different storage: a sequence's edge table carries an ordinal and a set's does not. That
//! is [`Self::collection_equation`], which meets the member at a projection this one does not read.
//!
//! # The gate is per DATABASE, and it is what keeps declare-many/build-one
//!
//! An equation names a CONCRETE backend, which is what makes it an audit rather than an obligation
//! deferred to a call site. Ungated, a declaration naming Postgres would fail to compile in a build
//! without the Postgres driver. Wrapped in the framework's conditional-expansion gate, the equations
//! exist per DECLARED ∩ COMPILED-IN backend — the same arrangement a record's own storability audit
//! rides, stated one layer up.
//!
//! # A member's row is reached by FIELD, and the declaration is where that has to be true
//!
//! `row.mask` and not `row.mask_ref()`, so the refusal is about the COLUMN rather than about an
//! accessor's name. The consequence is module locality: an emitted row's fields are private, so an
//! interface reads its members' rows from where those rows are declared. That is the same locality
//! the domain contract already has — it reads the members' own struct fields — and the two agree
//! rather than each having a rule.
//!
//! WHICH column is asked of [`InterfaceField::column`](crate::interface::InterfaceField::column),
//! so a member that carries the field under another name is read at that name here and at the same
//! name in its contract impl. The default and the rename come out of one function, which is what
//! keeps the two accesses from disagreeing about a column nobody moved.

use quote::{format_ident, quote};

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

impl InterfaceModel {
  /// Every pin, discharged at the row that has to satisfy it.
  ///
  /// Empty for a declaration that names no database at all: an interface whose fields pin nothing
  /// and whose `persist(…)` selects nothing has stated no fact about rows, so there is nothing here
  /// to check and no gate to write.
  pub(crate) fn equations(&self) -> proc_macro2::TokenStream {
    let databases = self.databases();
    if databases.is_empty() || self.stored().next().is_none() {
      return quote!();
    }
    let blocks = databases.into_iter().map(|kind| {
      let gate = self.framework(&["gate"], &kind.gate().to_string());
      let pairs = || {
        self
          .members
          .iter()
          .flat_map(|member| self.stored().map(move |field| (member, field)))
      };
      let equations = pairs().map(|(member, field)| self.equation(member, field, kind));
      // The KIND equation is a COLLECTION's alone, and its absence everywhere else is the design:
      // a scalar pin has one stored reading, so the row equation above already says everything
      // there is to say about it.
      let kinds = pairs()
        .filter(|(_, field)| field.collects())
        .map(|(member, field)| self.collection_equation(member, field, kind));
      quote! {
        #gate! {
          #(#equations)*
          #(#kinds)*
        }
      }
    });
    quote! {
      const _: () = {
        #(#blocks)*
      };
    }
  }

  /// ONE equation: this member's row, in this database, at this field's pinned type.
  fn equation(
    &self,
    member: &UnionMember,
    field: &InterfaceField,
    kind: DatabaseKind,
  ) -> proc_macro2::TokenStream {
    let at = field.name.span();
    let name = format_ident!(
      "_{member}_{database}_{field}",
      member = union::word(&member.ident),
      database = kind.as_str(),
      field = field.name,
    );
    let ty = &member.ty;
    let record = self.framework(&["transform"], "Record");
    let (module, item) = kind.backend();
    let backend = self.framework(module, item);
    // The column this MEMBER carries the field under, which is the interface's own field name
    // unless a member block moved it. One resolver, three consumers — see
    // [`InterfaceField::column`].
    let column = field.column(&member.ident);
    // WHICH reading of the pin this site takes, and the WORD is the whole of what decides it: a
    // collection's row field is the LIST of what the database stores, where the crossing one module
    // over is keyed on the element. See this module's note.
    let held = self.row_at(field, kind);
    // Respanned at the field the INTERFACE declared, for the reason the contract's own impls are:
    // the derive's span points at `#[ingraph::interface(…)]`, which names no field at all.
    quote::quote_spanned! {at=>
      fn #name(row: &<#ty as #record<#backend>>::Row) -> &#held {
        &row.#column
      }
    }
  }

  /// ONE consistency equation: this member's own COLLECTION KIND, against the word the interface
  /// promised.
  ///
  /// # The derives cannot see each other, so the two words MEET at a projection
  ///
  /// A member's `list(scalar)` is a fact of the member's declaration, and nothing in an interface's
  /// derive input holds it. What both declarations can name is `<M as Record<Db>>::Comparison` —
  /// the member's own predicate in this database — and its field for this column is the comparison
  /// the column's filter crosses into. That type is where the kind becomes VISIBLE: a sequence
  /// lowers to the edge kind and a set to the edge SET kind, and the two are different types
  /// because they are different storage — a sequence's edge table carries an ordinal and a set's
  /// rows are `(key…, value)` unique.
  ///
  /// So the equation is a never-run function that hands a member's own comparison back at the type
  /// the INTERFACE's word resolves to, and a member whose word disagrees is `E0308` naming both
  /// kinds. It reads the column through the borrow face rather than the field, which is the one
  /// difference from the row equation beside it: a comparison's fields are private and its `_ref`
  /// accessors are the emission's own reading face.
  ///
  /// # It rides the SAME gate and the same span, because it is the same kind of audit
  ///
  /// A comparison is per database, so the equation is; and it is spanned at the interface's field,
  /// so an `E0308` locates itself at the pin whose word was answered with another.
  ///
  /// What it does NOT check is the storage FORM — array or edge table — which is per member and per
  /// dialect and settled by the element's own row. Nothing here needs it: the interface's projection
  /// carries no collection column on any backend, so no reader of this pin is told where the member
  /// keeps it.
  ///
  /// # The asserted type is bound to an ALIAS, and the reason is a lint in the DECLARER's crate
  ///
  /// Four projections deep — a marker to a filter, a filter to a comparison — is
  /// `clippy::type_complexity` at a function signature, and the span it fires at is the pin, which
  /// is a declaration's own source and not something an expansion may leave a warning on. The alias
  /// carries the depth and the signature carries a name, which is what that lint asks for; an
  /// `#[allow]` would have been the expansion silencing a lint in somebody else's crate.
  fn collection_equation(
    &self,
    member: &UnionMember,
    field: &InterfaceField,
    kind: DatabaseKind,
  ) -> proc_macro2::TokenStream {
    let at = field.name.span();
    let name = format_ident!(
      "_{member}_{database}_{field}_collection",
      member = union::word(&member.ident),
      database = kind.as_str(),
      field = field.name,
    );
    let ty = &member.ty;
    let record = self.framework(&["transform"], "Record");
    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
    let (module, item) = kind.backend();
    let backend = self.framework(module, item);
    let column = field.column(&member.ident);
    let borrow = crate::method::Member::Borrow.name(column);
    let filter = self.filter_of(field);
    let pinned = self.stored_at(field, kind);
    let alias = format_ident!("{}", crate::emit::upper_camel(&name.to_string()));
    quote::quote_spanned! {at=>
      type #alias = <#filter as #to_comparison<#pinned, #backend>>::Comparison;

      fn #name(__ingraph_held: &<#ty as #record<#backend>>::Comparison) -> &#alias {
        __ingraph_held.#borrow()
      }
    }
  }
}