ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the mutation declaration's expansion says, read off its tokens.
//!
//! The expansion's BEHAVIOUR is asserted where it can be run — `ingraph-derive`'s own fixtures,
//! which expand a declaration for real and reach the emitted items through it. What is here is what
//! a token stream can be read for: that each of the three items is emitted, that the record says
//! what the declaration said, and that every framework path they name goes through the shelf.

use super::{DeclaredError, ExchangeModel, HandlerModel, MutationModel};

/// The declaration the whole grammar fits in, as the derive builds one.
///
/// `pub(super)` so the WIRE suite beside this one spends the same declaration: the two read
/// different halves of one expansion, and a second fixture would let the halves drift apart.
pub(super) fn watch_ops() -> MutationModel {
  MutationModel {
    krate: syn::parse_quote!(::ingraph),
    name: syn::parse_quote!(WatchOps),
    vis: syn::parse_quote!(pub),
    graphql: vec![crate::model::GraphqlKind::AsyncGraphql],
    exchanges: vec![
      ExchangeModel {
        field: syn::parse_quote!(add),
        ty: syn::parse_quote!((AddWatch, AddResponse)),
        rename: Some(syn::parse_quote!("addWatch")),
        handler: HandlerModel {
          path: syn::parse_quote!(crate::watch::add),
          awaited: true,
          context: vec![syn::parse_quote!(crate::Catalog)],
          error: Some(DeclaredError::Rich {
            ty: syn::parse_quote!(crate::AddWatchError),
            code: Some(syn::parse_quote!("ADD_FAILED")),
          }),
        },
      },
      ExchangeModel {
        field: syn::parse_quote!(remove),
        ty: syn::parse_quote!((RemoveWatch, RemoveResponse)),
        rename: None,
        handler: HandlerModel {
          path: syn::parse_quote!(crate::watch::remove),
          awaited: false,
          context: Vec::new(),
          error: Some(DeclaredError::Canned {
            message: syn::parse_quote!("that watch is not ours"),
            code: Some(syn::parse_quote!("NOT_OURS")),
          }),
        },
      },
      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,
        },
      },
    ],
  }
}

/// The rendered expansion with every space taken out — what a claim about a PATH or a call is read
/// off, for the resource emitter's reason: a path long enough to wrap arrives with newlines inside
/// its own turbofish.
fn compact(model: &MutationModel) -> String {
  rendered(model).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 EMITTED TOKENS with every space taken out, bypassing the formatter.
///
/// [`compact`] reads what a person would see, which is the right lens for a claim about an item's
/// SHAPE. It is the wrong one for a claim about a type: `prettyplease` breaks a long generic across
/// lines and adds a trailing comma inside it, so `(RemoveWatch, RemoveResponse)` reads back with a
/// comma that the emission never wrote and a differently-named field would move.
fn tokens(model: &MutationModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

/// THE VOCABULARY: one arm per field, named after the field, carrying that exchange's request.
#[test]
fn the_command_enum_has_one_arm_per_exchange() {
  let model = watch_ops();
  let emitted = tokens(&model);

  assert!(
    emitted.contains("pubenumWatchOpsCommand"),
    "{}",
    rendered(&model)
  );
  for (variant, ty) in [
    ("Add", "(AddWatch,AddResponse)"),
    ("Remove", "(RemoveWatch,RemoveResponse)"),
    ("Reindex", "(Reindex,())"),
  ] {
    let arm = format!("{variant}(<{ty}as::ingraph::__private::source::Mutation>::Request)");
    assert!(
      emitted.contains(&arm),
      "the `{variant}` arm: {}",
      rendered(&model)
    );
  }
}

/// The payload is a PROJECTION, which is what makes the emission its own assert: a field whose type
/// is not an exchange is `E0277` at the field rather than a resolution failure inside a resolver
/// nobody has written yet.
#[test]
fn the_arms_payload_is_the_projection_and_never_a_written_type() {
  let model = watch_ops();
  // The VOCABULARY's own tokens, taken out of the expansion rather than read off the whole of it:
  // the wire face spells the same projection at every resolver's argument, so a count over the
  // expansion would be counting two claims at once.
  let file: syn::File = syn::parse2(model.emit()).expect("the expansion parses as a file");
  let command = file
    .items
    .iter()
    .find_map(|item| match item {
      syn::Item::Enum(command) => Some(command),
      _ => None,
    })
    .expect("the command vocabulary");
  let arms: String = quote::quote!(#command)
    .to_string()
    .split_whitespace()
    .collect();

  assert!(
    !arms.contains("Add(AddWatch)"),
    "the request type is never written directly: {}",
    rendered(&model)
  );
  assert_eq!(
    arms
      .matches("as::ingraph::__private::source::Mutation>::Request")
      .count(),
    3,
    "one projection per field: {}",
    rendered(&model)
  );
}

/// THE ROW a source's `Mutation` seat resolves through.
#[test]
fn the_node_row_hands_the_vocabulary_to_a_source() {
  let model = watch_ops();
  assert!(
    compact(&model).contains(
      "impl::ingraph::__private::source::MutationNodeforWatchOps{typeCommand=WatchOpsCommand;}"
    ),
    "{}",
    rendered(&model)
  );
}

/// THE RECORD: one row per exchange, each carrying only the words its declaration wrote.
#[test]
fn the_record_says_what_the_declaration_said() {
  let model = watch_ops();
  let emitted = compact(&model);

  assert!(
    emitted.contains("impl::ingraph::__private::source::DeclaredMutationforWatchOps"),
    "{}",
    rendered(&model)
  );
  // One awaited handler, so the node is not all-blocking.
  assert!(
    emitted.contains("constALL_SYNC:bool=false;"),
    "{}",
    rendered(&model)
  );

  // The full row: every word written, every builder called.
  assert!(
    emitted.contains(
      "::ingraph::__private::source::Exchange::of(\"add\",\"crate::watch::add\")\
       .renamed(\"addWatch\")\
       .awaited()\
       .granting(&[\"crate::Catalog\"])\
       .failing(\
       ::ingraph::__private::source::Fallibility::Rich{\
       named:\"crate::AddWatchError\",\
       code:::core::option::Option::Some(\"ADD_FAILED\"),\
       })"
    ),
    "{}",
    rendered(&model)
  );

  // The canned row: no rename, no face, no grant — and the sentence carried whole.
  assert!(
    emitted.contains(
      "::ingraph::__private::source::Exchange::of(\"remove\",\"crate::watch::remove\")\
       .failing(\
       ::ingraph::__private::source::Fallibility::Canned{\
       message:\"thatwatchisnotours\",\
       code:::core::option::Option::Some(\"NOT_OURS\"),\
       })"
    ),
    "{}",
    rendered(&model)
  );
}

/// A word the declaration did not write earns no builder call, so the record cannot claim one.
#[test]
fn an_unwritten_word_leaves_no_call_behind() {
  let model = watch_ops();
  let emitted = compact(&model);

  assert!(
    emitted.contains(
      "::ingraph::__private::source::Exchange::of(\"reindex\",\"crate::watch::reindex\"),"
    ),
    "the plain exchange is the bare constructor and nothing else: {}",
    rendered(&model)
  );
  assert_eq!(
    emitted.matches(".renamed(").count(),
    1,
    "one field wrote a rename: {}",
    rendered(&model)
  );
  assert_eq!(
    emitted.matches(".awaited()").count(),
    1,
    "one field wrote the face word: {}",
    rendered(&model)
  );
  assert_eq!(
    emitted.matches(".granting(").count(),
    1,
    "one field wrote a context: {}",
    rendered(&model)
  );
  assert_eq!(
    emitted.matches(".failing(").count(),
    2,
    "two fields can fail: {}",
    rendered(&model)
  );
}

/// The OR law's own const: a node whose every handler is blocking says so.
#[test]
fn a_node_of_blocking_handlers_is_all_sync() {
  let mut model = watch_ops();
  model.exchanges[0].handler.awaited = false;
  assert!(model.all_sync());
  assert!(compact(&model).contains("constALL_SYNC:bool=true;"));
}

/// The record's `code` seat is an option and is emitted as one either way, so a reader never has to
/// tell an absent heading from an empty one.
#[test]
fn a_failure_with_no_code_says_none_rather_than_nothing() {
  let mut model = watch_ops();
  model.exchanges[1].handler.error = Some(DeclaredError::Canned {
    message: syn::parse_quote!("that watch is not ours"),
    code: None,
  });
  assert!(
    compact(&model).contains("code:::core::option::Option::None,"),
    "{}",
    rendered(&model)
  );
}

/// EVERY framework path goes through the shelf, so a declaring crate needs no `use` and a rename of
/// this crate's own modules cannot reach a declarer's namespace.
#[test]
fn every_framework_path_goes_through_the_shelf() {
  let model = watch_ops();
  let emitted = compact(&model);
  for named in [
    "Mutation",
    "MutationNode",
    "DeclaredMutation",
    "Exchange",
    "Fallibility",
  ] {
    assert!(
      !emitted.contains(&format!("::ingraph::{named}")),
      "`{named}` is reached through `__private`: {}",
      rendered(&model)
    );
  }
}

/// The crate path is the DECLARATION's, so a shim re-export moves every name at once.
#[test]
fn a_renamed_crate_moves_every_path() {
  let mut model = watch_ops();
  model.krate = syn::parse_quote!(crate::shim);
  let emitted = compact(&model);
  assert!(!emitted.contains("::ingraph::"), "{}", rendered(&model));
  assert!(
    emitted.contains("crate::shim::__private::source::MutationNode"),
    "{}",
    rendered(&model)
  );
}

/// The command enum wears the DECLARATION's visibility: a node a caller can name has commands that
/// caller can build.
#[test]
fn the_vocabulary_is_as_visible_as_the_node() {
  let mut model = watch_ops();
  model.vis = syn::parse_quote!(pub(crate));
  assert!(
    compact(&model).contains("pub(crate)enumWatchOpsCommand"),
    "{}",
    rendered(&model)
  );
}

/// A field legally called `r#type` is `type` in the record and `Type` in the vocabulary — the unraw
/// law, which every other name in this crate already obeys.
#[test]
fn a_raw_field_name_is_unrawed_in_both_places() {
  let mut model = watch_ops();
  model.exchanges[2].field = syn::parse_quote!(r#type);
  let emitted = compact(&model);
  assert!(emitted.contains("Type(<"), "{}", rendered(&model));
  assert!(
    emitted.contains("Exchange::of(\"type\","),
    "{}",
    rendered(&model)
  );
}

/// A snake-cased field becomes ONE camel arm rather than a word with an underscore in it.
#[test]
fn a_multiword_field_names_one_arm() {
  let mut model = watch_ops();
  model.exchanges[2].field = syn::parse_quote!(rebuild_index);
  assert!(
    compact(&model).contains("RebuildIndex(<"),
    "{}",
    rendered(&model)
  );
}

/// THE TOP-LEVEL IMPLS, named rather than counted: the vocabulary's row, the record, the assembled
/// face and the two sums' own faces — which together are the whole of the declaration side, however
/// the node is dressed for the wire.
///
/// The wire face is an `impl` too and it is not one of these — it lives inside the binding gate's
/// own anonymous `const`, where a build without async-graphql discards it whole. The suite beside
/// this one reads that half; what is asserted here is that it stayed over there.
#[test]
fn the_declaration_side_is_the_nodes_rust_surface_and_the_wire_stays_in_the_gate() {
  let model = watch_ops();
  let rendered = rendered(&model);
  let tops: Vec<&str> = rendered
    .lines()
    .filter(|line| line.starts_with("impl "))
    .collect();
  assert_eq!(
    tops,
    vec![
      "impl ::ingraph::__private::source::MutationNode for WatchOps {",
      "impl ::ingraph::__private::source::DeclaredMutation for WatchOps {",
      "impl ::core::fmt::Debug for WatchOpsResponse {",
      "impl ::core::fmt::Display for WatchOpsError {",
      "impl ::core::fmt::Debug for WatchOpsError {",
      "impl ::core::error::Error for WatchOpsError {}",
      "impl WatchOpsError {",
      "impl WatchOps {",
      "impl WatchOps {",
    ],
    "{rendered}"
  );
  // The `#[Object]` face is NOT at the top level — it is indented inside the gate's `const`, which
  // is what a build with no binding discards whole.
  assert!(!rendered.contains("Resolver"), "{rendered}");
  let gate = rendered
    .find("if_async_graphql!")
    .expect("the binding gate");
  // Read through the SPACELESS lens: the gate's body is a macro invocation, so the formatter wraps
  // its raw tokens wherever the line ran out rather than at the item's own shape.
  let gated: String = rendered[gate..].split_whitespace().collect();
  assert!(gated.contains("implWatchOpsMutations{"), "{rendered}");
}