ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The ARM FACTS: what the engine assembles a union statement out of, one binding per SQL database
//! the declaration is about.
//!
//! # Facts here, statement there
//!
//! The derive emits NO SQL TEXT. What a declaration knows is its own contract — which members there
//! are, what each of them calls each shared column — and where each member's rows live, which is the
//! MEMBER's declaration answering. How those become a statement is the engine's and changes with the
//! engine, so the binding carries the facts and the framework's `SqlInterface` is where they are
//! spent.
//!
//! # The impl names a CONCRETE backend, where a record's names a parameter
//!
//! A record's query binding is on the ROW, so the row IS one database and the dialect stays open. An
//! interface has no row of its own to be one database: its PROJECTION is per database, and a
//! projection is an associated type. So there is one impl per database, each naming that database's
//! backend and riding its conditional-expansion gate — the arrangement the row equations already
//! have, one layer up. Ungated, a declaration naming Postgres would fail to compile in a build
//! without the Postgres driver.
//!
//! # Every name in it is ASKED FOR
//!
//! ```text
//! <<Video as Record<Sqlite>>::Row as SqlQuery<Sqlite>>::ADDRESS
//!   └── the member, as the declaration spelled it
//!            └── the per-(record, database) pairing that names a target's ROW
//!                                             └── the member's own table and address column
//! ```
//!
//! `Record<Db>::Row` is the projection the row equations already read a member's columns through, so
//! nothing here rebuilds a name: a member that renames its table or its row moves both readings at
//! once. What is NOT reachable is anything below that — a stored column's TYPE has no projection —
//! which is what the interface's own pins are for and why the id stays off the projection row.

use quote::quote;

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

impl InterfaceModel {
  /// One query binding per SQL database, each behind that database's gate.
  ///
  /// Inside an anonymous const, for the reason the contract's own impls are: an impl names nothing
  /// anybody has to spell, so it sits where it collides with nothing. Coherence is unaffected —
  /// where an impl is WRITTEN says nothing about where it applies.
  pub(crate) fn bindings(&self) -> proc_macro2::TokenStream {
    if !self.projects() {
      return quote!();
    }
    let blocks = self.sql_databases().into_iter().map(|kind| {
      let gate = self.framework(&["gate"], &kind.gate().to_string());
      let binding = self.binding(kind);
      // The HYDRATION rides the same gate for the same reason: it names this database's backend, so
      // ungated a declaration mentioning Postgres would fail to compile in a build without the
      // Postgres driver.
      let hydration = self.hydration(kind);
      // The CROSSING is here rather than beside the predicate it builds, and the gate is why: the
      // predicate is a type generic in its database and needs no driver to be declared, where the
      // crossing names a concrete backend — which is exactly what makes it writable at all. See
      // [`cross`](super::cross).
      let crossing = self.crossing(kind);
      quote! {
        #gate! {
          #binding
          #hydration
          #crossing
        }
      }
    });
    quote! {
      const _: () = {
        #(#blocks)*
      };
    }
  }

  /// ONE database's binding: the vocabulary, the projection, the arms, and where each member's rows
  /// live.
  fn binding(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let interface = &self.name;
    let vocabulary = super::default_kind_name(interface);
    let row = super::default_row_name(interface, kind);
    let cursor = self.cursor_name(kind);
    let comparison = self.comparison_name(kind);
    let order_by = super::default_order_by_name(interface);

    let sql_interface = self.framework(&["query", "sql"], "SqlInterface");
    let sql_query = self.framework(&["query", "sql"], "SqlQuery");
    let record = self.framework(&["transform"], "Record");
    let arm = self.framework(&["interface"], "InterfaceArm");
    let column = self.framework(&["interface"], "InterfaceColumn");
    let field_name = self.framework(&["field"], "FieldName");
    let address_ty = self.framework(&["comparison"], "RecordAddress");
    let order_term = self.framework(&["cursor"], "OrderTerm");
    let id_alias = self.framework(&["interface"], "ID");
    // STATED only where the declaration moved them. The engine defaults both items to the
    // framework's own words, so a declaration that named no prefix expands exactly as it did before
    // the knob existed — the posture `SqlQuery::COLLECTIONS` already takes one trait over.
    let words = self
      .mints_the_default_words(kind)
      .then(proc_macro2::TokenStream::new);
    let words = words.unwrap_or_else(|| {
      let discriminant = self.kind_word(kind);
      let source = self.source_word(kind);
      quote! {
        const KIND: &'static #field_name = #field_name::new(#discriminant);
        const SOURCE: &'static #field_name = #field_name::new(#source);
      }
    });
    let (module, item) = kind.backend();
    let backend = self.framework(module, item);

    let arms = self.members.iter().map(|member| {
      let variant = &member.ident;
      // The two names of every shared column: the INTERFACE's, which the projection aliases to and
      // the row decodes under, and what THIS member calls it. They differ exactly where a member
      // block moved the column, and both are carried — see `InterfaceField::column`, the one
      // resolver every reader of a member's column goes through.
      let columns = self.projected().map(|field| {
        let promised = field.name.to_string();
        let held = field.column(&member.ident).to_string();
        quote!(#column::new(#field_name::new(#promised), #field_name::new(#held)),)
      });
      quote!(#arm::new(#vocabulary::#variant, &[#(#columns)*]),)
    });
    let addresses = self.members.iter().map(|member| {
      let variant = &member.ident;
      let ty = &member.ty;
      quote! {
        #vocabulary::#variant =>
          <<#ty as #record<#backend>>::Row as #sql_query<#backend>>::ADDRESS,
      }
    });

    // The value a boundary row holds at one term, one shared column at a time — read off the DECODED
    // projection, because every term of an interface's order is a column of the union's own output.
    let values = self.projected().map(|field| {
      let name = &field.name;
      let external = field.name.to_string();
      let variant = crate::emit::upper_camel(&external);
      quote! {
        #external => ::core::option::Option::Some(
          #cursor::#variant(::core::clone::Clone::clone(&__ingraph_row.#name)),
        ),
      }
    });

    // The COLLECTION half of the predicate, per ARM. A collection is the one shared column no arm
    // can alias into the union's output, so its conjuncts are rendered against that member's own
    // edge table — at the column THIS member calls it, which is the same resolver the arms' own
    // column list and the row equations go through.
    let collections: Vec<&InterfaceField> = self.collected().collect();
    let complex = self.framework(&["comparison"], "ComplexComparison");
    let comparison_backend = self.framework(&["comparison"], "Backend");
    let frame = self.framework(&["comparison"], "Frame");
    let at_ty = self.framework(&["comparison"], "At");
    let collection_arms = self.members.iter().map(|member| {
      let variant = &member.ident;
      let parts = collections.iter().map(|field| {
        let rust = &field.name;
        let held = field.column(&member.ident).to_string();
        quote! {
          let __ingraph_frame = #at_ty::frame(__ingraph_at, #field_name::new(#held));
          __ingraph_builder = #complex::<#backend>::apply(
            &__ingraph_filter.#rust,
            #frame::at(&__ingraph_frame),
            __ingraph_builder,
          )?;
        }
      });
      quote!(#vocabulary::#variant => { #(#parts)* })
    });
    let collection_counts = self.members.iter().map(|member| {
      let variant = &member.ident;
      let counts = collections.iter().map(|field| {
        let rust = &field.name;
        quote!(#complex::<#backend>::conjuncts(&__ingraph_filter.#rust))
      });
      quote!(#vocabulary::#variant => #(#counts)+*,)
    });
    // STATED only where the declaration has a collection to state it for. The trait defaults both
    // items to *nothing*, so an interface whose shared columns are all single-valued expands exactly
    // as it did before this pair existed and its statement is byte-for-byte what it was.
    let collection_items = collections.is_empty().then(proc_macro2::TokenStream::new);
    let collection_items = collection_items.unwrap_or_else(|| {
      let count_doc = leading(
        "How many conjuncts this predicate's COLLECTION columns render for one member's arm.",
      );
      let apply_doc = leading(
        "Render this predicate's COLLECTION columns for one member's arm, at the column THAT member \
         calls each of them — which is what its own edge table is derived from.",
      );
      quote! {
        #[doc = #count_doc]
        fn collection_conjuncts(
          __ingraph_filter: &Self::Comparison,
          __ingraph_kind: #vocabulary,
        ) -> ::core::primitive::usize {
          match __ingraph_kind {
            #(#collection_counts)*
          }
        }

        #[doc = #apply_doc]
        fn collections<'__ingraph_q>(
          __ingraph_filter: &'__ingraph_q Self::Comparison,
          __ingraph_kind: #vocabulary,
          __ingraph_at: #at_ty<'_>,
          mut __ingraph_builder: <#backend as #comparison_backend>::Builder<'__ingraph_q>,
        ) -> ::core::result::Result<
          <#backend as #comparison_backend>::Builder<'__ingraph_q>,
          <#backend as #comparison_backend>::Error,
        > {
          match __ingraph_kind {
            #(#collection_arms)*
          }
          ::core::result::Result::Ok(__ingraph_builder)
        }
      }
    });

    let address_doc = leading(
      "Where this member keeps its rows, and what one of them is addressed by — the MEMBER's own \
       answer, reached through its query binding. An interface holds no table of its own to give, \
       and a copy here would be a second spelling of a name `persist(<db>(table = \"…\"))` can move.",
    );
    let term_doc = leading(
      "One written term as the statement renders it. There is no per-database spelling to choose \
       between: every arm has already aliased its member's column to the interface's own name, so \
       what the `ORDER BY` names is that name in every database.",
    );
    let value_doc = leading(
      "The value this row holds at `term`. The TAIL's two slots are minted from the ADDRESS — the \
       discriminant is what the address says it is, so the pair cannot disagree — and every other \
       term is a shared column the projection already decoded.",
    );
    quote! {
      #[automatically_derived]
      impl #sql_interface<#backend> for #interface {
        type Kind = #vocabulary;
        type Row = #row;
        type Comparison = #comparison<#backend>;
        type Value = #cursor;
        type Order = #order_by;

        const ARMS: &'static [#arm<#vocabulary>] = &[#(#arms)*];
        #words

        #[doc = #address_doc]
        fn address(kind: #vocabulary) -> #address_ty {
          match kind {
            #(#addresses)*
          }
        }

        #[doc = #value_doc]
        fn value(
          __ingraph_row: &#row,
          __ingraph_term: &#order_term,
        ) -> ::core::option::Option<#cursor> {
          let __ingraph_column = #order_term::column(__ingraph_term);
          if __ingraph_column == <#interface as #sql_interface<#backend>>::KIND {
            return ::core::option::Option::Some(
              #cursor::__IgKind(#row::id(__ingraph_row).kind()),
            );
          }
          if __ingraph_column == #id_alias {
            return ::core::option::Option::Some(#cursor::__IgAddress(
              ::core::clone::Clone::clone(#row::id(__ingraph_row)),
            ));
          }
          match #field_name::as_str(__ingraph_column) {
            #(#values)*
            _ => ::core::option::Option::None,
          }
        }

        #[doc = #term_doc]
        #[inline]
        fn term(order: #order_by) -> #order_term {
          #order_by::term(order)
        }

        #collection_items
      }
    }
  }
}