ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The standalone door's own comparison emission, read directly off a hand-built [`StandaloneModel`]
//! — [`crate::fields::tests`]'s own pattern, read onto this door: construct the model rather than go
//! through a front end, emit, parse the result back into a [`syn::File`] and read it dense.
//!
//! # What is pinned here and what is not
//!
//! [`StandaloneModel::generic_pair`]'s pair, at BOTH arms now: gated on the hook exactly as the map
//! row is, present at a bare declaration and at a named one alike, and reading the per-database
//! STORED-type override where a named declaration wrote one — the fact this file's own knife exists
//! to close, [`crate::fields::tests`]'s own byte-identity discipline read onto the parts of
//! [`StandaloneModel::one_comparison`]'s emission the pair does not touch. The front end's own parsing
//! (`filter = "…"` vs `filter(rename = "…")`, the field-level refusal without a hook, the per-database
//! `type = "…"` block's own grammar) is `ingraph-derive`'s suite, unmoved by this file — what changes
//! here is read off a hand-built model, never off attribute tokens.

use crate::{
  model::DatabaseKind,
  name::RustSafeName,
  standalone::{StandaloneColumn, StandaloneModel, StandaloneStored},
};

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

/// One column, named and typed — no rename, no marker, no per-database storage entry: the plainest
/// column a declaration can write, which is what [`StandaloneModel::crossing_of`] reads as the
/// column's own domain type under `DefaultMarker`.
fn column(name: &str, ty: &str) -> StandaloneColumn {
  let member = ident(name);
  StandaloneColumn {
    name: RustSafeName::from_ident(&member),
    member,
    domain: syn::parse_str(ty).expect("a type"),
    wire: None,
    marker: None,
    stored: Vec::new(),
  }
}

/// **THE FIXTURE THE NEW PAIR IS OVER** — a bare struct (no `persist(…)`) naming its own minted
/// filter as the conversion hook, the ordinary shape a struct deriving both `Filter` and `Comparison`
/// writes: `#[ingraph(filter = "RollFilter")]` beside no database word at all.
fn roll() -> StandaloneModel {
  StandaloneModel {
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    subject: ident("Roll"),
    krate: syn::parse_quote!(::ingraph),
    filter: RustSafeName::from_ident(&ident("RollFilter")),
    order_by: RustSafeName::from_ident(&ident("RollOrderBy")),
    comparison: RustSafeName::from_ident(&ident("Roll")),
    databases: Vec::new(),
    columns: vec![column("width", "u32"), column("title", "String")],
    hook: Some(syn::parse_quote!(RollFilter)),
  }
}

/// One emission, parsed back and rendered dense — content rather than layout, [`crate::fields::tests`]'s
/// own `dense_of` read onto a raw token stream instead of a whole model's `.emit()`, because this
/// door has no single combined emitter to call.
fn dense_of(tokens: &proc_macro2::TokenStream) -> String {
  let file: syn::File = syn::parse2(tokens.clone()).expect("the emission is a parsable file");
  prettyplease::unparse(&file)
    .split_whitespace()
    .collect::<String>()
}

/// The same, for a token stream that is a FRAGMENT rather than a whole file —
/// [`StandaloneModel::crossings`]'s own `where`-clause tokens are not a parsable item on their own,
/// so this reads them with `to_string` and drops the spacing `prettyplease` would otherwise supply.
fn tight(tokens: proc_macro2::TokenStream) -> String {
  tokens.to_string().replace(' ', "")
}

/// **THE BARE ARM GAINS THE PAIR, UNDER THE HOOK.** `Default` and `TryFromFilter<RollFilter>` for
/// `RollComparison<DB>`, both at a parameter, both through `ToCrossedComparison` — the emission this
/// whole knife is for.
#[test]
fn the_bare_comparison_gains_the_pair_under_a_hook() {
  let emitted = dense_of(&roll().emit_comparison());

  assert!(
    emitted.contains("::core::default::DefaultforRollComparison<__INGRAPH_DB__>where"),
    "the empty predicate, at a parameter: {emitted}"
  );
  assert!(
    emitted.contains("TryFromFilter<RollFilter>forRollComparison<__INGRAPH_DB__>where"),
    "the crossing, named from the hook rather than from this door's own minted filter: {emitted}"
  );
  assert!(
    emitted.contains("ToCrossedComparison<u32,__INGRAPH_DB__,>"),
    "the scalar column's own row, through the same machinery the fields tier's bare arm uses: \
     {emitted}"
  );
  assert!(
    emitted.contains("ToCrossedComparison<String,__INGRAPH_DB__,>"),
    "and the string column's: {emitted}"
  );
}

/// **TWO COLUMNS OF ONE TYPE CONTRIBUTE ONE ROW** — the `where` clause is a set, so
/// [`StandaloneModel::crossings`] dedups on spelling and not on the field carrying it.
///
/// Read off [`StandaloneModel::crossings`] directly rather than off the whole emission: the BODY
/// names each member's row once PER MEMBER (a `cross`/`empty` call per column), which is correct and
/// is not what this test is about — only the CLAUSE is a set.
#[test]
fn two_columns_of_one_type_dedup_to_one_row() {
  let mut model = roll();
  model.columns = vec![column("width", "u32"), column("height", "u32")];
  let clause = tight(model.crossings(&ident("__INGRAPH_DB__"), None));
  assert_eq!(
    clause.matches("ToCrossedComparison<u32,").count(),
    1,
    "one clause row for the shared kind, not two: {clause}"
  );
}

/// **NO HOOK, NO PAIR — exactly as no hook was already no map row.** The pair rides the same gate
/// [`StandaloneModel::crossing`] always has, so a declaration naming no seat gets neither half.
///
/// `ToDatabaseComparison` itself is NOT the pin: the struct's own PER-COLUMN bounds
/// ([`StandaloneModel::assumptions`]) use that trait unconditionally, hook or not. What is new and
/// therefore what must stay absent is the MAP ROW naming the SUBJECT — `ToDatabaseComparison<Roll,
/// …> for RollFilter` — and the value-level pair beside it.
#[test]
fn a_bare_comparison_with_no_hook_gains_nothing() {
  let mut model = roll();
  model.hook = None;
  let emitted = dense_of(&model.emit_comparison());

  assert!(
    !emitted.contains("TryFromFilter"),
    "no crossing without a seat to cross from: {emitted}"
  );
  assert!(
    !emitted.contains("ToCrossedComparison"),
    "the new machinery is unreached: {emitted}"
  );
  assert!(
    !emitted.contains("ToDatabaseComparison<Roll,"),
    "the map row stays absent exactly as it always was: {emitted}"
  );
  assert!(
    !emitted.contains("implcore::default::Default"),
    "and `Default` does not ship alone: {emitted}"
  );
}

/// **THE NAMED LOOP GAINS THE PAIR TOO, UNDER THE SAME HOOK** — this knife's own deliverable:
/// `Default` and `TryFromFilter<RollFilter>` for `RollSqliteComparison<DB>`, both at a parameter,
/// both through `ToCrossedComparison` — the SAME shape
/// [`the_bare_comparison_gains_the_pair_under_a_hook`] pins for the bare arm, read here off a
/// declaration that names ONE database.
#[test]
fn the_named_comparison_gains_the_pair_under_a_hook() {
  let mut model = roll();
  model.databases = vec![DatabaseKind::Sqlite];
  let emitted = dense_of(&model.emit_comparison());

  assert!(
    emitted.contains("::core::default::DefaultforRollSqliteComparison<__INGRAPH_DB__>where"),
    "the empty predicate, at a parameter, for the NAMED comparison: {emitted}"
  );
  assert!(
    emitted.contains("TryFromFilter<RollFilter>forRollSqliteComparison<__INGRAPH_DB__>where"),
    "the crossing, named from the hook rather than from this door's own minted filter: {emitted}"
  );
  assert!(
    emitted.contains("ToCrossedComparison<u32,__INGRAPH_DB__,>"),
    "the scalar column's own row — no per-database override written here, so the DOMAIN type: \
     {emitted}"
  );
  assert!(
    emitted.contains("ToCrossedComparison<String,__INGRAPH_DB__,>"),
    "and the string column's: {emitted}"
  );
  // The pair is new tokens BESIDE `one_comparison`'s own emission, never instead of it — the map row
  // the hook already bought is exactly what it was.
  assert!(
    emitted.contains("ToDatabaseComparison<Roll"),
    "the pre-existing map row survives untouched: {emitted}"
  );
}

/// **NO HOOK, NO PAIR — AT A NAMED DATABASE EXACTLY AS AT NONE.**
/// [`a_bare_comparison_with_no_hook_gains_nothing`]'s own pin, read at a database this declaration
/// named: the gate is the HOOK, never bareness, so naming a database changes nothing about what an
/// absent hook buys.
#[test]
fn a_named_comparison_with_no_hook_gains_nothing() {
  let mut model = roll();
  model.databases = vec![DatabaseKind::Sqlite];
  model.hook = None;
  let emitted = dense_of(&model.emit_comparison());

  assert!(
    !emitted.contains("TryFromFilter"),
    "no crossing without a seat to cross from, named database or not: {emitted}"
  );
  assert!(
    !emitted.contains("ToCrossedComparison"),
    "the new machinery is unreached: {emitted}"
  );
  assert!(
    !emitted.contains("ToDatabaseComparison<Roll,"),
    "the map row stays absent exactly as it always was: {emitted}"
  );
  assert!(
    !emitted.contains("implcore::default::Default"),
    "and `Default` does not ship alone: {emitted}"
  );
}

/// **THE PER-DATABASE STORED-TYPE OVERRIDE IS WHAT THE NAMED PAIR CROSSES THROUGH** — the token-level
/// half of this knife's own measurement (the compiled half lives at
/// `ingraph/tests/standalone_named_crossing.rs`, over TWO declarations rather than one naming both
/// databases — see that file's own module doc for why): one model, two named databases, one column,
/// two DIFFERENT `type = "…"` overrides, and the crossing at EACH database names THAT database's own
/// stored type rather than the domain the two share. `emit_comparison`'s two branches never share a
/// body, so what a hand-built model with two `databases` entries emits per branch is what a real
/// declaration with a database apiece would emit too — this reads both branches from ONE model only
/// because that is cheaper to construct, not because the two databases share anything at runtime.
#[test]
fn the_named_pair_crosses_through_the_per_database_stored_override() {
  let mut model = roll();
  model.databases = vec![DatabaseKind::Sqlite, DatabaseKind::Postgres];
  model.columns = vec![StandaloneColumn {
    stored: vec![
      StandaloneStored {
        ty: Some(syn::parse_str("i64").expect("a type")),
        flatten: false,
      },
      StandaloneStored {
        ty: Some(syn::parse_str("i32").expect("a type")),
        flatten: false,
      },
    ],
    ..column("width", "u32")
  }];
  let emitted = dense_of(&model.emit_comparison());

  assert!(
    emitted.contains("TryFromFilter<RollFilter>forRollSqliteComparison<__INGRAPH_DB__>where"),
    "the SQLite arm gets the pair: {emitted}"
  );
  assert!(
    emitted.contains("ToCrossedComparison<i64,__INGRAPH_DB__,>"),
    "…crossing through ITS OWN override, `i64`, not the shared `u32` domain: {emitted}"
  );
  assert!(
    emitted.contains("TryFromFilter<RollFilter>forRollPostgresComparison<__INGRAPH_DB__>where"),
    "the Postgres arm gets the pair too: {emitted}"
  );
  assert!(
    emitted.contains("ToCrossedComparison<i32,__INGRAPH_DB__,>"),
    "…crossing through ITS OWN override, `i32` — a DIFFERENT stored type from SQLite's, at the SAME \
     declared column: {emitted}"
  );
  // The domain type never appears as a crossing's own `V` here: every row names a STORED type, and
  // neither database's stored type happens to be the domain.
  assert!(
    !emitted.contains("ToCrossedComparison<u32,"),
    "the override is what crosses, not the domain underneath it: {emitted}"
  );
}

/// **A `flatten` COLUMN AT A NAMED DATABASE STATES ONE BOUND MORE** —
/// [`StandaloneModel::crossings`]'s own doc: the `ToCrossedComparison` row is what `cross`/`empty`
/// need, and a `flatten` column ALSO needs [`StandaloneModel::assumptions`]'s own
/// `ToFlattenedComparison` row restated here, because [`StandaloneModel::one_comparison`]'s
/// `Self::new` demands it and `ToCrossedComparison` does not entail it — the two are SIBLING
/// refinements of the same map, neither implying the other.
#[test]
fn a_flatten_column_at_a_named_database_states_both_bounds() {
  let model = StandaloneModel {
    columns: vec![StandaloneColumn {
      stored: vec![StandaloneStored {
        ty: Some(syn::parse_str("i64").expect("a type")),
        flatten: true,
      }],
      ..column("width", "u32")
    }],
    databases: vec![DatabaseKind::Sqlite],
    ..roll()
  };
  let clause = tight(model.crossings(&ident("__INGRAPH_DB__"), Some(0)));

  assert!(
    clause.contains("ToCrossedComparison<i64,__INGRAPH_DB__>,"),
    "the crossing itself, through the override — what `cross`/`empty` need: {clause}"
  );
  assert!(
    clause.contains("ToFlattenedComparison<i64,__INGRAPH_DB__>,"),
    "…and the flattened row beside it, which `Self::new`'s own clause still demands: {clause}"
  );
}

/// **A `flatten` COLUMN CANNOT REACH THE BARE ARM AT ALL** — `flatten` lives on a PER-DATABASE
/// [`StandaloneStored`] entry, and the bare arm reads every column at `at = None`, which is exactly
/// what `StandaloneModel`'s own `stored` helper short-circuits to absent. Recorded as a compile-level
/// fact rather than as a runtime assertion: there is no field to set that would make a bare column
/// flatten, so this test is the closest a value-level suite gets to pinning the absence — a column
/// with a `stored` entry attached anyway, which the bare arm must ignore.
#[test]
fn a_stored_entry_on_a_bare_column_is_inert() {
  let mut model = roll();
  model.columns = vec![StandaloneColumn {
    stored: vec![StandaloneStored {
      ty: Some(syn::parse_str("i64").expect("a type")),
      flatten: true,
    }],
    ..column("width", "u32")
  }];
  let emitted = dense_of(&model.emit_comparison());
  // The stored override names `i64` and would show up in a `ToCrossedComparison<i64, …>` row were
  // it read; the bare arm reads the DOMAIN instead, so only `u32` appears.
  assert!(
    emitted.contains("ToCrossedComparison<u32,"),
    "the domain type, not the inert per-database override: {emitted}"
  );
  assert!(
    !emitted.contains("ToCrossedComparison<i64,"),
    "a `stored` entry with no named database to select it is never read: {emitted}"
  );
}