ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the ASSEMBLED FACE's expansion says, read off its tokens.
//!
//! Its BEHAVIOUR — that each tier runs, that a failure lands in the arm its declaration named, that
//! a wholly blocking node's face needs no runtime — is asserted where it can be run:
//! `ingraph/tests/mutation_face.rs`, which expands a declaration the way a declaring crate does and
//! CALLS the face. What is here is what a token stream can be read for: the two sums' arms, the OR
//! law's two outcomes, the parameter union, and the fact that there is exactly one call site per
//! exchange.

use super::super::tests::watch_ops;
use crate::mutation::{ExchangeModel, HandlerModel, MutationModel};

/// The emitted tokens with every space taken out.
fn tokens(model: &MutationModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

/// The rendered expansion, formatted — what a failing claim prints.
fn rendered(model: &MutationModel) -> String {
  prettyplease::unparse(&syn::parse2(model.emit()).expect("the expansion parses as a file"))
}

/// The same declaration with its ONE awaited handler made blocking — the OR law's other outcome.
fn wholly_blocking() -> MutationModel {
  let mut model = watch_ops();
  model.exchanges[0].handler.awaited = false;
  model
}

/// A node whose every exchange is the `Never` tier — the honest-empty error sum.
fn cannot_fail() -> MutationModel {
  MutationModel {
    exchanges: vec![ExchangeModel {
      field: syn::parse_quote!(reindex),
      ty: syn::parse_quote!((Reindex, ())),
      rename: None,
      handler: HandlerModel {
        path: syn::parse_quote!(crate::watch::reindex),
        awaited: false,
        context: Vec::new(),
        error: None,
      },
    }],
    ..watch_ops()
  }
}

/// A node whose two exchanges are granted the SAME resource, plus one granted another — the
/// parameter union, and the deduplication that makes it one list.
fn twice_granted() -> MutationModel {
  let mut model = watch_ops();
  model.exchanges[1].handler.context = vec![syn::parse_quote!(crate::Catalog)];
  model.exchanges[2].handler.context = vec![syn::parse_quote!(crate::watch::Ledger)];
  model
}

/// THE NAMES, all three derived from the node's own and none of them declarable.
#[test]
fn every_assembled_name_is_derived_from_the_nodes() {
  let model = watch_ops();
  assert_eq!(model.response_name(), "WatchOpsResponse");
  assert_eq!(model.error_name(), "WatchOpsError");
  assert_eq!(model.face_name(), "handle_watch_ops");
}

/// THE OR LAW, both ways: one awaited handler makes the whole face awaited, and a node whose every
/// handler is blocking assembles into a function no runtime is needed to call.
#[test]
fn the_face_is_the_or_of_its_handlers() {
  let awaited = watch_ops();
  assert!(awaited.awaited(), "one awaited handler");
  assert!(
    tokens(&awaited).contains("pubasyncfnhandle_watch_ops("),
    "{}",
    rendered(&awaited)
  );

  let blocking = wholly_blocking();
  assert!(blocking.all_sync(), "every handler blocking");
  assert!(
    tokens(&blocking).contains("pubfnhandle_watch_ops("),
    "{}",
    rendered(&blocking)
  );
  assert!(
    !tokens(&blocking).contains("asyncfnhandle_watch_ops"),
    "{}",
    rendered(&blocking)
  );
}

/// The OR law reaches the RECORD and the FACE from one reading, so the two cannot come to disagree.
#[test]
fn the_records_all_sync_and_the_faces_mode_are_one_fact() {
  for model in [watch_ops(), wholly_blocking(), cannot_fail()] {
    assert_eq!(
      model.all_sync(),
      !model.awaited(),
      "one reading, two spellings"
    );
    let emitted = tokens(&model);
    let stated = format!("constALL_SYNC:bool={};", model.all_sync());
    assert!(emitted.contains(&stated), "{}", rendered(&model));
  }
}

/// THE RESPONSE SUM: one arm per exchange, each carrying that exchange's own `Response` projection.
#[test]
fn the_response_sum_has_one_arm_per_exchange() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(emitted.contains("pubenumWatchOpsResponse{"), "{emitted}");
  for (variant, ty) in [
    ("Add", "(AddWatch,AddResponse)"),
    ("Remove", "(RemoveWatch,RemoveResponse)"),
    ("Reindex", "(Reindex,())"),
  ] {
    assert!(
      emitted.contains(&format!(
        "{variant}(<{ty}as::ingraph::__private::source::Mutation>::Response)"
      )),
      "{variant}: {}",
      rendered(&model)
    );
  }
}

/// BOTH SUMS DEBUG PAYLOAD-BLIND, which is what keeps them free of a bound on anybody's types.
#[test]
fn both_sums_debug_their_arm_and_never_its_payload() {
  let model = watch_ops();
  let emitted = tokens(&model);
  for sum in ["WatchOpsResponse", "WatchOpsError"] {
    assert!(
      emitted.contains(&format!("impl::core::fmt::Debugfor{sum}{{")),
      "{sum}: {}",
      rendered(&model)
    );
  }
  assert!(
    emitted.contains("Self::Add(_)=>::core::fmt::Formatter::write_str(__ingraph_f,\"Add\")"),
    "{}",
    rendered(&model)
  );
}

/// THE ERROR SUM: an arm per FALLIBLE exchange, the rich one carrying its declared type and the
/// canned one carrying nothing — and the `Never` tier contributing no arm at all.
#[test]
fn the_error_sum_carries_the_rich_type_and_nothing_for_a_canned_failure() {
  let model = watch_ops();
  let emitted = tokens(&model);
  let sum = emitted
    .split_once("pubenumWatchOpsError{")
    .expect("the error sum")
    .1
    .split_once('}')
    .expect("its arms")
    .0;
  assert!(sum.contains("Add(crate::AddWatchError)"), "{sum}");
  assert!(sum.contains("Remove"), "{sum}");
  assert!(
    !sum.contains("Reindex"),
    "an exchange that cannot fail contributes no way to fail: {sum}"
  );
}

/// A NODE THAT CANNOT FAIL gets an error sum with no variants — the honest empty, matched through
/// the place because there is no value to match.
#[test]
fn a_node_that_cannot_fail_gets_an_uninhabited_error() {
  let model = cannot_fail();
  let emitted = tokens(&model);
  assert!(emitted.contains("pubenumWatchOpsError{}"), "{emitted}");
  // Three readings over an uninhabited sum, and every one of them is the compiler's own proof.
  assert_eq!(
    emitted.matches("match*self{}").count(),
    3,
    "{}",
    rendered(&model)
  );
}

/// THE ONE-CODE-HEAD LAW at the sum's own `Display`: the declared heading, then the failure's words.
#[test]
fn the_error_sum_renders_under_the_heading_its_declaration_wrote() {
  let model = watch_ops();
  let emitted = tokens(&model);
  // RICH — the heading is written and the value renders itself, which is what the wire does too.
  // The lens takes every space out, the ones INSIDE a literal included, so `"ADD_FAILED: "` reads
  // back without its own trailing space — which is why the claim is spelled the way it is.
  assert!(
    emitted.contains(
      "Self::Add(__ingraph_refusal)=>{::core::fmt::Formatter::write_str(__ingraph_f,\"ADD_FAILED:\
       \")?;::core::fmt::Display::fmt(__ingraph_refusal,__ingraph_f)}"
    ),
    "{}",
    rendered(&model)
  );
  // CANNED — one literal, because nothing at runtime can vary it.
  assert!(
    emitted.contains(
      "Self::Remove=>::core::fmt::Formatter::write_str(__ingraph_f,\"NOT_OURS:thatwatchisnotours\")"
    ),
    "{}",
    rendered(&model)
  );
}

/// A failure's declared HEADING is readable off the value, which is what a caller mapping this sum
/// onto a transport's own vocabulary needs.
#[test]
fn the_error_sum_answers_the_code_its_declaration_wrote() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pubconstfncode(&self)->::core::option::Option<&'staticstr>"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("Self::Add(_)=>::core::option::Option::Some(\"ADD_FAILED\")"),
    "{}",
    rendered(&model)
  );
}

/// ONE CALL SITE PER EXCHANGE, and the wire spends the same one — so a handler that does not wear
/// its declared signature is refused once rather than once per face.
#[test]
fn one_call_is_emitted_per_exchange_and_both_faces_spend_it() {
  let model = watch_ops();
  let emitted = tokens(&model);
  for (call, tier) in [
    (
      "__ingraph_exchange_add",
      "->::core::result::Result<<(AddWatch,AddResponse)as::ingraph::__private::source::Mutation>::\
       Response,crate::AddWatchError>",
    ),
    (
      "__ingraph_exchange_remove",
      "->::core::result::Result<<(RemoveWatch,RemoveResponse)as::ingraph::__private::source::\
       Mutation>::Response,()>",
    ),
    (
      "__ingraph_exchange_reindex",
      "-><(Reindex,())as::ingraph::__private::source::Mutation>::Response",
    ),
  ] {
    // DEFINED once …
    assert_eq!(
      emitted.matches(&format!("fn{call}(")).count(),
      1,
      "{call}: {}",
      rendered(&model)
    );
    assert!(emitted.contains(tier), "{call}: {}", rendered(&model));
    // … and CALLED twice, under the two spellings the two callers reach it by: the assembled
    // face's arm is INSIDE `impl WatchOps`, so it says `Self::`, and the wire's resolver is inside
    // the unit's own `#[Object]` impl, so it names the node.
    assert_eq!(
      emitted.matches(&format!("Self::{call}(")).count(),
      1,
      "{call}: {}",
      rendered(&model)
    );
    assert_eq!(
      emitted.matches(&format!("WatchOps::{call}(")).count(),
      1,
      "{call}: {}",
      rendered(&model)
    );
  }
  // The HANDLER itself is named in exactly one place per exchange — the call above — so there is
  // one site at which a declared signature is cast.
  for handler in [
    "crate::watch::add(",
    "crate::watch::remove(",
    "crate::watch::reindex(",
  ] {
    assert_eq!(
      emitted.matches(handler).count(),
      1,
      "{handler}: {}",
      rendered(&model)
    );
  }
}

/// A NODE WITH NO WIRE WORD still gets its whole assembled face — the face is the node's Rust
/// surface and the schema is the binding's.
#[test]
fn the_face_is_emitted_without_any_wire_word() {
  let model = MutationModel {
    graphql: Vec::new(),
    ..watch_ops()
  };
  let emitted = tokens(&model);
  assert!(emitted.contains("pubasyncfnhandle_watch_ops("), "{emitted}");
  assert!(!emitted.contains("async_graphql"), "{emitted}");
  // The face's own call stands, and the wire has no resolver to spend the other.
  assert_eq!(emitted.matches("Self::__ingraph_exchange_add(").count(), 1);
  assert_eq!(
    emitted.matches("WatchOps::__ingraph_exchange_add(").count(),
    0
  );
}

/// THE PARAMETER UNION: one face runs every exchange, so it is handed what they were granted
/// between them — deduplicated by the path that named it, in first-written order.
#[test]
fn the_face_takes_the_union_of_what_its_exchanges_were_granted() {
  let model = twice_granted();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "pubasyncfnhandle_watch_ops(catalog:&crate::Catalog,ledger:&crate::watch::Ledger,\
       __ingraph_cmd:WatchOpsCommand,)"
    ),
    "{}",
    rendered(&model)
  );
}

/// A node granted NOTHING takes the command alone — the union of no grants is no parameters.
#[test]
fn an_ungranted_node_takes_the_command_alone() {
  let model = cannot_fail();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pubfnhandle_watch_ops(__ingraph_cmd:WatchOpsCommand,)"),
    "{}",
    rendered(&model)
  );
}

/// THE ARMS: each command variant answers with the same-named response arm, and a failure lands in
/// the same-named error arm.
#[test]
fn each_command_arm_answers_and_refuses_under_its_own_name() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "WatchOpsCommand::Add(__ingraph_request)=>matchSelf::__ingraph_exchange_add(catalog,\
       __ingraph_request).await{"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("::core::result::Result::Ok(WatchOpsResponse::Add(__ingraph_answer))"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("::core::result::Result::Err(WatchOpsError::Add(__ingraph_refusal))"),
    "{}",
    rendered(&model)
  );
  // The CANNED arm reads its `Err(())` for the POSITION it is, and carries no value onward.
  assert!(
    emitted.contains(
      "::core::result::Result::Err(())=>::core::result::Result::Err(WatchOpsError::Remove)"
    ),
    "{}",
    rendered(&model)
  );
  // The NEVER arm has no `Result` to match at all.
  assert!(
    emitted.contains(
      "WatchOpsCommand::Reindex(__ingraph_request)=>::core::result::Result::Ok(WatchOpsResponse::\
       Reindex(Self::__ingraph_exchange_reindex(__ingraph_request)))"
    ),
    "{}",
    rendered(&model)
  );
}

/// A RENAMED crate moves every framework path the face names.
#[test]
fn a_renamed_crate_moves_the_faces_paths() {
  let model = MutationModel {
    krate: syn::parse_quote!(other::ingraph),
    graphql: Vec::new(),
    ..watch_ops()
  };
  let emitted = tokens(&model);
  assert_eq!(
    emitted.matches("::ingraph::__private").count(),
    emitted.matches("other::ingraph::__private").count(),
    "{emitted}"
  );
}