ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The union's two schema faces, over models built BY HAND.
//!
//! No declaration is parsed here, for the reason [`crate::tests`] states: the split that lets a
//! front end other than a derive reach this emitter only exists while the emitter can be driven
//! from a plain model. What a real declaration produces is pinned where a real declaration exists —
//! `ingraph-derive`'s union grammar suite for the two halves' agreement, and `ingraph`'s
//! `tests/union_faces.rs` for the SDL a client actually reads.

use crate::{
  model::GraphqlKind,
  union::{UnionInput, UnionMember, UnionModel, UnionOutput, UnionSkin},
};

/// The union this module is measured against: three members, the last of them over a type nobody
/// declared and the middle one a RAW identifier, so nothing here can quietly depend on a member
/// being a bare path or a variant on being an ordinary word.
fn found(graphql: Vec<UnionSkin>) -> UnionModel {
  UnionModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("Found"),
    members: vec![
      member("Media", syn::parse_quote!(Media)),
      member("r#Tape", syn::parse_quote!(media::Tape)),
      member("VideoClip", syn::parse_quote!(Vec<u8>)),
    ],
    error: None,
    graphql,
  }
}

fn member(name: &str, ty: syn::Type) -> UnionMember {
  UnionMember {
    ident: ident(name),
    ty,
  }
}

fn ident(name: &str) -> syn::Ident {
  syn::parse_str(name).expect("an identifier")
}

/// A backend dressed for whichever positions a case names.
fn skin(output: bool, input: Option<UnionInput>) -> UnionSkin {
  UnionSkin {
    kind: GraphqlKind::AsyncGraphql,
    output: output.then(UnionOutput::default),
    input,
  }
}

/// `input(rename = "…")`, as the model holds it.
fn renamed(word: &str) -> UnionInput {
  UnionInput {
    rename: Some(syn::parse_quote!(#word)),
  }
}

/// The wire half as one string, so a claim about it can be a substring.
fn rendered(model: &UnionModel) -> String {
  model.graphql_faces().to_string()
}

/// **A UNION THAT NAMES NO BACKEND EMITS NO WIRE HALF AT ALL.**
///
/// Not an empty gate block and not a `cfg` that expands to nothing — nothing, so the whole emission
/// of a declaration that wrote no `graphql(…)` is the method face it always was.
#[test]
fn a_union_with_no_backend_emits_nothing() {
  assert!(rendered(&found(Vec::new())).is_empty());
}

/// **THE WHOLE FACE RIDES THE BINDING GATE**, both positions and the marker with them.
///
/// A build of `ingraph` with no `async-graphql` compiles a declaration carrying this derive down to
/// its method face — which is what a gate IS, and what a `#[cfg(feature = "async-graphql")]` written
/// inside an expansion could not be: such a `cfg` asks whether the DECLARING crate has a feature by
/// that name, which is a different manifest and usually no feature at all.
#[test]
fn the_whole_wire_half_is_behind_the_binding_gate() {
  let model = found(vec![skin(true, Some(UnionInput::default()))]);
  let file: syn::File = syn::parse2(model.graphql_faces()).expect("the face parses");
  let syn::Item::Const(anonymous) = file.items.first().expect("one anonymous const per backend")
  else {
    panic!("the face is an anonymous const");
  };
  assert_eq!(anonymous.ident, "_");

  let rendered = rendered(&model);
  assert_eq!(
    rendered.matches("if_async_graphql").count(),
    1,
    "one gate, wrapping the block's whole body: {rendered}"
  );
  assert!(
    rendered.contains(":: ingraph :: __private :: gate :: if_async_graphql"),
    "and it is reached through the shelf: {rendered}"
  );
}

/// **EVERY async-graphql NAME IS REACHED THROUGH THE SHELF, and no ATTRIBUTE is emitted.**
///
/// The #157 build pin, held locally: a DECLARING crate never needs async-graphql in its own
/// manifest, so a bare `::async_graphql::…` would not resolve there. An emitted ATTRIBUTE would need
/// a `crate = "…"` key beside the shelf path — a derive expands into paths of its own — and this
/// emission writes none: both faces are hand-written impls carrying `#[automatically_derived]`.
#[test]
fn every_library_name_is_shelved_and_no_attribute_is_written() {
  let rendered = rendered(&found(vec![skin(true, Some(UnionInput::default()))]));

  assert!(
    !rendered.contains(":: async_graphql")
      || rendered.contains(":: ingraph :: __private :: async_graphql"),
    "{rendered}"
  );
  assert_eq!(
    rendered.matches(":: async_graphql").count(),
    rendered
      .matches(":: ingraph :: __private :: async_graphql")
      .count(),
    "every mention of the library is the shelved one: {rendered}"
  );
  assert!(
    !rendered.contains("# [:: ingraph :: __private :: async_graphql"),
    "no async-graphql attribute is emitted, so none can be missing its `crate` key: {rendered}"
  );
}

/// **ONE FACE TAKES THE UNION'S OWN NAME, WHICHEVER FACE IT IS.**
///
/// A schema has one namespace for type names and a single face has nothing to collide with, so the
/// output-only union and the input-only union both publish `Found`.
#[test]
fn a_single_face_publishes_the_unions_own_name() {
  let output = skin(true, None);
  assert_eq!(output.output_sdl(&ident("Found")), "Found");

  let input = skin(false, Some(UnionInput::default()));
  assert_eq!(input.input_sdl(&ident("Found")), "Found");

  let rendered = rendered(&found(vec![input]));
  assert!(rendered.contains(r#"Borrowed ("Found")"#), "{rendered}");
  assert!(!rendered.contains("FoundInput"), "{rendered}");
}

/// **DUAL EMISSION: the OUTPUT keeps the union's own name and the INPUT derives `<Union>Input`.**
///
/// The two faces are impls on ONE Rust type, so the schema needs two names for them — and the
/// output's is the one a client writes in a selection set, which is why it is the one that does not
/// move.
#[test]
fn both_faces_split_the_name_between_them() {
  let both = skin(true, Some(UnionInput::default()));
  assert_eq!(both.output_sdl(&ident("Found")), "Found");
  assert_eq!(both.input_sdl(&ident("Found")), "FoundInput");

  let rendered = rendered(&found(vec![both]));
  assert!(rendered.contains(r#"Borrowed ("Found")"#), "{rendered}");
  assert!(
    rendered.contains(r#"Borrowed ("FoundInput")"#),
    "{rendered}"
  );
  assert!(rendered.contains(r#"MetaType :: Union"#), "{rendered}");
  assert!(
    rendered.contains(r#"MetaType :: InputObject"#),
    "{rendered}"
  );
}

/// **The rename moves the INPUT's name at either arity** — a scope that already publishes a
/// `<Union>Input` needs the escape exactly as much as one that simply prefers another word.
#[test]
fn the_rename_moves_the_input_name_whether_or_not_the_output_is_rendered() {
  assert_eq!(
    skin(true, Some(renamed("FoundChoice"))).input_sdl(&ident("Found")),
    "FoundChoice"
  );
  assert_eq!(
    skin(false, Some(renamed("FoundChoice"))).input_sdl(&ident("Found")),
    "FoundChoice"
  );

  let rendered = rendered(&found(vec![skin(true, Some(renamed("FoundChoice")))]));
  assert!(
    rendered.contains(r#"Borrowed ("FoundChoice")"#),
    "{rendered}"
  );
  assert!(!rendered.contains("FoundInput"), "{rendered}");
}

/// **The union's own name leaves Rust unraw'd**, at both faces — the `r#` is Rust's escape for a
/// word that collides with its grammar and no part of the name.
#[test]
fn a_raw_union_publishes_the_word_without_its_escape() {
  let mut model = found(vec![skin(true, Some(UnionInput::default()))]);
  model.name = ident("r#type");
  let both = &model.graphql[0];

  assert_eq!(both.output_sdl(&model.name), "type");
  assert_eq!(both.input_sdl(&model.name), "typeInput");
  assert!(
    !rendered(&model).contains("r#type\""),
    "{}",
    rendered(&model)
  );
}

/// **ONE NULLABLE SEAT PER MEMBER, named in lower camel case off the variant's own spelling** — and
/// `oneof: true`, which is what publishes the directive.
///
/// The words are async-graphql's own `OneofObject` default, spelled here because no derive of that
/// library's is reachable from a door that may only append.
#[test]
fn the_input_face_seats_every_member_under_its_own_camel_word() {
  let rendered = rendered(&found(vec![skin(false, Some(UnionInput::default()))]));

  for word in ["media", "tape", "videoClip"] {
    assert_eq!(
      rendered.matches(&format!(r#""{word}""#)).count(),
      // The registry entry names it twice — the key and the value's own `name` — the parse asks for
      // it and then takes it, and the render writes it.
      5,
      "`{word}` is the seat, its registry name, its two reads and its write: {rendered}"
    );
  }
  assert!(rendered.contains("oneof : true"), "{rendered}");
  assert!(
    rendered.contains("OneofObjectType for Found"),
    "the marker beside `InputType`, which is what a `@oneOf` carries: {rendered}"
  );
}

/// **EVERY SEAT IS ASKED FOR THROUGH THE MARKER, and the marker carries this framework's sentence.**
///
/// A member with no input face is named ONCE, at its own token: the three sites the face names a
/// member at are all spanned at the member's type and all report the same message, and rustc emits
/// a diagnostic identical in message and span once. `do_not_recommend` is what keeps the message
/// this crate's — without it the report descends through the blanket impl and names `InputType`,
/// which is true and is not what the framework wants to say.
#[test]
fn the_input_seats_are_reached_through_a_marker_that_names_the_refusal() {
  let rendered = rendered(&found(vec![skin(true, Some(UnionInput::default()))]));

  assert!(
    rendered.contains("diagnostic :: on_unimplemented"),
    "{rendered}"
  );
  assert!(
    rendered.contains("diagnostic :: do_not_recommend"),
    "{rendered}"
  );
  assert!(
    rendered.contains("is a member of `Found`, which declares a GraphQL INPUT face"),
    "the sentence names the union: {rendered}"
  );
  assert_eq!(
    rendered.matches("__IngraphSeat").count(),
    // The trait, the blanket impl, and three mentions per member.
    2 + 3 * 3,
    "every member mention goes through the marker: {rendered}"
  );
  for member in ["Media", "media :: Tape", "Vec < u8 >"] {
    assert!(
      !rendered.contains(&format!(
        "< {member} as :: ingraph :: __private :: async_graphql :: InputType >"
      )),
      "no member is named beside the library's own trait, or the refusal would be its sentence \
       rather than this framework's: {rendered}"
    );
  }
}

/// **THE MARKER EXISTS ONLY WHERE THE INPUT FACE DOES.** An output-only union asks nothing of a
/// member but the output face it is being rendered through.
#[test]
fn an_output_only_union_declares_no_seat_marker() {
  let rendered = rendered(&found(vec![skin(true, None)]));

  assert!(!rendered.contains("__IngraphSeat"), "{rendered}");
  assert!(!rendered.contains("InputType"), "{rendered}");
  assert!(rendered.contains("UnionType for Found"), "{rendered}");
}

/// **THE OUTPUT FACE DELEGATES TO THE MEMBER, in all three places a union has to.**
///
/// The selection set is collected against the member the value is holding, the introspection name is
/// the member's own, and every member's type is registered so a schema walked from this one reaches
/// the arms.
#[test]
fn the_output_face_answers_every_question_off_the_member() {
  let rendered = rendered(&found(vec![skin(true, None)]));

  assert!(
    rendered.contains("ContainerType :: collect_all_fields (__ingraph_arm"),
    "{rendered}"
  );
  assert_eq!(
    rendered.matches("OutputType > :: type_name ()").count(),
    // One arm apiece for the introspection name, and one apiece for the possible-type set.
    3 * 2,
    "{rendered}"
  );
  assert_eq!(
    rendered.matches("OutputType > :: create_type_info").count(),
    3,
    "every arm is registered, so a schema reaching the union reaches its members: {rendered}"
  );
}