ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the BINDING states, read off the tokens — one seat marker per seat, and one `const` block per
//! shared arm carrying both edges.
//!
//! Beside [`super::super::fuse::tests`] on this directory's one-file-per-thing precedent. What only a
//! REAL COMPILE can say — that a drifted tower is refused at the arm and that the message names the
//! answer type — is `ingraph/tests/tower_pin/`.

use super::super::{ArmModel, MemberModel, SearchModel, SeatModel, SharedBinding, SharedBridge};
use crate::index::Dedup;

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// The head's broadcast seat, typed as the LOCKED declaration types it.
fn seat(name: &str) -> SeatModel {
  SeatModel {
    name: ident(name),
    ty: syn::parse_quote!(::std::string::String),
  }
}

/// One arm, on whichever crossing a case hands it.
fn arm(name: &str, tower: &str, shared: Option<SharedBinding>) -> ArmModel {
  ArmModel {
    name: ident(name),
    tower: syn::parse_str(tower).expect("a tower type"),
    shared,
    floor: None,
  }
}

/// A member holding `arms`.
fn member(field: &str, arms: Vec<ArmModel>) -> MemberModel {
  MemberModel {
    field: ident(field),
    ty: syn::parse_quote!(Shots),
    weight: None,
    depth: None,
    floor: None,
    arms,
  }
}

/// A recipe over the seats and members a case hands it.
fn recipe(seats: Vec<SeatModel>, members: Vec<MemberModel>) -> SearchModel {
  SearchModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("TravelSearch"),
    seats,
    dedup: Dedup::Hash,
    limit: None,
    graphql: None,
    members,
  }
}

/// The bound half of the emission with its spaces taken out.
fn tight(model: &SearchModel) -> String {
  let mut whole = model.seat_markers();
  whole.extend(model.bindings());
  whole.to_string().split_whitespace().collect()
}

/// The crossing a `shared` arm reads.
fn total() -> Option<SharedBinding> {
  Some(SharedBinding {
    seat: ident("text"),
    bridge: SharedBridge::Total,
  })
}

/// **ONE MARKER PER DECLARED SEAT, PREFIXED BY THE RECIPE** — so two recipes over one member declare
/// two keys and their crossings cannot collide.
#[test]
fn every_seat_mints_a_marker_named_for_its_recipe() {
  let emitted = tight(&recipe(
    vec![seat("text"), seat("point")],
    vec![member("subs", Vec::new())],
  ));
  assert!(emitted.contains("structTravelSearchTextSeat;"), "{emitted}");
  assert!(
    emitted.contains("structTravelSearchPointSeat;"),
    "{emitted}"
  );
}

/// **A RECIPE THAT BROADCASTS NOTHING MINTS NO MARKER** — the presence law at the type the crossing is
/// keyed on.
#[test]
fn a_recipe_with_no_seat_mints_no_marker() {
  let emitted = tight(&recipe(Vec::new(), vec![member("subs", Vec::new())]));
  assert!(!emitted.contains("Seat;"), "{emitted}");
}

/// **THE ANSWER EDGE IS STATED PER SHARED ARM**, keyed on the seat's marker and asking the crossing OF
/// the member's own question — both halves projections, neither a name this emission mangled.
#[test]
fn a_shared_arm_demands_the_crossing_from_its_towers_answer() {
  let emitted = tight(&recipe(
    vec![seat("text")],
    vec![member(
      "shots",
      vec![arm("text", "crate::ClipText", total())],
    )],
  ));
  assert!(
    emitted.contains("fn__ingraph_a_bound_tower_answers_what_its_member_is_asked_with"),
    "{emitted}",
  );
  assert!(
    emitted.contains(
      "__IgAsked:::ingraph::__private::retrieve::TrySharedQuestion<TravelSearchTextSeat,__IgAnswer>"
    ),
    "{emitted}",
  );
  assert!(
    emitted.contains("<Shotsas::ingraph::__private::retrieve::Fusable>::Question"),
    "the member's question is named rather than projected: {emitted}",
  );
  assert!(
    emitted.contains("<crate::ClipTextas::ingraph::__private::retrieve::SearchTower>::Answer"),
    "the tower's answer is named rather than projected: {emitted}",
  );
}

/// **AN ARM THAT READS NO BROADCAST STATES NEITHER EDGE.** Without a seat there is nothing to cross
/// from, and the arm's own question is the question layer's to produce.
#[test]
fn an_unshared_arm_raises_no_obligation() {
  let emitted = tight(&recipe(
    vec![seat("text")],
    vec![member("shots", vec![arm("text", "crate::ClipText", None)])],
  ));
  assert!(
    !emitted.contains("__ingraph_a_bound_tower_answers"),
    "{emitted}",
  );
  // The marker still lands: it is the seat's own type and the head declared the seat.
  assert!(emitted.contains("structTravelSearchTextSeat;"), "{emitted}");
}

/// **A MEMBER THAT BINDS NO TOWER RAISES NOTHING**, which is the plain coordinate member.
#[test]
fn a_plain_member_raises_no_obligation() {
  let emitted = tight(&recipe(
    vec![seat("text")],
    vec![member("subs", Vec::new())],
  ));
  assert!(
    !emitted.contains("__ingraph_a_bound_tower_answers"),
    "{emitted}",
  );
}

/// **EACH OF THE FOUR WORDS STATES ITS OWN QUESTION EDGE** — two bounds and two coercions, and which
/// is which is a fact about what a bridge IS rather than a preference.
#[test]
fn the_four_crossings_each_state_their_own_bridge() {
  let hook: syn::Path = syn::parse_quote!(crate::widen);
  let table: [(SharedBridge, &str); 4] = [
    (
      SharedBridge::Total,
      "__ingraph_a_shared_arm_takes_the_seats_own_type",
    ),
    (
      SharedBridge::Fallible,
      "__ingraph_a_try_shared_arm_takes_the_seats_own_type",
    ),
    (SharedBridge::Hook(hook.clone()), "crate::widen"),
    (
      SharedBridge::FallibleHook(hook),
      "__ingraph_a_try_shared_hook_answers_the_towers_question",
    ),
  ];

  for (bridge, owed) in table {
    let word = bridge.word();
    let emitted = tight(&recipe(
      vec![seat("text")],
      vec![member(
        "shots",
        vec![arm(
          "text",
          "crate::ClipText",
          Some(SharedBinding {
            seat: ident("text"),
            bridge,
          }),
        )],
      )],
    ));
    assert!(
      emitted.contains(owed),
      "`{word}` lost its bridge: {emitted}"
    );
  }
}

/// **THE TWO TRAIT BRIDGES DEMAND THE TWO CONVERSIONS THE WORDS NAME**, and each is stated ABOUT the
/// tower's own `Question` rather than about the seat.
#[test]
fn the_trait_bridges_demand_the_conversions_their_words_name() {
  for (bridge, owed) in [
    (SharedBridge::Total, "::core::convert::From<__IgSeat>"),
    (SharedBridge::Fallible, "::core::convert::TryFrom<__IgSeat>"),
  ] {
    let emitted = tight(&recipe(
      vec![seat("text")],
      vec![member(
        "shots",
        vec![arm(
          "text",
          "crate::ClipText",
          Some(SharedBinding {
            seat: ident("text"),
            bridge,
          }),
        )],
      )],
    ));
    let owed = owed.replace(' ', "");
    assert!(emitted.contains(&owed), "{emitted}");
    assert!(
      emitted.contains(
        "<__IgToweras::ingraph::__private::retrieve::SearchTower>::Question:::core::convert"
      ),
      "the bound was stated about the wrong subject: {emitted}",
    );
  }
}

/// **A SHARED ARM WHOSE SEAT THE HEAD DOES NOT DECLARE STATES NOTHING**, rather than reaching for a
/// marker no declaration minted: the seat is refused at the front end, and this half is what keeps a
/// recipe that reached the emitter anyway from minting a dangling name.
#[test]
fn an_arm_naming_an_undeclared_seat_states_nothing() {
  let emitted = tight(&recipe(
    vec![seat("text")],
    vec![member(
      "shots",
      vec![arm(
        "image",
        "crate::ClipImage",
        Some(SharedBinding {
          seat: ident("absent"),
          bridge: SharedBridge::Total,
        }),
      )],
    )],
  ));
  // THE QUANTITY, and it is the assertion the two absences beneath it cannot make. *States nothing*
  // is about OBLIGATIONS and not about tokens: the head's own declared seat is still minted, so an
  // emptiness check would be false, and a pin on `AbsentSeat` alone stays true over an emitter that
  // had started minting something else entirely — that name is one nothing in this tree writes.
  // What is counted is the binding SPEND, which is `const _: fn() = …` once per obligation.
  assert!(
    emitted.contains("pubstructTravelSearchTextSeat"),
    "the emitter did not run at all, so the absences below say nothing: {emitted}",
  );
  assert_eq!(
    emitted.matches("const_:fn()=").count(),
    0,
    "an arm whose seat the head never declared spent a binding obligation: {emitted}",
  );
  assert!(!emitted.contains("AbsentSeat"), "{emitted}");
  assert!(
    !emitted.contains("__ingraph_a_bound_tower_answers"),
    "{emitted}",
  );
}