ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The OPEN VOCABULARY a crate DECLARES: what `#[derive(ingraph::Enum)]` expands into when a
//! variant wears `#[ingraph(other)]` and no `remote = "…"` names an upstream.
//!
//! ```ignore
//! #[derive(Clone, PartialEq, Eq, Hash, ingraph::Enum)]
//! pub enum BodyJoint {
//!   Nose,
//!   LeftShoulder,
//!   RightShoulder,
//!   #[ingraph(other)]
//!   Other(ingraph::Utf8Bytes),
//! }
//! ```
//!
//! # It is the FOURTH cell, and it is not a knob
//!
//! There is no `vocabulary`, no `open` and no `escape` word. Two structural facts pick the mode —
//! whether a `remote` is named, and whether a variant is marked — and this module is the cell where
//! the answer is *no upstream, and an escape*. What that combination MEANS is what the other three
//! cells could not say:
//!
//! - a **closed vocabulary this crate declares** owns its words and its variants ARE the set, so a
//!   word outside it is a refusal;
//! - a **mirror** has an upstream that owns every word, so its openness is a claim about somebody
//!   else's type and the compiler settles it;
//! - **this** owns its words AND admits it does not own all of them. The roster is read out of a
//!   vendor's documentation, a protobuf, a model card — somewhere with no Rust value behind it — so
//!   there is nothing for an openness claim to be spent against and nothing to delegate a word to.
//!
//! # What follows from having no upstream
//!
//! **The escape's two GATED postures are unavailable**, and the refusal for one says so at the
//! declaration: `other(from = "…")` and `other(try_from = "…")` name a function turning a word into
//! an UPSTREAM value, and there is none. So the posture is [`Escape::Total`](super::Escape::Total),
//! the door is total, `FromStr::Err` is [`Infallible`](core::convert::Infallible), and no refusal
//! type is declared beside the enum.
//!
//! **The words are read through the FOLD**, which is the half a closed vocabulary has no need of. A
//! closed set publishes its members in an SDL `enum` and a client writes one of them back; an open
//! one publishes a SCALAR and meets its words as text, in whichever spelling a producer uses — so
//! the door folds ASCII case and the three separators before it compares. The relation is
//! `ingraph`'s own `name::folds_to`, NAMED by the emitted door rather than copied into it — one
//! definition workspace-wide, so two vocabularies cannot come to disagree about what a word is.
//!
//! **The stored form is the WORD, in every face**, exactly as a mirror's is and for a reason one
//! grain over: the escape has no discriminant to be a number of. A face block naming a form is
//! refused at the declaration for that reason.
//!
//! # What it emits
//!
//! | item | shared with |
//! |---|---|
//! | `EnumFilterMarker`, `DefaultMarker`, `DefaultVecMarker` | both other modes |
//! | `VARIANTS` — the roster, escape excluded | the mirror |
//! | `new`, `as_str` | neither: this is the fold's door |
//! | `is_<variant>`, the escape's included | the mirror |
//! | `Display`, and `FromStr` at `Infallible` | neither |
//! | `CursorValue`, over the canonical word | the mirror's cursor, parameterised |
//! | `DelegatesId`, over the CARRIER | both other modes, the closed one at `Utf8Bytes` |
//! | `ColumnKind`, `Assemble` | both other modes |
//! | `sqlx::Type`, `Encode`, `Decode`, `Carrier`, at TEXT | the mirror's storage, parameterised |
//! | a custom SCALAR, plus the two crossings | the mirror's unpromoted wire face, verbatim |
//!
//! What it does NOT emit is as load-bearing: no refusal type (the door is total), no per-face
//! accessor or `TryFrom<&…Name>` (there is one word, not one per face), no `From`/`remote()` pair
//! (there is no upstream), and no `Debug` — the declaration derives that, and what it prints is the
//! declaration's business.
//!
//! # The ESCAPE carries a FOLDED word, and that is what makes `Eq` mean something
//!
//! Two producers writing `left_paw_extra` and `leftPawExtra` for a word this roster does not name
//! are ONE value: the door folds before it builds the escape, so the two compare equal and hash into
//! one bucket. A roster that carried the arriving spelling would have an escape whose equality was
//! about typography.
//!
//! The CARRIER is read off the marked variant's own field type. The door builds one through
//! [`From<&str>`](From) and reads one through [`AsRef<str>`](AsRef), so any text carrier satisfying
//! that pair holds a word — `Utf8Bytes` and `SmolStr` among them — and a type satisfying neither is
//! the compiler's refusal at the field the declaration wrote.
//!
//! Exactly ONE row NAMES the carrier's type rather than reaching it through those two traits: the key
//! delegation, whose `Inner` IS the carrier — see
//! [`open_key_delegation`](EnumModel::open_key_delegation). That is why the model records the
//! payload's token at all, and it is also what puts the refusal at the FIELD: the door's own
//! conversions are reported at the derive, and the key row spends the same conversion under a named
//! obligation whose span is the payload the declaration wrote.

use quote::quote;

use super::{DatabaseKind, EnumModel, EnumVariant};

#[cfg(test)]
mod tests;

impl EnumModel {
  /// The whole expansion for an OPEN vocabulary this crate declares.
  ///
  /// One anonymous `const` and the wire face beside it, which is the shape both other modes take.
  /// There is no third item: a refusal type stands outside the block only where a parse can produce
  /// one, and this door cannot.
  pub(super) fn emit_open(&self, escape: &EnumVariant) -> proc_macro2::TokenStream {
    let markers = self.markers();
    let face = self.open_face(escape);
    let parsing = self.open_parsing();
    let cursor = self.open_cursor();
    let key = self.key_delegation();
    let width = self.width_row();
    let read = self.read_row();
    let storage = DatabaseKind::ALL
      .into_iter()
      .map(|database| self.open_storage(database));
    let wire = self.scalar_wire();
    quote! {
      const _: () = {
        #markers
        #face
        #parsing
        #cursor
        #key
        #width
        #read
        #(#storage)*
      };

      #wire
    }
  }

  /// The ROSTER, the DOOR, the word, and the predicates.
  ///
  /// `VARIANTS` lists the named members alone. The escape carries a runtime word, so it is no
  /// constant — and the list's whole job is to say what a client may ask for, which a word meaning
  /// *something else* is not.
  ///
  /// # `new` tries every member BEFORE it builds an escape
  ///
  /// A word this roster names has to reach the variant that names it, or nothing would round-trip:
  /// every value would come back as an escape carrying the word it went out as, comparing unequal to
  /// the member it means. So the door is a walk of the roster under the fold, in DECLARATION order,
  /// and the escape is what is left.
  ///
  /// The walk is linear and that is the measured shape rather than a placeholder: the fold is a
  /// comparison rather than a normalisation, so there is no key to look a word up by without
  /// materialising one — which is an allocation on the path a match is supposed to avoid.
  ///
  /// # `as_str` hands back a BORROW, where a closed vocabulary's hands back a `&'static str`
  ///
  /// The named arms are static words; the escape's is the carrier's own, which lives as long as the
  /// value does. One signature covers both, and it is the weaker one.
  fn open_face(&self, escape: &EnumVariant) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = &self.name;
    let escaped = &escape.ident;
    let folds_to = self.framework(&["name"], "folds_to");
    let folded = self.framework(&["name"], "folded");

    let roster = self.restated().map(|variant| {
      let ident = &variant.ident;
      quote!(Self::#ident)
    });
    let doors = self.restated().map(|variant| {
      let ident = &variant.ident;
      let word = variant.folded();
      quote! {
        if #folds_to(__ingraph_word, #word) {
          return Self::#ident;
        }
      }
    });
    let words = self.restated().map(|variant| {
      let ident = &variant.ident;
      let word = variant.folded();
      quote!(Self::#ident => #word,)
    });
    let predicates = self.variants.iter().map(|variant| self.predicate(variant));

    let roster_doc = format!(
      "Every word [`{name}`] NAMES, in declaration order.\n\nThe escape is absent: it carries a \
       word rather than a name, so it is no constant. This is the list a client reads to learn what \
       it may ask for, and a word meaning *something else* is not one of them."
    );
    let door_doc = format!(
      "Read a word in ANY spelling.\n\nTOTAL — there is no refusal, a word this roster does not \
       name riding [`{name}::{escaped}`] with its FOLDED spelling. ASCII case and `_`, `-` and a \
       space are ignored, so `leftShoulder`, `left_shoulder`, `LEFT-SHOULDER` and `Left Shoulder` \
       are one value."
    );
    let word_doc = format!(
      "This value's CANONICAL word — what a column holds, a cursor carries and a client \
       reads.\n\nFor a named member it is the declaration's own spelling; for [`{name}::{escaped}`] \
       it is the folded word that variant carries."
    );

    quote! {
      #[automatically_derived]
      impl #name {
        #[doc = #roster_doc]
        #vis const VARIANTS: &'static [Self] = &[#(#roster),*];

        #[doc = #door_doc]
        #[must_use]
        #vis fn new(__ingraph_word: &::core::primitive::str) -> Self {
          #(#doors)*

          Self::#escaped(::core::convert::Into::into(
            ::std::string::String::as_str(&#folded(__ingraph_word)),
          ))
        }

        #[doc = #word_doc]
        #[must_use]
        #vis fn as_str(&self) -> &::core::primitive::str {
          match self {
            #(#words)*
            Self::#escaped(__ingraph_word) => {
              ::core::convert::AsRef::<::core::primitive::str>::as_ref(__ingraph_word)
            }
          }
        }

        #(#predicates)*
      }
    }
  }

  /// The RENDERING and the PARSE, both this vocabulary's own.
  ///
  /// [`Display`](core::fmt::Display) writes the canonical word and nothing around it, and
  /// [`FromStr`](core::str::FromStr) is the door — which is what makes its `Err`
  /// [`Infallible`](core::convert::Infallible). That is not a convenience: OPEN means exactly that a
  /// word this vocabulary does not know becomes its escape rather than a refusal, so there is
  /// nothing for an error type to carry and no refusal type to declare.
  fn open_parsing(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    quote! {
      #[automatically_derived]
      impl ::core::fmt::Display for #name {
        #[inline]
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          ::core::fmt::Formatter::write_str(f, #name::as_str(self))
        }
      }

      #[automatically_derived]
      impl ::core::str::FromStr for #name {
        type Err = ::core::convert::Infallible;

        #[inline]
        fn from_str(
          text: &::core::primitive::str,
        ) -> ::core::result::Result<Self, Self::Err> {
          ::core::result::Result::Ok(#name::new(text))
        }
      }
    }
  }

  /// The keyset cursor, over the canonical word — the shared codec, with this mode's two ends.
  ///
  /// The read goes back through the DOOR, and the door being total a forged position is a value
  /// rather than a refusal. That costs a page nothing: a cursor naming no member names no row
  /// either.
  fn open_cursor(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    self.word_cursor(
      &quote!(::core::primitive::str::as_bytes(#name::as_str(self))),
      &quote!(::core::option::Option::Some(#name::new(text))),
    )
  }

  /// One backend's storage rows — the shared TEXT emission, with this mode's two ends.
  ///
  /// The decode CANONICALISES, and here that is load-bearing rather than defensive: a row written by
  /// another program, or by a producer whose spelling this crate had not yet met, reads back as the
  /// member it names. A value bound out is already canonical, so a row this crate wrote reads back
  /// byte for byte.
  fn open_storage(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
    let name = &self.name;
    self.text_storage(
      database,
      &quote!(::std::string::String::from(#name::as_str(self))),
      &quote!(::core::option::Option::Some(#name::new(stored))),
    )
  }
}