ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The WIRE query surface: the predicate a client sends, and the arguments that carry it.
//!
//! # One filter, where the page has one predicate per database
//!
//! `<I><Db>Comparison` is per database because a predicate holds STORED values, and what a database
//! stores is the interface's own pin. A client sees none of that: it writes the contract's own
//! names at the contract's own types, once, and which database answers is a deployment's business.
//! So there is ONE `<I>Filter`, and the crossing into a database is [`cross`](super::cross) — the
//! single place storage enters, exactly as it is for a record.
//!
//! # The operand's form is the DOMAIN type, and the wire form is not spent here
//!
//! A record's filter field carries that field's declared wire form. An interface's does not, and
//! the reason is the crossing this round emits: an operand's filter and the comparison's are ONE
//! KIND or nothing crosses between them, and a wire form is free to move a `u64` onto a `String` —
//! which moves the operand from the scalar kind to the text one and leaves the crossing unwritable.
//! What a wire form is for is the type a SCHEMA publishes, and no schema is rendered yet, so
//! `graphql(type = "…")` stays read-and-held rather than spent on the one face it would break.
//!
//! # The COMPUTED tier is statically absent, and the absence is the refusal
//!
//! A filter names a column a statement can compare; a computed field is derived from a member's
//! wire OUTPUT and is a column nowhere. So the filter's fields are the STORED tier and there is no
//! runtime refusal to write — a client filtering on a computed field names a member of this struct
//! that does not exist, which is `E0560` at the call site naming the field. The order-by already
//! draws that line and this is the same line, one type over.
//!
//! # The arguments MIRROR the lane, and the lane is `InterfaceFind`'s
//!
//! | member | the engine's | why it is here |
//! |---|---|---|
//! | `filter` | `InterfaceFind::filter` | the predicate the query is narrowed by |
//! | `order` | `InterfaceFind::order` | the terms, in the sequence they run |
//! | `first` / `last` | `InterfaceOrdered::first` / `last` | which end of the order the page is taken from |
//! | `after` / `before` | `InterfacePaging::after` / `before` | where a page resumes |
//!
//! **No ceiling and no skip**, where a record's argument object has both: `InterfaceFind` offers
//! `limit` on nothing — an interface's order is never absent, so *any N rows, unordered* is not a
//! question it can be asked — and there is no `OFFSET` lane at all. A member a caller could set and
//! no method could spend is an argument object promising a query the engine refuses.
//!
//! **`order` is a `Vec` and not an `Option<Vec>`**, for the same reason: an interface's order is
//! completed with `(…, __ig_kind__, id)` whatever the client wrote, so *no order* and *the empty
//! order* are one state and a second spelling of it could only disagree with the first.
//!
//! A cursor is the STRING and it is forced rather than chosen, as a record's is: `Cursor<V>` is
//! parameterised by the cursor VALUE, which is per database, and this object is per interface. What
//! is named is what `Cursor::encode` produces and `Cursor::decode` reads.

use quote::quote;

use crate::{emit::leading, interface::InterfaceModel, method::Member, unit};

#[cfg(test)]
mod tests;

impl InterfaceModel {
  /// The wire query surface: `<I>Filter` and `<I>GraphqlInput`, under the projection's own
  /// condition — and, inside the binding gate, the two INPUT FACES a client actually writes.
  ///
  /// Under it rather than under a wire-face block of its own, because both types are written over
  /// the SHARED COLUMNS and the order-by: an interface that projects nothing has neither to be
  /// written over, and an interface about no SQL database has no lane for the arguments to mirror.
  pub(crate) fn wire(&self) -> proc_macro2::TokenStream {
    if !self.projects() {
      return quote!();
    }
    let filter = self.filter();
    let arguments = self.arguments();
    let faces = self.input_faces();
    quote! {
      #filter
      #arguments
      #faces
    }
  }

  /// The `InputType` impls the two written-by-a-client types wear, inside the BINDING GATE.
  ///
  /// # THE CONTRACT IS THE BOUNDARY — this is where D-5 becomes a schema
  ///
  /// The ruling, in the user's own words: *接口上 只能问接口里有的字段*. Read here it costs nothing
  /// to enforce, because there is nothing to enforce: the emitted `<I>Filter` and `<I>OrderBy` are
  /// written over the CONTRACT's own fields and hold no member-specific one, so the published input
  /// objects cannot carry a field the interface did not declare. A client naming a member's private
  /// column is refused by the VALIDATOR against the schema, before a resolver runs — statically
  /// absent rather than answered at run time, which is the same posture the computed tier's absence
  /// from the filter already takes.
  ///
  /// # Two RIDERS the ruling recorded, and neither builds anything
  ///
  /// A future demand for a per-member WHERE — a filter scoped to an inline fragment — is an
  /// ADDITIVE round of its own, so nothing here forecloses it and nothing here reserves a word for
  /// it. Per-member ORDER is refused STRUCTURALLY and for good: ordering a union by a column some
  /// arm lacks lands in NULL-placement dialect divergence, a total order no two dialects would
  /// agree on, which is the partition frame's semantics-disagree class one layer down.
  ///
  /// # The names are the FRAMEWORK's, and there is no rename tier to read
  ///
  /// A record's input faces resolve their SDL names through `wire_type`, which exists to carry a
  /// declared `filter(rename = "…")`. An interface's grammar has no such word, so `<I>Filter` and
  /// `<I>OrderBy` are what a client reads — the design's own SDL vocabulary, which is exactly the
  /// case `wire_type` calls its identity reading.
  ///
  /// Both faces come from [`unit::wire`](crate::unit::wire), the same emitter a record's do, so a
  /// byte of registry construction cannot differ between the two front ends.
  fn input_faces(&self) -> proc_macro2::TokenStream {
    let interface = &self.name;
    let gate = self.framework(&["gate"], "if_async_graphql");
    let filter_name = super::default_filter_name(interface);
    let order_name = super::default_order_by_name(interface);
    let filter_sdl = filter_name.to_string();
    let order_sdl = order_name.to_string();
    // The STORED tier on both faces, and the two lists are one walk apart for a reason the record
    // side already states: an order-by term and a filter field name ONE column at ONE schema
    // position, so a client never spells the same column two ways in one document.
    let fields: Vec<unit::wire::FilterField> = self
      .stored()
      .map(|field| unit::wire::FilterField {
        // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        field: crate::emit::wire::wire_member(&field.name),
        member: field.name.clone(),
        filter: self.filter_of(field),
      })
      .collect();
    let terms: Vec<unit::wire::OrderField> = self
      .stored()
      .map(|field| unit::wire::OrderField {
        // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        field: crate::emit::wire::wire_member(&field.name),
        variant: crate::emit::upper_camel(&field.name.to_string()),
        // An interface promises SHARED columns and has no field words of its own to withhold one
        // with: `graphql(skip)` is written on a MEMBER's field, and what a member does not publish
        // it cannot promise here either — that is the member's own refusal to make. So every term
        // an interface names is a term its schema names.
        published: true,
      })
      .collect();
    let filter = unit::wire::filter_face(
      &unit::wire::InputFace {
        krate: &self.krate,
        name: &filter_name,
        sdl: &filter_sdl,
      },
      &fields,
      // No relation positions: an interface's contract fields are columns, and its members' own
      // relations are theirs.
      &[],
    );
    let order = unit::wire::order_by_face(
      &unit::wire::InputFace {
        krate: &self.krate,
        name: &order_name,
        sdl: &order_sdl,
      },
      &terms,
    );
    quote! {
      #gate! {
        #filter
        #order
      }
    }
  }

  /// `<I>Filter` — the predicate a client writes, over the contract's stored fields.
  ///
  /// It is [`unit::filter`](crate::unit::filter)'s own walk and no longer a second copy of it. The
  /// struct, the outer `Option` per column and the builder pair are ONE emitter, shared with a
  /// record's filter and a standalone `#[derive(ingraph::Filter)]`; what an interface supplies is
  /// the rows and the two nouns — that each column is a SHARED one, and the paragraph a contract's
  /// filter carries where a record's has nothing to add.
  ///
  /// Each field carries its type's FILTER rather than its value, for the record filter's reason:
  /// `Option<value>` expresses equality alone, and on a nullable column it collapses three states —
  /// no predicate, `IS NULL`, `= v` — into two. The framework carries the null test on a
  /// `Nullable<F>` wrapper and registers `Option<T>` to it, so nullability needs no detection here
  /// and must get none.
  ///
  /// The outer `Option` is *did the client ask about this column at all*, and the crossing answers
  /// `None` with the empty comparison — which renders no conjunct, so an unwritten field narrows
  /// nothing.
  fn filter(&self) -> proc_macro2::TokenStream {
    let interface = &self.name;
    let rows: Vec<unit::FilterColumn> = self
      .stored()
      .map(|field| unit::FilterColumn {
        // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        member: field.name.clone(),
        name: format!("shared `{}` column", field.name),
        filter: self.filter_of(field),
      })
      .collect();
    let header = unit::UnitHeader {
      vis: &self.vis,
      name: super::default_filter_name(interface),
      subject: format!("[`{interface}`]"),
      note: Some(
        "One per interface where the page's own predicate is one per database: a client writes the \
         CONTRACT's names at the contract's types, and which database answers is a deployment's \
         business. A COMPUTED field is not here at all — it is derived from a member's wire output \
         and is a column nowhere."
          .to_owned(),
      ),
    };
    let (declaration, builders) = unit::filter(&header, &rows);
    quote! {
      #declaration
      #builders
    }
  }

  /// `<I>GraphqlInput` — a query's whole arguments, in the shape the interface's lane takes them.
  ///
  /// Construction is `Default` plus one `with_*` per member, with a borrow beside it — the shape
  /// the filter has, and for its reason: a client's arguments are BUILT, where an output object is
  /// minted by a conversion and sealed against anything else.
  ///
  /// What a flat object cannot mirror is the TYPESTATE — a bag with both `first` and `last` set is
  /// spellable here and refused by the builder, a GraphQL input object being flat by construction.
  /// That refusal belongs to the round that resolves these arguments into a call.
  fn arguments(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let interface = &self.name;
    let name = super::default_input_name(interface);
    let filter = super::default_filter_name(interface);
    let order_by = super::default_order_by_name(interface);

    let optional: Vec<(syn::Ident, proc_macro2::TokenStream, &str)> = vec![
      (
        quote::format_ident!("filter"),
        quote!(#filter),
        "The predicate this query is constrained by.",
      ),
      (
        quote::format_ident!("first"),
        quote!(::core::primitive::u32),
        "How many rows to take from the start of the order.",
      ),
      (
        quote::format_ident!("last"),
        quote!(::core::primitive::u32),
        "How many rows to take from the far end of the order.",
      ),
      (
        quote::format_ident!("after"),
        quote!(::std::string::String),
        "Resume after the row this cursor was minted at — the string `Cursor::encode` produced.",
      ),
      (
        quote::format_ident!("before"),
        quote!(::std::string::String),
        "Resume before the row this cursor was minted at — the string `Cursor::encode` produced.",
      ),
    ];

    let members = optional
      .iter()
      .map(|(member, ty, _)| quote!(#member: ::core::option::Option<#ty>,));
    let methods = optional.iter().map(|(member, ty, what)| {
      let with = Member::With.name(member);
      let borrow = Member::Borrow.name(member);
      let with_doc = leading(&format!("The same arguments with `{member}` given. {what}"));
      let borrow_doc = leading(&format!("`{member}`, where the client gave one. {what}"));
      quote! {
        #[doc = #with_doc]
        #[must_use]
        #[inline]
        #vis fn #with(mut self, #member: #ty) -> Self {
          self.#member = ::core::option::Option::Some(#member);
          self
        }

        #[doc = #borrow_doc]
        #[inline]
        #vis const fn #borrow(&self) -> ::core::option::Option<&#ty> {
          self.#member.as_ref()
        }
      }
    });

    let order = quote::format_ident!("order");
    let with_order = Member::With.name(&order);
    let order_slice = Member::Slice.name(&order);
    let order_doc = leading(
      "The same arguments with the order a client wrote — the terms in the sequence they run, \
       which is the one structure the GraphQL specification calls ordered.",
    );
    let slice_doc = leading(
      "The order as written, in the sequence its terms run. An EMPTY order is not a missing one: \
       an interface's order completes with `(…, __ig_kind__, id)` whatever the client wrote, so \
       the empty list is the page ordered by the tail alone.",
    );
    let doc = leading(&format!(
      "A query's arguments over the [`{interface}`]s a client asks for — the interface's own lane, \
       in the types a schema can name.\n\nThere is no ceiling and no skip: `InterfaceFind` offers \
       neither, an interface's order never being absent, and a member no method could spend is an \
       argument object promising a query the engine refuses."
    ));
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::default::Default)]
      #vis struct #name {
        order: ::std::vec::Vec<#order_by>,
        #(#members)*
      }

      impl #name {
        #[doc = #order_doc]
        #[must_use]
        #[inline]
        #vis fn #with_order(mut self, order: ::std::vec::Vec<#order_by>) -> Self {
          self.order = order;
          self
        }

        #[doc = #slice_doc]
        #[inline]
        #vis fn #order_slice(&self) -> &[#order_by] {
          &self.order
        }

        #(#methods)*
      }
    }
  }
}