ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! **THE BACKEND-NAMESPACE LAW, held over the whole emission** — every ident an emitted
//! async-graphql face mints wears `__async_graphql_`, and every name a client reads is written out
//! beside it.
//!
//! Beside the door rather than in [`crate::tests`], which is this workspace's shape for an axis
//! that arrives with its own grammar: the roster a reader walks stays the one it was.
//!
//! # Why a WALK and not a list of names
//!
//! [`wire_method`] is one function, so the door itself is a one-line assertion. What a one-line
//! assertion cannot say is that the door is the ONLY door — an emitter that spelled a prefix by
//! hand would satisfy it and break the law in the same expansion. So the second pin reads the
//! emitted tokens back, finds every `#[Object]` face in them, and holds the rule over every
//! function and every argument it finds, whatever a later round adds.
//!
//! # The SECOND law, which the prefix's own shape makes load-bearing
//!
//! async-graphql's default field name is its rename rule over the METHOD IDENT, and `Inflector`
//! skips a leading separator run before camelCasing what remains. Under a bare `__` that produced
//! the member's own name by accident — `__title` → `title` — so an item that forgot its
//! `#[graphql(name = "…")]` still published the right word. Under a prefix that NAMES THE BACKEND
//! it does not: `__async_graphql_title` → `asyncGraphqlTitle`. So layer 3 is no longer prudence,
//! and the walk asks for it on every item that is a schema item at all.
//!
//! # What the law does NOT reach, stated so an absence reads as a decision
//!
//! * the emission's own LOCALS (`__ingraph_*`) — a local is scoped to its body, so two backends'
//!   bodies cannot collide however they spell theirs;
//! * the ACCESSORS beside a face — layer 2, the Rust read road, which a caller spells;
//! * the emitted TYPES — visible vocabulary a declaration names and an application mounts;
//! * a resolver's `&Context`, which async-graphql reads by TYPE and never publishes, so it is the
//!   one named parameter with no client-facing name to write.
//!
//! Each of the first three is [`wire_method`]'s own note, and the walk below is scoped to
//! `#[Object]` blocks precisely so that stating them here costs nothing: nothing outside such a
//! block is examined at all.

use quote::{ToTokens as _, format_ident};

use super::wire_method;

/// The prefix the ruling of 2026-08-13 names, spelled ONCE on the assertion side.
///
/// A test that spelled it per assertion would be a second copy of the door's own shape, which is
/// the drift this module is here to catch rather than to commit.
const PREFIX: &str = "__async_graphql_";

/// **THE DOOR** — what [`wire_method`] mints, including the input that made the prefix load-bearing
/// twice over.
///
/// `where` is a Rust KEYWORD, and a prefixed keyword is an ordinary ident — which is why the
/// argument the list leg spends can be handed to the door at all. The pin is here rather than at
/// that emitter because the property is the door's.
#[test]
fn the_door_mints_the_backend_s_own_namespace() {
  assert_eq!(
    wire_method(&format_ident!("title")).to_string(),
    "__async_graphql_title"
  );
  assert_eq!(
    wire_method(&format_ident!("where")).to_string(),
    "__async_graphql_where"
  );
}

/// One item of an emitted face — a function, or one named parameter of one.
struct Minted {
  /// The Rust ident the emission minted.
  ident: String,
  /// Whether LAYER 3 sits on it: a `#[graphql(name = "…")]`, the client's own word.
  named: bool,
  /// Whether this is the resolver's `&Context` — read by TYPE, published never.
  context: bool,
}

/// One emitted `#[Object]` face.
struct Face {
  /// The type the face is for, for a message that has to say which one broke the rule.
  owner: String,
  /// Its functions and their named parameters, in emission order.
  minted: Vec<Minted>,
  /// How many of those are ARGUMENTS, so a run over a corpus can say the argument half was reached.
  arguments: usize,
}

/// Whether an attribute is async-graphql's `Object`.
///
/// Matched on the LEAF beside an `async_graphql` segment rather than on the whole path, because the
/// emission reaches the attribute through the shelf — `#krate::__private::async_graphql::Object`
/// — and a walk keyed on the shelf's own spelling would answer differently for a declaring crate
/// than for this one.
fn is_object(attribute: &syn::Attribute) -> bool {
  let path = attribute.path();
  path
    .segments
    .last()
    .is_some_and(|segment| segment.ident == "Object")
    && path
      .segments
      .iter()
      .any(|segment| segment.ident == "async_graphql")
}

/// Whether a `#[graphql(…)]` attribute among these writes a `name` key.
///
/// The KEY and not the whole attribute, because an item may carry other graphql words beside it and
/// the law is about the name alone.
fn names_itself(attributes: &[syn::Attribute]) -> bool {
  attributes.iter().any(|attribute| {
    attribute.path().is_ident("graphql")
      && attribute
        .to_token_stream()
        .to_string()
        .replace(' ', "")
        .contains("name=")
  })
}

/// Every `#[Object]` face in a walked emission, descending into the anonymous const the impls live
/// in.
///
/// [`crate::tests::emission`] has already opened the feature gates, so a face inside one is an
/// ordinary item here — which is the property that keeps a gate from being a place the law could
/// be broken unwatched.
fn faces(items: &[syn::Item]) -> Vec<Face> {
  let mut found = Vec::new();
  for item in items {
    match item {
      syn::Item::Const(anonymous) => {
        if let syn::Expr::Block(block) = &*anonymous.expr {
          let held: Vec<syn::Item> = block
            .block
            .stmts
            .iter()
            .filter_map(|statement| match statement {
              syn::Stmt::Item(item) => Some(item.clone()),
              _ => None,
            })
            .collect();
          found.extend(faces(&held));
        }
      }
      syn::Item::Impl(block) if block.attrs.iter().any(is_object) => {
        let mut face = Face {
          owner: block.self_ty.to_token_stream().to_string().replace(' ', ""),
          minted: Vec::new(),
          arguments: 0,
        };
        for item in &block.items {
          let syn::ImplItem::Fn(method) = item else {
            continue;
          };
          face.minted.push(Minted {
            ident: method.sig.ident.to_string(),
            named: names_itself(&method.attrs),
            context: false,
          });
          for argument in &method.sig.inputs {
            let syn::FnArg::Typed(typed) = argument else {
              continue;
            };
            let syn::Pat::Ident(named) = &*typed.pat else {
              continue;
            };
            face.arguments += 1;
            face.minted.push(Minted {
              ident: named.ident.to_string(),
              named: names_itself(&typed.attrs),
              context: typed.ty.to_token_stream().to_string().contains("Context"),
            });
          }
        }
        found.push(face);
      }
      _ => {}
    }
  }
  found
}

/// **BOTH LAWS OVER THE CORPUS** — every function and every argument of every emitted `#[Object]`
/// face is inside the backend's namespace, and every one that is a schema item spells its own
/// client name.
///
/// Two models, because the faces they emit are different halves of the same law: `wired` writes the
/// two OUTPUT objects, whose methods are `&self` readers, and `queried` adds the QUERY UNIT, whose
/// legs are the emission's only functions that take named parameters at all. The argument half is
/// vacuous without the second, and a vacuous pin is what this file exists to refuse — so the count
/// is asserted rather than assumed.
#[test]
fn every_ident_an_emitted_face_mints_wears_the_backend_prefix() {
  let mut arguments_seen = 0usize;
  for (label, model) in [
    ("wired", crate::tests::wired()),
    ("queried", crate::tests::queried()),
  ] {
    let file = crate::tests::emission(&model);
    let found = faces(&file.items);
    assert!(
      !found.is_empty(),
      "{label}: the walk found no `#[Object]` face, so the rules below would hold vacuously"
    );
    for face in found {
      assert!(
        !face.minted.is_empty(),
        "{label}: `{}` is an empty face — an object with no field is not a GraphQL type",
        face.owner
      );
      arguments_seen += face.arguments;
      for minted in &face.minted {
        assert!(
          minted.ident.starts_with(PREFIX),
          "{label}: `{}::{}` is minted inside an async-graphql face and is not in that backend's \
           namespace — every such ident goes through `method::wire_method`, and a second GraphQL \
           binding on this type is what an unprefixed one would collide with",
          face.owner,
          minted.ident
        );
        assert!(
          minted.named || minted.context,
          "{label}: `{}::{}` publishes a name derived from its IDENT, and the ident carries the \
           backend's prefix — async-graphql would render it `asyncGraphql…`. Every schema item \
           writes `#[graphql(name = \"…\")]`",
          face.owner,
          minted.ident
        );
      }
    }
  }
  assert!(
    arguments_seen > 0,
    "the ARGUMENT half of the law was never exercised — the query unit's legs are what carry it"
  );
}