ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The GraphQL face's acceptance, 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 `graphql_enum` suite for the two front ends' agreement, and `ingraph`'s
//! `tests/wire_schema.rs` for the SDL a client actually reads.

use std::collections::BTreeMap;

use quote::ToTokens as _;

use crate::enumeration::{EnumModel, EnumVariant, Namespace};

/// The vocabulary this module is measured against: one variant whose wire word is RENAMED, one
/// taking the default casing, and one whose Rust spelling is a raw identifier.
fn codec() -> EnumModel {
  EnumModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("Codec"),
    width: None,
    variants: vec![renamed("Vp9", "VP_9"), variant("H264"), variant("r#Tape")],
    forms: BTreeMap::new(),
    wire_name: None,
    error: None,
    remote: None,
  }
}

fn variant(name: &str) -> EnumVariant {
  EnumVariant {
    ident: ident(name),
    rename: None,
    names: BTreeMap::new(),
    upstream: None,
    escape: None,
    carrier: None,
  }
}

fn renamed(name: &str, wire: &str) -> EnumVariant {
  let mut names = BTreeMap::new();
  names.insert(Namespace::Graphql, wire.to_owned());
  EnumVariant {
    ident: ident(name),
    rename: None,
    names,
    upstream: None,
    escape: None,
    carrier: None,
  }
}

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

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

/// The face read back as items.
fn face(model: &EnumModel) -> syn::File {
  syn::parse2(model.graphql_face()).expect("the face parses")
}

/// **THE FACE RIDES THE BINDING GATE AND NOTHING ELSE.**
///
/// A build of `ingraph` with no `async-graphql` compiles a declaration carrying this derive to
/// nothing at all — 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_face_is_behind_the_binding_gate() {
  let file = face(&codec());
  let syn::Item::Const(anonymous) = file.items.first().expect("the face is one anonymous const")
  else {
    panic!("the face is one anonymous const");
  };
  assert_eq!(anonymous.ident, "_");
  assert_eq!(file.items.len(), 1, "and nothing stands beside it");

  let rendered = rendered(&codec());
  assert!(
    rendered.contains("__private :: gate :: if_async_graphql"),
    "{rendered}"
  );
  // ONE gate, so no impl escaped it.
  assert_eq!(
    rendered.matches("if_async_graphql").count(),
    1,
    "{rendered}"
  );
}

/// **The wire SHOUTS by default, and a rename is the escape.**
///
/// `SCREAMING_SNAKE_CASE` is GraphQL's own convention for enum values, and it comes from
/// [`Namespace::default_name`] — the same function `as_graphql_str` is written from, which is what
/// makes the two faces one table rather than two rules that agree today.
#[test]
fn the_values_shout_and_a_rename_moves_one() {
  let rendered = rendered(&codec());
  for word in ["\"VP_9\"", "\"H264\"", "\"TAPE\""] {
    assert!(rendered.contains(word), "`{word}` is missing:\n{rendered}");
  }
  assert!(
    !rendered.contains("\"VP9\""),
    "the rename did not move the value:\n{rendered}"
  );
  assert!(
    !rendered.contains("\"r#Tape\""),
    "the raw escape is Rust's and no part of the name:\n{rendered}"
  );
}

/// **The TYPE's schema name is the enum's own, unraw'd** where the declaration moved nothing — the
/// default `graphql(rename = "…")` overrides, and the `r#` a raw enum carries is Rust's escape rather
/// than part of the name.
#[test]
fn the_type_publishes_the_enums_own_name() {
  let mut model = codec();
  model.name = ident("r#Match");
  let rendered = rendered(&model);
  assert!(rendered.contains("\"Match\""), "{rendered}");
  assert!(!rendered.contains("\"r#Match\""), "{rendered}");
}

/// **NO PROSE REACHES THE SCHEMA**, on the type or on any value.
///
/// `description: None` is a FACT of this emission rather than a hope about what a derive lifted:
/// async-graphql's own derives call `get_rustdoc` unconditionally with no key to decline it, so a
/// derived face publishes whatever a declaration happened to document. Nothing here is derived.
///
/// The count is exact — one for the type, one per value — so a `description` that ever became
/// anything else reds this rather than passing an emptiness check.
#[test]
fn every_description_is_none() {
  let rendered = rendered(&codec());
  assert_eq!(
    rendered
      .matches("description : :: core :: option :: Option :: None")
      .count(),
    4,
    "one for the type and one for each of the three values:\n{rendered}"
  );
  assert!(
    !rendered.contains("get_rustdoc") && !rendered.contains("doc ="),
    "{rendered}"
  );
}

/// **The face carries NO async-graphql attribute**, which is what keeps `emit::wire`'s BUILD PIN
/// satisfied without spending its `crate = "…"` key: the impls are hand-written and every
/// async-graphql NAME in them is already rooted through the shelf, so there is no derive expanding
/// into paths of its own.
#[test]
fn the_face_carries_no_backend_attribute() {
  let attributes: Vec<String> = face(&codec())
    .into_token_stream()
    .to_string()
    .split("# [")
    .skip(1)
    .filter_map(|tail| tail.split(']').next().map(str::to_owned))
    .collect();
  assert!(
    attributes
      .iter()
      .all(|attribute| attribute == "automatically_derived" || attribute == "inline"),
    "{attributes:?}"
  );
}

/// **Every framework name is reached through `__private`**, which is the one way emitted code may
/// reach one — the rule the whole emitter obeys, checked here over the face's own tokens.
#[test]
fn every_framework_path_goes_through_the_shelf() {
  let rendered = rendered(&codec());
  assert!(
    !rendered.contains(":: async_graphql :: async_graphql"),
    "{rendered}"
  );
  assert_eq!(
    rendered.matches(":: async_graphql").count(),
    rendered
      .matches(":: ingraph :: __private :: async_graphql")
      .count(),
    "an async-graphql name escaped the shelf:\n{rendered}"
  );
}

/// **The face rides in [`EnumModel::emit`], WHOLLY INSIDE THE GATE** — which is what makes the one
/// door safe for a vocabulary declared for storage and never exposed.
///
/// That enum is the common case, and what keeps it out of somebody's SDL is REACHABILITY rather than
/// a second word: a schema is walked from its roots, so a face nothing names is a face nothing
/// renders. What the gate decides is narrower and is checked here — a build without the binding
/// compiles the whole face to nothing.
#[test]
fn the_face_rides_the_one_emission_inside_the_gate() {
  let emitted = codec().emit().to_string();
  assert!(emitted.contains("if_async_graphql"), "{emitted}");

  let (before, gated) = emitted
    .split_once("if_async_graphql")
    .expect("the gate is in the emission");
  for face in ["InputType", "EnumItem"] {
    assert!(gated.contains(face), "`{face}` is missing:\n{emitted}");
    assert!(
      !before.contains(face),
      "`{face}` escaped the gate:\n{emitted}"
    );
  }
}

/// **The crate path is the model's**, so a declaration reaching `ingraph` through a shim gets a face
/// rooted there — the same `crate = "…"` escape every other emission spends.
#[test]
fn the_shelf_follows_the_declared_crate() {
  let mut model = codec();
  model.krate = syn::parse_quote!(crate::shim);
  let rendered = rendered(&model);
  assert!(
    rendered.contains("crate :: shim :: __private :: async_graphql"),
    "{rendered}"
  );
  assert!(!rendered.contains(":: ingraph :: __private"), "{rendered}");
}

/// **THE OUTPUT LEG IS THERE**, which is the block W3's fork table named the decisive row: a record
/// exposing a vocabulary column could carry no output object while this impl was missing, and every
/// wire face past it sat behind that one row.
///
/// The `async fn` body is the ROAD, and it is what the ruling asked be tried first: async-graphql's
/// own default resolves `resolve` as an RPITIT method, which an `async fn` impl satisfies exactly.
#[test]
fn the_output_leg_is_emitted_as_an_async_fn() {
  let rendered = rendered(&codec());
  assert!(
    rendered.contains(":: async_graphql :: OutputType"),
    "{rendered}"
  );
  assert!(
    rendered.contains("async fn resolve"),
    "the output leg takes the RPITIT road:\n{rendered}"
  );
  assert!(
    rendered.contains(":: async_graphql :: resolver_utils :: enum_value"),
    "the value a resolver renders comes off the same table the parse reads:\n{rendered}"
  );
}

/// **ONE registry entry, whichever position names the type.**
///
/// The output face's two head methods DELEGATE to the input face rather than restating it. A GraphQL
/// enum is one type in one registry, so a second `create_type_info` here would be a second entry
/// able to disagree with the first about the values it publishes — and it is what async-graphql's
/// own `Enum` derive does too, where both faces call one `__create_type_info`.
#[test]
fn the_output_face_registers_through_the_input_one() {
  let rendered = rendered(&codec());
  assert_eq!(
    rendered.matches("create_input_type").count(),
    1,
    "one registration, reached from both positions:\n{rendered}"
  );
  assert_eq!(
    rendered.matches("MetaTypeId :: Enum").count(),
    1,
    "{rendered}"
  );
}

/// **THE OUTPUT CROSSING'S ONE ROW**, which is what makes a declared vocabulary RETURNABLE from an
/// emitted wire face rather than merely renderable by a hand-written one.
///
/// A vocabulary crosses as ITSELF, so the row is the identity — and it is a BORROW, which is what
/// keeps a column of words free of a copy per response.
///
/// **The second row is GONE, and its absence is pinned here beside the first.** It stood on an
/// element-keyed output trait, and that trait is retired: a `Vec<Codec>` reaches a wire face through
/// the collection rows the output map writes over `ListMarker`/`SetMarker`, reading the fork off the
/// `DefaultVecMarker` row the reading emission mints beside the filter's — one fact, one place, both
/// positions. [`the_vec_reading_is_emitted_so_a_collection_of_the_vocabulary_has_one`] is the other
/// half of the pair.
#[test]
fn the_output_crossing_is_emitted_for_the_value() {
  let rendered = rendered(&codec());
  assert!(
    rendered.contains(":: graphql :: ToGraphqlOutput for Codec"),
    "the value's row:\n{rendered}"
  );
  assert!(
    !rendered.contains("VecToGraphqlOutput"),
    "the retired element-keyed trait is named nowhere:\n{rendered}"
  );
  assert!(
    rendered.contains("type Output < '__ingraph > = & '__ingraph Self"),
    "a vocabulary crosses as itself, by reference:\n{rendered}"
  );
  assert!(
    !rendered.contains("type Output < '__ingraph > = & '__ingraph [Self]"),
    "and nothing here states what a collection of them crosses as:\n{rendered}"
  );
}