ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The ELEMENT MODE's emission, read as TOKENS — the claims a compiled schema cannot make.
//!
//! `ingraph`'s own `tests/element_mode.rs` is where a minted filter reaches a real schema and
//! filters a real query, which is the claim that matters most and the one only a separate crate can
//! make. What is left for this file is what a compiling expansion says nothing about: that every
//! framework name goes through the SHELF rather than through a direct path, that the wire half sits
//! behind the binding GATE, and that the minted type takes the DECLARATION's visibility rather than
//! a fixed `pub`.

use quote::quote;

use super::{ElementFamily, ElementModel};

/// Tokens with their spacing removed, so a comparison is about content rather than layout.
fn tight(tokens: impl quote::ToTokens) -> String {
  tokens.to_token_stream().to_string().replace(' ', "")
}

/// One element, as the front end would have handed it over.
fn model(family: ElementFamily, subject: &str, inner: syn::Type) -> ElementModel {
  let subject = syn::Ident::new(subject, proc_macro2::Span::call_site());
  ElementModel {
    vis: syn::parse_quote!(pub),
    filter: crate::name::RustSafeName::from_ident(&crate::model::default_filter_name(&subject)),
    krate: syn::parse_quote!(::ingraph),
    family,
    member: syn::Member::Unnamed(syn::Index {
      index: 0,
      span: proc_macro2::Span::call_site(),
    }),
    inner,
    subject,
    wire_name: None,
  }
}

/// A text element, the case every claim below is stated on unless a family is the subject.
fn tag() -> ElementModel {
  model(ElementFamily::String, "Tag", syn::parse_quote!(String))
}

/// **EVERY FRAMEWORK NAME GOES THROUGH THE SHELF.**
///
/// An expansion lands in the DECLARING crate, so a direct `::ingraph::TextFilter` would name the
/// crate's public surface rather than the shelf the framework promises expansions — and the shelf is
/// what lets an item move without regenerating anyone's expansion. Asserted as an ABSENCE, because
/// the positive form would be a list to keep in step with the emission.
#[test]
fn no_emitted_path_reaches_the_framework_without_the_shelf() {
  let rendered = tight(tag().emit());
  assert!(rendered.contains("::ingraph::__private::graphql::TextFilter"));

  // The shelf's own root is REMOVED before the search, so a path THROUGH it cannot answer for a
  // path AROUND it: `::ingraph::__private::async_graphql::Scalar` contains `::async_graphql::` as a
  // substring and is exactly the spelling this asserts the emission uses.
  let unshelved = rendered.replace("::ingraph::__private::", "\u{1}");
  for direct in [
    "::ingraph::TextFilter",
    "::ingraph::GraphqlFilter",
    "::ingraph::ToGraphqlInput",
    "::ingraph::ToGraphqlOutput",
    "::ingraph::StringFilterMarker",
    "::ingraph::DefaultMarker",
    "::async_graphql::",
  ] {
    assert!(
      !unshelved.contains(direct),
      "`{direct}` is spelled without the shelf:\n{rendered}"
    );
  }
}

/// **THE WIRE HALF RIDES THE BINDING GATE**, and the rest does not.
///
/// A `#[cfg(feature = "async-graphql")]` written into an expansion would ask whether the DECLARING
/// crate has a feature by that name; the gate asks the question of `ingraph`'s own build, which is
/// where the library is. The filter type itself is UNCONDITIONAL — a build with no GraphQL library
/// still declares its elements and still filters them in Rust.
#[test]
fn the_wire_half_is_behind_the_gate_and_the_filter_is_not() {
  let rendered = tight(tag().emit());
  let (before, after) = rendered
    .split_once("if_async_graphql!")
    .expect("the wire half rides the gate");

  assert!(before.contains("pubstructTagFilter"), "{before}");
  assert!(before.contains("StringFilterMarker"), "{before}");
  assert!(before.contains("ToDatabaseComparison"), "{before}");
  assert!(!before.contains("async_graphql::InputType"), "{before}");

  assert!(after.contains("async_graphql::ScalarType"), "{after}");
  assert!(after.contains("async_graphql::InputType"), "{after}");
  assert!(after.contains("ToGraphqlInput"), "{after}");
  assert!(after.contains("ToGraphqlOutput"), "{after}");
}

/// **THE MINTED TYPE TAKES THE DECLARATION'S VISIBILITY**, so an element a crate keeps to itself
/// mints a filter it keeps to itself. Its MEMBER is `pub(crate)` whatever that visibility is — the
/// three-layer naming law's substrate, readable by a sibling expansion and never API.
#[test]
fn the_minted_filter_takes_the_declarations_visibility() {
  let mut private = tag();
  private.vis = syn::Visibility::Inherited;
  let rendered = tight(private.emit());

  assert!(
    rendered.contains("structTagFilter(pub(crate)"),
    "{rendered}"
  );
  assert!(!rendered.contains("pubstructTagFilter"), "{rendered}");
}

/// **EACH FAMILY HOLDS ITS OWN KIND**, which is what makes the word decide rather than decorate.
#[test]
fn each_family_holds_the_frameworks_own_kind() {
  for (family, kind) in [
    (ElementFamily::Scalar, "ScalarFilter"),
    (ElementFamily::String, "TextFilter"),
    (ElementFamily::Bytes, "BytesFilter"),
    (ElementFamily::Enum, "EnumFilter"),
  ] {
    let rendered = tight(model(family, "Value", syn::parse_quote!(String)).emit());
    assert!(
      rendered.contains(&format!("__private::graphql::{kind}<Value>")),
      "the {} family holds `{kind}`:\n{rendered}",
      family.word()
    );
  }
}

/// **EACH FAMILY'S OPERATION SET IS ITS OWN**, and the counts are the framework's own filters'.
///
/// Read off the emitted WIRE names rather than the accessor idents, because the wire name is the
/// schema commitment: a slot that lost its name would still compile and would publish a face a
/// client cannot write.
///
/// ALL FOUR are read here now. The enumeration used to be absent for want of a face to render its
/// slots on, which is exactly what the alias's retirement gave it — so its row is the shortest
/// statement of what changed: four slots, rendered, where before there were four slots and no
/// rendering.
#[test]
fn each_familys_operation_set_is_the_frameworks_own() {
  for (family, count, present, absent) in [
    (ElementFamily::Scalar, 8, "\"lte\"", "\"contains\""),
    (ElementFamily::String, 20, "\"startsWithNocase\"", "\"any\""),
    (
      ElementFamily::Bytes,
      10,
      "\"notContains\"",
      "\"startsWith\"",
    ),
    (ElementFamily::Enum, 4, "\"notIn\"", "\"gt\""),
  ] {
    let rendered = tight(model(family, "Value", syn::parse_quote!(String)).emit());
    let slots = family.operations().len();
    assert_eq!(
      slots,
      count,
      "the {} family has {count} operators",
      family.word()
    );
    assert!(rendered.contains(present), "{rendered}");
    assert!(!rendered.contains(absent), "{rendered}");
  }
}

/// **EVERY FAMILY HANDS THE HELD FILTER OUT, AND HANDS ITS OPERANDS ON** — the owning projection
/// and the operand map, which land together because the second is written through the first.
///
/// # Why both are read at all four families rather than at one
///
/// They are the two rows a CROSSING needs, and a crossing is per (element × dialect): a family that
/// grew a special case would be a family whose elements could not be lowered the way the other
/// three's are. The `Mapped` projection is asserted as the HELD filter's own answer rather than as
/// a spelling, which is what makes the row a delegation — the enum family lands `EnumFilter<V>` and
/// the bytes family `BytesFilter<V, K, I>`, and this door decides neither.
#[test]
fn every_family_hands_out_what_it_holds_and_maps_what_it_carries() {
  for (family, kind) in [
    (ElementFamily::Scalar, "ScalarFilter"),
    (ElementFamily::String, "TextFilter"),
    (ElementFamily::Bytes, "BytesFilter"),
    (ElementFamily::Enum, "EnumFilter"),
  ] {
    let rendered = tight(model(family, "Value", syn::parse_quote!(String)).emit());
    let held = format!("::ingraph::__private::graphql::{kind}<Value>");

    // THE OWNING PROJECTION, beside the borrowing one rather than instead of it.
    assert!(
      rendered.contains(&format!("pubfninto_inner(self)->{held}{{self.0}}")),
      "the {} family hands the held filter out:\n{rendered}",
      family.word(),
    );
    assert!(
      rendered.contains(&format!("pubconstfnget(&self)->&{held}")),
      "and keeps the borrowing one:\n{rendered}",
    );

    // THE OPERAND MAP, its `Mapped` PROJECTED off the held filter and its value half delegating
    // through the projection above.
    assert!(
      rendered.contains("TryMapFilter<Value,__INGRAPH_STORED__>forValueFilter"),
      "the {} family maps its operands:\n{rendered}",
      family.word(),
    );
    assert!(
      rendered.contains(&format!(
        "typeMapped=<{held}as::ingraph::__private::graphql::TryMapFilter<Value,__INGRAPH_STORED__>>\
         ::Mapped;"
      )),
      "and projects `Mapped` off what it holds:\n{rendered}",
    );
    assert!(
      rendered.contains("Self::into_inner(self)"),
      "and delegates through the owning projection:\n{rendered}",
    );
  }
}

/// **THE ENUM FAMILY'S DOOR MINTS**, and the claim is that its emission is the OTHER THREE's item
/// for item.
///
/// It used to be a TYPE ALIAS — `pub type CodecFilter = EnumFilter<Codec>` — which routed around
/// the orphan rule at the nullable twin before `ingraph::NullableFace` brought that wall down. What
/// the detour went on costing is in `ElementModel::declaration`'s note; what it cost HERE is the
/// items below, every one of which the other three families had and this one did not.
///
/// Asserted item by item rather than as a rendering, because the shape IS the item list: a door
/// that emitted the struct and skipped the nullable row would still be a door with a struct in it.
#[test]
fn the_enum_familys_door_mints_the_same_items_the_other_three_do() {
  let model = model(ElementFamily::Enum, "Codec", syn::parse_quote!(String));
  let rendered = tight(model.emit());

  assert!(
    rendered.contains(
      "pubstructCodecFilter(pub(crate)::ingraph::__private::graphql::EnumFilter<Codec>);"
    ),
    "{rendered}"
  );
  assert!(!rendered.contains("typeCodecFilter="), "{rendered}");

  for present in [
    "implCodecFilter",                                      // the accessor face
    "GraphqlFilterforCodecFilter",                          // the emptiness contract
    "ToDatabaseComparison",                                 // the lowering map
    "TryMapFilter<Codec,__INGRAPH_STORED__>forCodecFilter", // the operand map
    "async_graphql::InputTypeforCodecFilter",               // the input object
    "async_graphql::InputObjectTypeforCodecFilter",         // and its marker
    "NullableFaceforCodecFilter", // and the row its nullable twin is built from
  ] {
    assert!(
      rendered.contains(present),
      "a minting door emits `{present}`:\n{rendered}"
    );
  }

  // The family's four slot names are rendered now, on the face the mint gave them — and they are
  // `EnumFilter<T>`'s own four, in `EnumFilter<T>`'s own order, which is why the SDL did not move.
  assert_eq!(model.family.operations().len(), 4);
  for slot in ["\"eq\"", "\"ne\"", "\"in\"", "\"notIn\""] {
    assert!(rendered.contains(slot), "{rendered}");
  }

  // The ELEMENT's own halves are unchanged beside them: the two readings a field resolves through,
  // and the scalar and crossings only a declaring crate can write.
  for present in [
    "EnumFilterMarkerforCodec",
    "DefaultMarkerforCodec",
    "ScalarTypeforCodec",
    "ToGraphqlInputforCodec",
    "ToGraphqlOutputforCodec",
  ] {
    assert!(rendered.contains(present), "{rendered}");
  }
}

/// **THE ENUM FAMILY'S MINT TAKES THE DECLARATION'S VISIBILITY** too, which is the visibility claim
/// stated at the family that used to reach it down a second path.
#[test]
fn the_enum_familys_mint_takes_the_declarations_visibility() {
  let mut private = model(ElementFamily::Enum, "Codec", syn::parse_quote!(String));
  private.vis = syn::Visibility::Inherited;
  let rendered = tight(private.emit());

  assert!(
    rendered.contains("structCodecFilter(pub(crate)"),
    "{rendered}"
  );
  assert!(!rendered.contains("pubstructCodecFilter"), "{rendered}");
}

/// **THE RENAME WORD MOVES BOTH NAMES, AT EVERY FAMILY** — the divergence the enum door used to
/// carry, closed.
///
/// `filter(rename = "…")` moved the RUST name at all four and the WIRE name at three: the alias had
/// no `type_name` of its own, so `EnumFilter<T>`'s derivation kept publishing `<Element>Filter`
/// whatever the declaration renamed the alias to. Both names are the mint's now, and the assertion
/// is the pair — the struct's ident and the string `InputType::type_name` returns — at each family
/// in turn, so a door that moved one and not the other is named.
#[test]
fn a_renamed_filter_moves_the_rust_name_and_the_wire_name_at_every_family() {
  for family in ElementFamily::ALL {
    let mut renamed = model(family, "Codec", syn::parse_quote!(String));
    renamed.filter = crate::name::RustSafeName::from_ident(&syn::Ident::new(
      "CodecPredicate",
      proc_macro2::Span::call_site(),
    ));
    let rendered = tight(renamed.emit());
    let word = family.word();

    assert!(
      rendered.contains("pubstructCodecPredicate("),
      "the {word} family mints the RENAMED type:\n{rendered}"
    );
    assert!(
      rendered.contains(r#"Cow::Borrowed("CodecPredicate")"#),
      "the {word} family publishes the RENAMED wire name:\n{rendered}"
    );
    // And the old name is gone from BOTH faces rather than merely joined by the new one.
    assert!(
      !rendered.contains("CodecFilter"),
      "the {word} family leaves no `CodecFilter` behind:\n{rendered}"
    );
  }
}

/// **A NAMED FIELD IS AN ELEMENT AS READILY AS A POSITIONAL ONE**, and the emission spells the
/// member it was given — the watershed being the MARKER rather than the punctuation.
#[test]
fn a_named_member_is_spelled_where_a_positional_one_is() {
  let mut named = tag();
  named.member = syn::Member::Named(syn::Ident::new("words", proc_macro2::Span::call_site()));
  let rendered = tight(named.emit());

  assert!(
    rendered.contains("Self{words:__ingraph_inner}"),
    "{rendered}"
  );
  assert!(rendered.contains("&self.words"), "{rendered}");
}

/// **THE SCALAR IS NAMED AFTER THE ELEMENT AND THE INPUT OBJECT AFTER THE FILTER**, which is what a
/// client reads and the only place either name is stated.
#[test]
fn the_two_wire_names_are_the_two_rust_names() {
  let rendered = tight(tag().emit());
  assert!(rendered.contains(r#"name="Tag""#), "{rendered}");
  assert!(
    rendered.contains(r#"Cow::Borrowed("TagFilter")"#),
    "{rendered}"
  );
}

/// **THE EMISSION PARSES AS RUST**, which is what keeps a token-level assertion above from passing
/// over something rustc would refuse to read at all.
#[test]
fn the_emission_is_a_well_formed_item_sequence() {
  for family in ElementFamily::ALL {
    let emitted = model(family, "Value", syn::parse_quote!(String)).emit();
    syn::parse2::<syn::File>(quote!(#emitted))
      .unwrap_or_else(|e| panic!("the {} family's emission parses: {e}", family.word()));
  }
}