ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The union emitter'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 the derive reach this emitter only exists while the emitter can be driven
//! from a plain model.

use super::{Face, UnionMember, UnionModel};

/// The union the whole module is measured against: three members, the last of them over a type
/// nobody declared, so nothing here can quietly depend on a member being a bare path.
fn found() -> UnionModel {
  UnionModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("Found"),
    members: vec![
      member("Media", syn::parse_quote!(Media)),
      member("Clip", syn::parse_quote!(Clip)),
      member("Tape", syn::parse_quote!(Vec<u8>)),
    ],
    error: None,
    graphql: Vec::new(),
  }
}

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

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// The expansion, read back as items.
fn emission(model: &UnionModel) -> syn::File {
  syn::parse2(model.emit()).expect("the expansion parses")
}

/// The whole expansion as one string, so a claim about it can be a substring.
fn rendered(model: &UnionModel) -> String {
  prettyplease::unparse(&emission(model))
}

/// The anonymous const's statements, in emission order.
fn body(file: &syn::File) -> Vec<syn::Stmt> {
  let block = file
    .items
    .iter()
    .find_map(|item| match item {
      syn::Item::Const(anonymous) if anonymous.ident == "_" => Some(&anonymous.expr),
      _ => None,
    })
    .expect("the expansion holds one anonymous const");
  let syn::Expr::Block(block) = block.as_ref() else {
    panic!("the const's value is a block");
  };
  block.block.stmts.clone()
}

/// Every type the expansion declares into the DECLARING scope, named as it names them.
fn declared_structs(file: &syn::File) -> Vec<String> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// The face's methods, in emission order.
fn methods(model: &UnionModel) -> Vec<String> {
  face(&emission(model))
    .iter()
    .map(|method| method.sig.ident.to_string())
    .collect()
}

/// The face's `const` methods, in emission order.
fn const_methods(model: &UnionModel) -> Vec<String> {
  face(&emission(model))
    .iter()
    .filter(|method| method.sig.constness.is_some())
    .map(|method| method.sig.ident.to_string())
    .collect()
}

/// Every method of the inherent impl the anonymous const holds.
fn face(file: &syn::File) -> Vec<syn::ImplItemFn> {
  body(file)
    .iter()
    .filter_map(|stmt| match stmt {
      syn::Stmt::Item(syn::Item::Impl(item)) if item.trait_.is_none() => Some(&item.items),
      _ => None,
    })
    .flatten()
    .filter_map(|item| match item {
      syn::ImplItem::Fn(item) => Some(item.clone()),
      _ => None,
    })
    .collect()
}

/// **The expansion declares its REFUSAL type and nothing else.**
///
/// A union is a type somebody else already declared, so there is nothing here to name — except the
/// one type a caller has to be able to spell, which is what a wrong-variant unwrap hands back. The
/// face is scoped where it can collide with nothing the declaring module wrote.
#[test]
fn the_expansion_declares_only_the_refusal_a_wrong_unwrap_answers_with() {
  let file = emission(&found());

  assert_eq!(declared_structs(&file), ["FoundUnwrapError"]);
  assert_eq!(
    file
      .items
      .iter()
      .filter(|item| matches!(item, syn::Item::Const(_)))
      .count(),
    1
  );
}

/// **Seven methods per member, in declaration order, spelled the way `#[unwrap(ref, ref_mut)]`
/// spells them.**
///
/// The list is built from [`Face::ALL`], so a receiver the emitter stops writing fails here; the
/// first member's names are also spelled out, so a receiver the whole vocabulary stops knowing
/// about fails here too.
#[test]
fn every_member_gets_the_seven_methods_the_face_vocabulary_names() {
  let model = found();
  let expected: Vec<String> = model
    .members
    .iter()
    .flat_map(|member| Face::ALL.map(|face| face.name(&member.word()).to_string()))
    .collect();

  assert_eq!(methods(&model), expected);
  assert_eq!(
    methods(&model)[..7],
    [
      "is_media",
      "unwrap_media",
      "unwrap_media_ref",
      "unwrap_media_mut",
      "try_unwrap_media",
      "try_unwrap_media_ref",
      "try_unwrap_media_mut"
    ]
  );
}

/// **Only the predicate is `const`.**
///
/// A receiver taking `self` drops the payload it did not match, and a `const fn` may not drop a
/// value whose type could implement [`Drop`] — so the owned pair is out on its own terms, and a
/// family whose three receivers differed in constness would read as an accident.
#[test]
fn only_the_predicate_is_const() {
  assert_eq!(
    const_methods(&found()),
    ["is_media", "is_clip", "is_tape"],
    "{}",
    rendered(&found())
  );
}

/// **The refusal's fields are PRIVATE**, which is what seals its construction to this expansion:
/// nothing outside the declaring module can build one, while both names stay readable through the
/// accessors.
#[test]
fn the_refusal_carries_two_private_fields_and_reads_them_out() {
  let file = emission(&found());
  let refusal = file
    .items
    .iter()
    .find_map(|item| match item {
      syn::Item::Struct(item) => Some(item),
      _ => None,
    })
    .expect("the expansion declares the refusal");

  assert!(
    refusal
      .fields
      .iter()
      .all(|field| matches!(field.vis, syn::Visibility::Inherited)),
    "{:?}",
    refusal.fields
  );
  assert_eq!(
    refusal
      .fields
      .iter()
      .map(|field| field.ident.as_ref().expect("a named field").to_string())
      .collect::<Vec<_>>(),
    ["asked", "held"]
  );

  let rendered = rendered(&found());
  assert!(rendered.contains("pub const fn asked(&self)"), "{rendered}");
  assert!(rendered.contains("pub const fn held(&self)"), "{rendered}");
}

/// **A DECLARED name is the one the expansion emits, everywhere the type is named** — the struct it
/// declares and every signature a caller reads it out of. The default is absent from the whole
/// emission, which is the other half: the rename MOVES the type rather than adding a second
/// spelling of it.
#[test]
fn the_declared_name_is_what_the_whole_expansion_calls_the_refusal() {
  let mut model = found();
  model.error = Some(ident("NoSuchMember"));

  assert_eq!(model.error(), "NoSuchMember");
  assert_eq!(declared_structs(&emission(&model)), ["NoSuchMember"]);

  let rendered = rendered(&model);
  assert!(
    rendered.contains("Result<Media, NoSuchMember>"),
    "the signature a caller reads it out of: {rendered}"
  );
  assert!(
    rendered.contains("NoSuchMember {"),
    "and the construction: {rendered}"
  );
  assert!(!rendered.contains("FoundUnwrapError"), "{rendered}");
}

/// **A rename moves the TYPE and not the sentence.**
///
/// What failed is an unwrap out of the union, so the message names the union — which is also what
/// keeps a declaration that renames the type from silently rewording every refusal its users
/// already match on.
#[test]
fn a_renamed_refusal_still_names_the_union_in_its_sentence() {
  const SENTENCE: &str = r#""`Found`: asked for `{}`, held `{}`""#;

  assert!(rendered(&found()).contains(SENTENCE));
  let mut model = found();
  model.error = Some(ident("NoSuchMember"));
  assert!(rendered(&model).contains(SENTENCE), "{}", rendered(&model));
}

/// **The table saying which variant is held is written ONCE**, and every refusal the face builds
/// reads it.
///
/// Several copies of one mapping are several things that can come to disagree, and the disagreement
/// is invisible: each is right in isolation and only the set is wrong.
#[test]
fn the_held_table_is_written_once_and_read_everywhere() {
  let rendered = rendered(&found());

  assert_eq!(
    rendered.matches("fn __ingraph_held").count(),
    1,
    "{rendered}"
  );
  // One read per `try_unwrap` receiver: three members, three receivers.
  assert_eq!(
    rendered.matches("= __ingraph_held(").count(),
    3 * 3,
    "{rendered}"
  );
}

/// **A ONE-MEMBER union writes no fallback arm and no table**, because it has no wrong variant.
///
/// Its single pattern is irrefutable, so an arm beside it would be `unreachable_patterns` in the
/// declaring crate — a warning at a span its author cannot edit, over an arm nothing could take.
#[test]
fn a_one_member_union_has_no_wrong_variant_to_write_for() {
  let mut model = found();
  model.members.truncate(1);
  let rendered = rendered(&model);

  assert!(!rendered.contains("__ingraph_held"), "{rendered}");
  assert!(
    !rendered.contains("_ =>"),
    "no fallback arm, so nothing builds a refusal there is no variant to earn: {rendered}"
  );
  assert_eq!(methods(&model).len(), 7);
  // The refusal type is still declared and still named in every signature: the face is one shape,
  // and a union that grows a second member grows no new methods.
  assert_eq!(declared_structs(&emission(&model)), ["FoundUnwrapError"]);
  assert!(
    rendered.contains("Result<Media, FoundUnwrapError>"),
    "{rendered}"
  );
}

/// **A union that names no backend names NO framework path either.**
///
/// The method face is `core` and the whole of it, so a declaration that wrote no `graphql(…)` block
/// expands to exactly what every union in this tree expanded to before the wire round: no shelf
/// path, no gate, no library. `crate = "…"` is read regardless — it is a constant of the grammar
/// rather than an entry whose meaning depends on its neighbours — and this is the claim that it
/// costs a silent declaration nothing.
#[test]
fn the_expansion_is_core_and_nothing_else() {
  let rendered = rendered(&found());

  assert!(!rendered.contains("::ingraph"), "{rendered}");
  assert!(!rendered.contains("__private"), "{rendered}");
  assert!(!rendered.contains("async_graphql"), "{rendered}");
}

/// The visibility a declaration carries is the visibility every emitted item takes — a private
/// union's refusal stays private rather than leaking into its crate's public API.
#[test]
fn every_emitted_item_is_exactly_as_visible_as_the_declaration() {
  let mut model = found();
  model.vis = syn::parse_quote!(pub(crate));
  let rendered = rendered(&model);

  assert!(
    rendered.contains("pub(crate) struct FoundUnwrapError"),
    "{rendered}"
  );
  assert!(
    rendered.contains("pub(crate) const fn is_media"),
    "{rendered}"
  );
  assert!(
    rendered.contains("pub(crate) fn try_unwrap_media"),
    "{rendered}"
  );
  assert!(!rendered.contains("pub struct"), "{rendered}");
}