ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! **THE BINDING, PROVEN** — the two obligations a `tower(… , shared)` arm raises, and the seat
//! markers the crossings are keyed on.
//!
//! ```text
//!   shared(text(type = "String"))            ┌── <ClipText as SearchTower>::Question: From<String>
//!   tower(text(type = "crate::ClipText",  ───┤       shared seat ↔ arm
//!               shared))                     └── <Shots as Fusable>::Question:
//!                                                   TrySharedQuestion<…TextSeat, <ClipText as SearchTower>::Answer>
//!                                                    binding ↔ member
//! ```
//!
//! # These are the theorem net's two edges at this grain, and neither was spellable before
//!
//! *shared seat ↔ arm* and *binding ↔ member* are edges of the compile-time net the retrieval
//! assembly is proven connected by. A recipe is the FIRST declaration that can state either: the seat
//! type and the tower path are both written in its own tokens, and the member's question is a
//! projection off `Fusable`. So the two land here, one `const` block per arm, spanned at the word the
//! author would have to change.
//!
//! # WHY THE ANSWER EDGE IS A CROSSING RATHER THAN AN EQUALITY
//!
//! The net's own phrasing is *tower `Answer` == member coordinates*. A recipe cannot write the second
//! half of that equality: a member's coordinate type lives inside the member's own election, behind
//! the two-clock wall, and the most a recipe holds is `<M as Fusable>::Question` — the whole question
//! PACKAGE, not one election's coordinates. What is expressible, and what says the same thing, is
//! that the member's question can be built FROM what the tower answers. So the edge is
//! [`TrySharedQuestion`]'s, with the tower's `Answer` in the broadcast position, and it moves from
//! `E0271` to `E0277`: the message names the answer type that arrived and the crossing that is
//! missing, where an equality would also have named the type expected.
//!
//! That is a real narrowing and it is recorded rather than hidden. The tower's own `answer = "…"` head
//! word is what still states the expected type as an equality, at the tower — so a drift is caught at
//! both ends, and only one of the two ends can name both types.
//!
//! # THE SEAT MARKERS ARE UNGATED and are minted for every recipe with a seat
//!
//! One unit struct per declared seat, whatever the recipe's backend word said: the crossings above are
//! Rust obligations rather than wire ones, and the wire road spends the same markers. A recipe with no
//! `shared(…)` mints none, which is the presence law.
//!
//! [`TrySharedQuestion`]: https://docs.rs/ingraph

use heck::ToUpperCamelCase as _;
use quote::{format_ident, quote, quote_spanned};

use super::{ArmModel, MemberModel, SearchModel, SharedBridge};
use crate::emit::{framework, leading, respan};

#[cfg(test)]
mod tests;

impl SearchModel {
  /// `<Recipe><Seat>Seat` — the marker one broadcast seat is keyed by.
  ///
  /// Prefixed with the recipe, because two recipes may declare a seat of one name over one member and
  /// the crossings must not collide: a marker shared between them would make *which recipe's
  /// broadcast this is* unstatable, which is the same reason the marker exists at all.
  pub(super) fn seat_marker_name(&self, seat: &syn::Ident) -> syn::Ident {
    format_ident!(
      "{}{}Seat",
      self.name,
      seat.to_string().to_upper_camel_case()
    )
  }

  /// ONE UNIT STRUCT PER DECLARED SEAT — the type a crossing is keyed on and nobody holds a value of.
  pub(super) fn seat_markers(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let recipe = &self.name;
    let minted = self.seats.iter().map(|seat| {
      let name = self.seat_marker_name(&seat.name);
      let ty = &seat.ty;
      let doc = leading(&format!(
        "[`{recipe}`]'s `{seat}` broadcast seat, as a type.\n\nThe key a crossing into one member's \
         question is written under — `SharedQuestion<{name}, …>` — and never a value: what a caller \
         fills is the seat's own type, which this declaration says is \
         `{spelled}`.",
        seat = seat.name,
        spelled = quote!(#ty),
      ));
      quote! {
        #[doc = #doc]
        #[derive(
          ::core::fmt::Debug,
          ::core::clone::Clone,
          ::core::marker::Copy,
          ::core::cmp::PartialEq,
          ::core::cmp::Eq,
          ::core::hash::Hash,
        )]
        #vis struct #name;
      }
    });
    quote!(#(#minted)*)
  }

  /// EVERY BOUND ARM'S OBLIGATIONS — nothing at all for a recipe whose members bind no tower, or
  /// whose arms read no broadcast.
  pub(super) fn bindings(&self) -> proc_macro2::TokenStream {
    let stated = self
      .members
      .iter()
      .flat_map(|member| member.arms.iter().map(move |arm| (member, arm)))
      .filter_map(|(member, arm)| self.binding(member, arm));
    quote!(#(#stated)*)
  }

  /// ONE ARM's two obligations.
  ///
  /// [`None`] for an arm that reads no broadcast: without a seat there is no crossing to demand and no
  /// bridge to check, and the arm's own question is the question layer's to produce.
  fn binding(&self, member: &MemberModel, arm: &ArmModel) -> Option<proc_macro2::TokenStream> {
    use syn::spanned::Spanned as _;

    let shared = arm.shared.as_ref()?;
    let seat = self
      .seats
      .iter()
      .find(|declared| declared.name == shared.seat)?;
    let krate = &self.krate;
    let tower_face = framework(krate, &["retrieve"], "SearchTower");
    let crossing = framework(krate, &["retrieve"], "TrySharedQuestion");
    let fusable = framework(krate, &["retrieve"], "Fusable");
    let marker = self.seat_marker_name(&seat.name);
    let seat_ty = &seat.ty;
    let tower = &arm.tower;
    let member_ty = &member.ty;
    let at = arm.tower.span();

    // THE ANSWER EDGE — the member's question is buildable from what this tower answers.
    //
    // The HELPER's name is half the diagnostic and is written as a sentence for the tower head pin's
    // reason: a bound has an `on_unimplemented` note but no place to say what JOIN was being checked,
    // and the identifier in the *required by a bound in …* line is the only place this one can.
    let answers = format_ident!("__ingraph_a_bound_tower_answers_what_its_member_is_asked_with");
    let asked = respan(quote!(<#member_ty as #fusable>::Question), at);
    let answer = respan(quote!(<#tower as #tower_face>::Answer), at);
    let spend = quote_spanned!(at=> const _: fn() = #answers::<#asked, #answer>;);

    // THE QUESTION EDGE — the seat's own type reaches this tower's question, across the bridge the
    // word chose. Four shapes, and the two hooks are checked by COERCING the author's function to the
    // signature the crossing needs: a path is an item and a bound cannot be written about one.
    let bridged = match &shared.bridge {
      SharedBridge::Total => {
        let total = format_ident!("__ingraph_a_shared_arm_takes_the_seats_own_type");
        let spend = quote_spanned!(at=> const _: fn() = #total::<#tower, #seat_ty>;);
        quote! {
          fn #total<__IgTower, __IgSeat>()
          where
            __IgTower: #tower_face,
            <__IgTower as #tower_face>::Question: ::core::convert::From<__IgSeat>,
          {
          }

          #spend
        }
      }
      SharedBridge::Fallible => {
        let fallible = format_ident!("__ingraph_a_try_shared_arm_takes_the_seats_own_type");
        let spend = quote_spanned!(at=> const _: fn() = #fallible::<#tower, #seat_ty>;);
        quote! {
          fn #fallible<__IgTower, __IgSeat>()
          where
            __IgTower: #tower_face,
            <__IgTower as #tower_face>::Question: ::core::convert::TryFrom<__IgSeat>,
          {
          }

          #spend
        }
      }
      SharedBridge::Hook(path) => {
        // AN ASCRIPTION rather than a helper, and the difference is what a hook IS: the two trait
        // bridges are bounds and a bound is written about a type, where a hook is an ITEM. So the
        // check is the coercion the author's function has to survive, and its refusal is `E0308` at
        // the word naming both signatures.
        let question = respan(quote!(<#tower as #tower_face>::Question), at);
        quote_spanned! {at=>
          const _: fn() = || {
            let _: fn(&#seat_ty) -> #question = #path;
          };
        }
      }
      SharedBridge::FallibleHook(path) => {
        let hook = format_ident!("__ingraph_a_try_shared_hook_answers_the_towers_question");
        let question = respan(quote!(<#tower as #tower_face>::Question), at);
        let spend = quote_spanned! {at=>
          const _: fn() = || #hook::<#seat_ty, #question, _>(#path);
        };
        quote! {
          // THE ERROR TYPE IS FREE, which is why this one is a call rather than an ascription: a
          // fallible hook refuses with whatever its author chose, and the crossing asks only that
          // the ANSWER be the tower's question.
          fn #hook<__IgSeat, __IgQuestion, __IgError>(
            _hook: fn(&__IgSeat) -> ::core::result::Result<__IgQuestion, __IgError>,
          ) {
          }

          #spend
        }
      }
    };

    Some(quote! {
      const _: () = {
        fn #answers<__IgAsked, __IgAnswer>()
        where
          __IgAsked: #crossing<#marker, __IgAnswer>,
        {
        }

        #spend

        #bridged
      };
    })
  }
}