ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The CROSSING: a wire filter becomes one database's predicate, and the operands enter storage.
//!
//! ```text
//! MediaFilter { title: Some(TextFilter::eq("reel")), mask: Some(ScalarFilter::eq(9u64)) }
//!   │
//!   ├─ per shared column: the comparison its filter crosses into, at the type this database pins
//!   ├─ the declared operand converter, where `input(comparison(<db>(try_into = "…")))` names one
//!   └─ MediaSqliteComparison<Sqlite>
//! ```
//!
//! # It names a CONCRETE backend, and that is the whole of why it can be written
//!
//! A record's comparison is generic in its database and stays that way — `<E>Filter`'s own
//! `ToDatabaseComparison<Row, Db>` is stated at a PARAMETER, so a declaration storing one dialect
//! need not compile that dialect's driver — and at a generic `Db` the crossing is unwritable. The
//! wall is measured, and it is the one `ToFlattenedComparison` records: a `where` clause whose self
//! type is `<F as ToDatabaseComparison<V, Db>>::Comparison` makes rustc resolve the projection
//! through the impl that DEFINES it, so the clause demands whatever that impl demands of `Db` —
//! `Db: sqlx::Database`, `V: Carrier<Db>` and `Db::Builder<'q> == SqlConjunction<'q, Db>`, the last
//! of which no `Db` bound can supply.
//!
//! An interface's engine face is already per database. `SqlInterface<Sqlite>` binds
//! `type Comparison = <I>SqliteComparison<Sqlite>`, the row equations name a concrete backend, and
//! the hydration does too — so this impl names the same one, rides the same gate, and every
//! projection in it NORMALISES: the comparison resolves to a concrete kind, its `TryFromFilter` row
//! is the one that kind implements, and its `try_from_filter_with` is an inherent method that
//! exists. **The record's wall is about a generic dialect and not about the crossing**, and an
//! interface simply does not have a generic dialect to be stopped by.
//!
//! # A declared converter REPLACES the chain rather than joining it
//!
//! `input(comparison(<db>(try_into = "…")))` is handed one operand and answers with the stored form,
//! and the declaration owns the whole hop. A field with no entry crosses through the stored type's
//! own [`TryFrom`] — which for the identity crossing is `Infallible` through std's own reflexive
//! blanket, so a column that stores what it holds is provably unable to refuse.
//!
//! It is not a convenience. `u64` pinned at `BeU64` has no `TryFrom` between the two — the storage
//! form is a byte layout rather than a numeric widening — so a pinned column of that shape crosses
//! through the declaration or not at all, and the refusal is `E0277` naming the pair.
//!
//! # ONE spelling, whatever KIND the column is — including a collection
//!
//! This emitter cannot tell a collection column from a scalar one and must not try: `type Ids =
//! Vec<Uuid7>` and a scalar are the same tokens, so what a column IS is the compiler's answer and
//! never this crate's reading. The declared leg is therefore written once, at two arguments, and the
//! kind the projection resolves to decides what happens.
//!
//! A collection's crossing has TWO converting slots — its own operands, and the ones inside its
//! nested `any` filter — and both are made of the same element, so ONE declaration fills both. That
//! composition lives on the kinds themselves (`SqlEdgeComparison::try_from_filter_with` and its
//! seven siblings), where the two-function entry is `try_from_filter_with_element`. So a collection
//! column reaches the declaration through the very call a scalar column reaches it through, and what
//! it refuses with is that kind's own error rather than the converter's bare one — which the
//! declared error cell absorbs exactly as it absorbs every other leg.
//!
//! **A collection column IS an interface's column**, and what settles the pin's two readings is the
//! interpretation WORD the pin carries: the crossing here is keyed on the ELEMENT a database stores
//! and the member's row holds the LIST of them, which is
//! [`InterfaceModel::stored_at`](crate::interface::InterfaceModel::stored_at) and its `row_at`
//! beside it — one function apart, one declared fact. A pin whose type is a collection and whose
//! declaration writes no word is read as a scalar at both sites, which is `E0308` at the row
//! equation naming the pair. Pinned by
//! `an_interface_operand_crossing_absorbs_a_collections_legs`, whose first refusal is this module's
//! absorption and whose second is the missing word.
//!
//! # Every refusal is bound to a NAMED type before it is converted
//!
//! Which is what makes the declared error cell's obligations legible: a cell that cannot absorb one
//! of the columns' crossings is `E0277` at the declaration naming WHICH, exactly as the hydration
//! cell's four legs already are. The default is the boxed refusal, which absorbs all of them
//! through `core`'s own blanket.

use quote::quote;

use crate::{
  emit::leading,
  interface::{InterfaceField, InterfaceModel},
  model::DatabaseKind,
};

impl InterfaceModel {
  /// ONE database's crossing: `TryFromFilter<<I>Filter>` for that database's predicate.
  pub(crate) fn crossing(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let interface = &self.name;
    let filter = super::default_filter_name(interface);
    let comparison = self.comparison_name(kind);
    let error = self.operand_error(kind);
    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
    let (module, item) = kind.backend();
    let backend = self.framework(module, item);

    let stored: Vec<&InterfaceField> = self.stored().collect();
    let names: Vec<&syn::Ident> = stored.iter().map(|field| &field.name).collect();
    let legs = stored.iter().map(|field| {
      let rust = &field.name;
      let wire = self.filter_of(field);
      let pinned = self.stored_at(field, kind);
      let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
      let held = quote!(<#wire as #to_comparison<#pinned, #backend>>::Comparison);
      // The DECLARED leg and the default one are two shapes rather than one with a hole, for the
      // reason a declared marker and an inferred one are: what a declared converter SAYS is *do not
      // ask the stored type how to take this value, I have answered*. The kind's own
      // `try_from_filter_with` is the entry point it says that through, and the trait crossing below
      // is the same call with the stored type's `TryFrom` in place of the function.
      let crossed = match field.operand(kind) {
        Some(convert) => quote! {
          match <#held>::try_from_filter_with(__ingraph_held, #convert) {
            ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
            ::core::result::Result::Err(__ingraph_why) => {
              return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
            }
          }
        },
        None => quote! {
          match <#held as #try_from_filter<#wire>>::try_from_filter(__ingraph_held) {
            ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
            ::core::result::Result::Err(__ingraph_why) => {
              let __ingraph_why: <#held as #try_from_filter<#wire>>::Error = __ingraph_why;
              return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
            }
          }
        },
      };
      quote! {
        let #rust = match __ingraph_filter.#rust {
          ::core::option::Option::Some(__ingraph_held) => #crossed,
          // A column the client said nothing about: the EMPTY comparison, which renders no
          // conjunct — so an unwritten field narrows nothing rather than matching nothing.
          ::core::option::Option::None => ::core::default::Default::default(),
        };
      }
    });

    let what = super::row::what(kind);
    let doc = leading(&format!(
      "Cross a wire filter into the predicate {what} is queried by — every operand through the \
       crossing its declaration names, and the empty comparison wherever the client asked \
       nothing.\n\n# Errors\n[`{error}`] — whatever an operand's crossing into its stored form \
       refused with.",
      error = super::contract::tight(&error)
    ));
    quote! {
      #[automatically_derived]
      impl #try_from_filter<#filter> for #comparison<#backend> {
        type Error = #error;

        #[doc = #doc]
        fn try_from_filter(
          __ingraph_filter: #filter,
        ) -> ::core::result::Result<Self, Self::Error> {
          #(#legs)*
          ::core::result::Result::Ok(Self::new(#(#names,)*))
        }
      }
    }
  }
}