ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The NEWTYPE DEVICE's emission, read as TOKENS — the claims a compiled expansion cannot make.
//!
//! `ingraph`'s own `tests/newtype_device.rs` is where three declared shapes reach a real schema, a
//! real cursor and a real database, 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 delegation is FULLY QUALIFIED, which a bare `self.0.method(…)` would satisfy the
//!   compiler with today and resolve elsewhere the day the inner type grows an inherent method;
//! - that every framework name goes through the SHELF rather than through a direct path;
//! - that a kit nobody named emits NOTHING, which is the whole content of *opt-in*;
//! - that the wire face rides the BINDING GATE and the dialect rows their own.

use super::{Gate, Kits, NewTypeModel, ScalarKit};
use crate::{element::ElementFamily, model::DatabaseKind};

/// 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 newtype, as the front end would have handed it over.
fn model(inner: syn::Type, kits: Kits) -> NewTypeModel {
  NewTypeModel {
    vis: syn::parse_quote!(pub),
    subject: syn::Ident::new("Tag", proc_macro2::Span::call_site()),
    generics: syn::Generics::default(),
    krate: syn::parse_quote!(::ingraph),
    member: syn::Member::Unnamed(syn::Index {
      index: 0,
      span: proc_macro2::Span::call_site(),
    }),
    inner,
    kits,
  }
}

/// EVERY kit this round builds, on one declaration — the widest emission there is.
fn whole() -> NewTypeModel {
  model(
    syn::parse_quote!(String),
    Kits {
      scalar: Some(ScalarKit {
        rename: None,
        gate: Some(Gate::Parse(syn::parse_quote!(door))),
      }),
      input: true,
      output: true,
      marker: Some(ElementFamily::String),
      filter: true,
      cursor: true,
      databases: vec![DatabaseKind::Sqlite, DatabaseKind::Postgres],
    },
  )
}

/// **THE EMISSION LAW: no delegation is a BARE METHOD CALL.**
///
/// `self.0.push_bind(qb)` compiles today and resolves elsewhere tomorrow — method resolution
/// prefers an INHERENT method, so an inner type growing one of that name silently takes the call
/// away from the trait the row is implementing. Asserted as an ABSENCE over the whole emission,
/// because the positive form would be a list to keep in step with what is emitted.
///
/// The one dotted spelling that IS legal is a FIELD access, and it is the reason the search is for
/// `self.0.` followed by a letter rather than for `self.0` alone: `&self.0` is the argument every
/// qualified call passes, and `self.0.method(` is the shape this rules out.
#[test]
fn no_delegation_is_written_as_a_bare_method_call() {
  let rendered = tight(whole().emit());
  for (at, _) in rendered.match_indices("self.0.") {
    let tail = &rendered[at + "self.0.".len()..];
    assert!(
      !tail.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_'),
      "a bare method call on the wrapped value: …{}…",
      &rendered[at..(at + 60).min(rendered.len())]
    );
  }
}

/// **EVERY DELEGATION NAMES ITS TRAIT**, which is the positive half of the law — and it is asserted
/// per ROW rather than in aggregate, so a row that stopped delegating is caught rather than covered
/// for by its neighbours.
#[test]
fn every_row_reaches_the_wrapped_type_through_its_trait() {
  let rendered = tight(whole().emit());
  for qualified in [
    "<Stringas::ingraph::__private::cursor::CursorValue>::write_cursor",
    "<Stringas::ingraph::__private::cursor::CursorValue>::read_cursor",
    "<Stringas::ingraph::__private::column::ColumnKind>::SEGMENTS",
    "<Stringas::ingraph::__private::comparison::sql::Carrier<::ingraph::__private::sqlx::Sqlite>>::push_bind",
    "<Stringas::ingraph::__private::sqlx::Type<::ingraph::__private::sqlx::Sqlite>>::type_info",
    "<Stringas::ingraph::__private::sqlx::Encode<'__ingraph,::ingraph::__private::sqlx::Sqlite>>::produces",
  ] {
    assert!(rendered.contains(qualified), "missing `{qualified}`");
  }
}

/// **`Encode` IS DELEGATED WHOLE**, all four methods.
///
/// `produces` is the one that would matter quietly: it is the per-VALUE type override, consulted
/// ahead of `Type::type_info`, so a default `None` here would discard the wrapped type's answer with
/// nothing to see. The other three are here so that the day one of them grows a default worth
/// overriding, this test is what says the wrapper is not taking it.
#[test]
fn the_encode_row_forwards_every_method() {
  let rendered = tight(whole().emit());
  for method in [
    "fnencode(",
    "fnencode_by_ref(",
    "fnproduces(",
    "fnsize_hint(",
  ] {
    assert!(rendered.contains(method), "`Encode` is missing `{method}`");
  }
}

/// **A KIT NOBODY NAMED EMITS NOTHING**, which is the whole content of *opt-in* and the line between
/// this device and the element mode.
#[test]
fn an_unnamed_kit_emits_nothing() {
  let lone = tight(
    model(
      syn::parse_quote!(u64),
      Kits {
        input: true,
        ..Kits::default()
      },
    )
    .emit(),
  );
  assert!(lone.contains("ToGraphqlInput"));
  for absent in [
    "ScalarType",
    "CursorValue",
    "ColumnKind",
    "DefaultMarker",
    "Carrier",
    "Assemble",
    "ToGraphqlOutput",
  ] {
    assert!(!lone.contains(absent), "an unnamed kit emitted `{absent}`");
  }
}

/// **THE WIRE FACE RIDES THE BINDING GATE**, and each dialect's rows ride that dialect's — while the
/// row every dialect SHARES rides the family's.
///
/// Three gates and not one, and the middle one is why: a `Carrier<Sqlite>` names a type a lean build
/// has not got, and the read row is generic over the ROW — so a build with two dialects would get it
/// twice if it rode theirs.
#[test]
fn each_row_rides_the_gate_its_names_need() {
  let rendered = tight(whole().emit());
  for gate in [
    "::ingraph::__private::gate::if_async_graphql!",
    "::ingraph::__private::gate::if_sqlx!",
    "::ingraph::__private::gate::if_sqlite!",
    "::ingraph::__private::gate::if_postgres!",
  ] {
    assert!(rendered.contains(gate), "missing `{gate}`");
  }
}

/// **THE MINTED READING IS THE ONLY NAME THE DECLARING SCOPE GAINS**, and it takes the
/// DECLARATION's visibility rather than a fixed `pub`.
///
/// Everything else lives inside an anonymous `const`, which is where an emission puts what it owes
/// the declaring scope no name for.
#[test]
fn the_reading_is_the_one_name_outside_the_anonymous_const() {
  let rendered = tight(whole().emit());
  let (before, _) = rendered
    .split_once("const_:()={")
    .expect("the emission opens an anonymous const");
  assert!(before.contains("pubenumTagWire{}"), "{before}");

  let private = tight(
    NewTypeModel {
      vis: syn::parse_quote!(pub(crate)),
      ..whole()
    }
    .emit(),
  );
  assert!(private.contains("pub(crate)enumTagWire{}"), "{private}");
}

/// **A READING PUBLISHES `<the operand's schema name>Filter`**, and a `rename` moves both.
///
/// The framework's own naming law, applied where the framework cannot see the type: a reading that
/// spelled its own name would be free to disagree with the name the operand already publishes.
#[test]
fn the_reading_publishes_the_operands_name_and_follows_a_rename() {
  assert!(
    tight(whole().emit()).contains(r#"constNAME:&'static::core::primitive::str="TagFilter""#)
  );

  let renamed = NewTypeModel {
    kits: Kits {
      scalar: Some(ScalarKit {
        rename: Some("Label".to_owned()),
        gate: None,
      }),
      ..whole().kits
    },
    ..whole()
  };
  let rendered = tight(renamed.emit());
  assert!(
    rendered.contains(r#"name="Label""#),
    "the scalar's own name"
  );
  assert!(
    rendered.contains(r#"constNAME:&'static::core::primitive::str="LabelFilter""#),
    "the filter's name follows it"
  );
}

/// **THE ENUM FAMILY MINTS NO READING**, and the absence is the framework's shape rather than a gap:
/// `EnumFilter<T>` carries no carrier parameter, a closed vocabulary's operands crossing as
/// themselves.
#[test]
fn the_enumeration_family_names_its_filter_directly() {
  let rendered = tight(
    model(
      syn::parse_quote!(u32),
      Kits {
        marker: Some(ElementFamily::Enum),
        filter: true,
        ..Kits::default()
      },
    )
    .emit(),
  );
  assert!(
    !rendered.contains("TagWire"),
    "no reading is minted: {rendered}"
  );
  assert!(rendered.contains("typeFilter=::ingraph::__private::graphql::EnumFilter<Tag>;"));
}

/// **THE CROSSING FOLLOWS THE FACE.** A declaration publishing a scalar crosses as ITSELF; one
/// publishing none crosses as whatever its wrapped type crosses as.
#[test]
fn the_crossing_form_forks_on_the_scalar() {
  let faced = tight(whole().emit());
  assert!(faced.contains("typeInput=Tag;"), "{faced}");

  let transparent = tight(
    model(
      syn::parse_quote!(u64),
      Kits {
        input: true,
        ..Kits::default()
      },
    )
    .emit(),
  );
  assert!(
    transparent.contains("typeInput=<u64as::ingraph::__private::graphql::ToGraphqlInput>::Input;"),
    "{transparent}"
  );
}

/// **THE DOOR IS SPENT ON EVERY READ AND ON NO WRITE.**
///
/// Counted rather than described: the scalar's `parse`, its `is_valid`, the cursor's `read_cursor`,
/// the row's `assemble` and one `decode` per dialect all name the door, and the write paths name it
/// nowhere. A write is a value the type already holds, so there is nothing to check.
#[test]
fn the_door_is_named_by_every_read_path_and_by_no_write() {
  let rendered = tight(whole().emit());
  assert_eq!(
    rendered.matches("door(").count(),
    6,
    "two wire legs, the cursor, the row read, and one decode per dialect: {rendered}"
  );

  let doorless = tight(
    NewTypeModel {
      kits: Kits {
        scalar: Some(ScalarKit::default()),
        ..whole().kits
      },
      ..whole()
    }
    .emit(),
  );
  assert!(
    !doorless.contains("door("),
    "a declaration with no door names none"
  );
}

/// **NO EMITTED PATH REACHES THE FRAMEWORK WITHOUT THE SHELF.**
///
/// An expansion lands in the DECLARING crate, so a direct `::ingraph::CursorValue` 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.
#[test]
fn no_emitted_path_reaches_the_framework_without_the_shelf() {
  let rendered = tight(whole().emit());
  // The shelf's own root is REMOVED before the search, so a path THROUGH it cannot answer for a
  // path AROUND it.
  let unshelved = rendered.replace("::ingraph::__private::", "\u{1}");
  for direct in [
    "::ingraph::CursorValue",
    "::ingraph::ColumnKind",
    "::ingraph::Assemble",
    "::ingraph::DefaultMarker",
    "::ingraph::ToGraphqlInput",
    "::ingraph::ToGraphqlOutput",
    "::ingraph::TextFilter",
    "::ingraph::sqlx",
    "::async_graphql::",
  ] {
    assert!(
      !unshelved.contains(direct),
      "`{direct}` is reached around the shelf"
    );
  }
}

/// **A NAMED FIELD IS A NEWTYPE TOO**, and every row reaches it by its own name — the READ that
/// rebuilds `Self` as much as the write that takes the value out.
#[test]
fn a_named_member_is_reached_by_name() {
  let bound = tight(
    NewTypeModel {
      member: syn::Member::Named(syn::Ident::new("text", proc_macro2::Span::call_site())),
      ..whole()
    }
    .emit(),
  );
  assert!(bound.contains("&self.text"), "{bound}");

  // The rebuild is on the TRANSPARENT road, where a crossing wraps rather than passing itself on.
  let built = tight(
    NewTypeModel {
      member: syn::Member::Named(syn::Ident::new("text", proc_macro2::Span::call_site())),
      kits: Kits {
        input: true,
        ..Kits::default()
      },
      ..whole()
    }
    .emit(),
  );
  assert!(built.contains("Self{text:__ingraph_inner}"), "{built}");
}

/// **A DECLARATION'S OWN PARAMETERS RIDE EVERY ROW**, and each row's own obligation is added rather
/// than substituted — which is what makes a pass-through writable at all where the wrapped type is a
/// PARAMETER.
#[test]
fn a_parameterised_declaration_carries_its_bounds_onto_every_row() {
  let rendered = tight(
    NewTypeModel {
      generics: syn::parse_quote!(<S: Unit>),
      inner: syn::parse_quote!(S),
      ..whole()
    }
    .emit(),
  );
  assert!(rendered.contains("forTag<S>"), "{rendered}");
  assert!(
    rendered.contains("S:::ingraph::__private::cursor::CursorValue"),
    "the row's own obligation is a `where` predicate on the wrapped type: {rendered}"
  );
  assert!(
    rendered.contains("<Sas::ingraph::__private::cursor::CursorValue>::write_cursor"),
    "and the call names it: {rendered}"
  );
}