ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! THE BONE RENAME — the top-level `rename` word, and the roster that proves it reached everything.
//!
//! Beside [`audits`](super::audits) rather than inside it, on this crate's one-file-per-thing
//! precedent: the audits prove the roster names what the emission declares, and this file proves
//! that a rename moves BOTH of them together. The two claims are separable and a reader looking for
//! either should not have to read the other.
//!
//! # Why the roster IS the proof
//!
//! A rename could reach the emission and miss the enumeration the front end's collision refusals are
//! measured against, and nothing would fail: the declaration would compile and its refusals would be
//! about names it no longer mints. So every claim here is stated over BOTH — the module-scope items
//! the expansion actually lands, and `emitted_types`' answer — and the two are compared to each
//! other rather than each to a list written here.
//!
//! # What a rename must NOT move
//!
//! Three things, and each has a claim of its own: the author's own struct name, which is their item
//! in their file; the DURABLE slot name, which is a storage identity and would silently repoint a
//! live corpus; and the SDL, which is the other axis entirely.

use super::{
  Dedup, Elected, ElectionLabel, IndexGraphql, IndexModel, IndexRename, Projected, RenamePiece,
  Upstream,
};
use crate::{
  engine::{Engine, FieldEngines},
  model::{Column, GraphqlKind, NodeKind, Projection},
  prefix::EmissionPrefix,
};

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

/// A VECTOR declaration electing TWO fields onto one engine — the shape that mints the widest
/// family: two election markers, two slot markers, two slot packages apiece, and the multi-route
/// pair over them.
fn frames(rename: Option<IndexRename>) -> IndexModel {
  let field = |name: &str| Column {
    project: Projection::Borrowed,
    ty: syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
    source: ident(name),
    name: ident(name),
  };
  let elected = |name: &str| {
    Elected::new(
      ident(name),
      ElectionLabel::Embedding,
      syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
      None,
    )
  };
  let engines = |name: &str| FieldEngines {
    field: ident(name),
    engines: vec![Engine::bare(ident("lance"))],
    fanout: false,
  };
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    index: ident("Frames"),
    kind: NodeKind::Vector,
    vis: syn::parse_quote!(pub),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(Keyframe),
      projections: vec![
        Projected {
          field: ident("clip"),
          from: ident("clip"),
          ty: syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
        },
        Projected {
          field: ident("poster"),
          from: ident("poster"),
          ty: syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
        },
      ],
    },
    dedup: Dedup::Hash,
    embeddings: vec![elected("clip"), elected("poster")],
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: vec![engines("clip"), engines("poster")],
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql: None,
    rename,
    slot: None,
    fields: vec![field("clip"), field("poster")],
  }
}

/// EVERY TYPE the whole expansion lands at MODULE SCOPE, by name — the markers and the packages,
/// which is where every name a declaring scope can spell lives.
fn landed(model: &IndexModel) -> Vec<String> {
  let file: syn::File = syn::parse2(model.emit()).expect("the emission parses");
  file
    .items
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Struct(declared) => Some(declared.ident.to_string()),
      syn::Item::Enum(declared) => Some(declared.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// The roster the front end's collision refusals are measured against.
fn rostered(model: &IndexModel) -> Vec<String> {
  model
    .emitted_types()
    .iter()
    .map(|declared| declared.name.to_string())
    .collect()
}

#[test]
fn a_base_rename_moves_every_minted_name_and_the_roster_with_it() {
  let renamed = frames(Some(IndexRename::Base(ident("ShotSearch"))));
  let plain = frames(None);

  // BOTH SIDES MOVE TOGETHER. Compared to each other rather than to a list, so a mint added later is
  // covered without anybody remembering to add it here.
  assert_eq!(landed(&renamed), rostered(&renamed));
  assert_eq!(landed(&plain), rostered(&plain));

  // AND THEY MOVED. Every name is the new base plus the segment it always carried.
  assert_eq!(
    landed(&renamed),
    landed(&plain)
      .iter()
      .map(|name| name.replacen("Frames", "ShotSearch", 1))
      .collect::<Vec<_>>(),
  );
  assert!(
    !landed(&renamed).is_empty(),
    "the fixture mints a family for the claim to be about",
  );
}

#[test]
fn the_authors_own_struct_name_never_moves() {
  let renamed = frames(Some(IndexRename::Base(ident("ShotSearch"))));
  let said = renamed.emit().to_string();
  // The declaration is the author's item in the author's file, so every impl the expansion writes
  // is still `for Frames`. A rename that took the struct with it would rename somebody's code.
  assert!(said.contains("for Frames"), "the impls still name the item");
  assert!(
    !landed(&renamed).iter().any(|name| name == "ShotSearch"),
    "and the base is a STEM rather than a type: {:?}",
    landed(&renamed),
  );
}

#[test]
fn the_durable_slot_name_never_moves_with_a_rust_rename() {
  // THE ASYMMETRY THE EMITTER STATES OUT LOUD. A slot's marker is a Rust type and moves; the slot's
  // durable NAME is the corpus that pairing owns, and a Rust word repointing it would silently
  // address a different index.
  let renamed = frames(Some(IndexRename::Base(ident("ShotSearch"))))
    .emit()
    .to_string();
  let plain = frames(None).emit().to_string();
  for durable in ["frames__clip__lance", "frames__poster__lance"] {
    assert!(plain.contains(durable), "the fixture names its corpora");
    assert!(
      renamed.contains(durable),
      "`{durable}` moved with a Rust rename",
    );
  }
  assert!(
    renamed.contains("ShotSearchClipLance"),
    "and the MARKER did move",
  );
}

#[test]
fn a_piece_rename_names_that_mint_and_leaves_the_rest_alone() {
  let renamed = frames(Some(IndexRename::Pieces(vec![
    (RenamePiece::FuseOptions, ident("ShotKnobs")),
    (RenamePiece::Evidence, ident("WhoAgreed")),
  ])));
  let names = landed(&renamed);
  assert!(names.iter().any(|name| name == "ShotKnobs"), "{names:?}");
  assert!(names.iter().any(|name| name == "WhoAgreed"), "{names:?}");
  assert!(
    !names.iter().any(|name| name == "FramesFuseOptions"),
    "the named mint is gone from the scope: {names:?}",
  );
  assert!(
    names.iter().any(|name| name == "FramesFuseQuestion"),
    "and every mint the block did not name keeps the declaration's own: {names:?}",
  );
  assert_eq!(names, rostered(&renamed), "the roster moved with it");
}

#[test]
fn the_two_axes_compose_and_neither_reads_the_other() {
  // A declaration that renames BOTH: the Rust family is `ShotSearch…` and the schema is `WireFace…`.
  // Nothing in either answer is built from the other's word, which is the axis law's whole content.
  let mut model = frames(Some(IndexRename::Base(ident("ShotSearch"))));
  let mut skin = crate::index::IndexBackend::of(GraphqlKind::AsyncGraphql);
  skin.prefix = Some(syn::LitStr::new("wireFace", proc_macro2::Span::call_site()));
  model.graphql = Some(IndexGraphql {
    backends: vec![skin],
  });
  let said = model.emit().to_string();
  assert!(
    landed(&model)
      .iter()
      .all(|name| name.starts_with("ShotSearch")),
    "the Rust family is the BONE word's: {:?}",
    landed(&model),
  );
  assert!(
    said.contains("\"WireFaceFuseOptions\""),
    "and the schema is the SKIN word's",
  );
  assert!(
    !said.contains("\"ShotSearchFuseOptions\""),
    "with no Rust name reaching the schema",
  );
}

#[test]
fn an_artifact_family_mints_no_type_for_a_rename_to_move() {
  // THE MEASUREMENT the blob's own verdict rests on, pinned where it can change: this kind lands no
  // package, no vocabulary and no marker — its engines are at the head, so it has no `(field ×
  // engine)` slot, and it elects nothing, so it has no election. The day it mints one, this fails.
  let mut blob = frames(None);
  blob.kind = NodeKind::Blob;
  blob.embeddings = Vec::new();
  blob.engines = Vec::new();
  blob.stores = vec![Engine::bare(ident("fs"))];
  assert!(blob.emitted_types().is_empty());
  assert!(landed(&blob).is_empty(), "{:?}", landed(&blob));
}

#[test]
fn the_slot_word_reaches_the_durable_name_and_the_default_stands() {
  // THE ONE WORD IN THIS GRAMMAR THAT REACHES A DEPLOYMENT'S DISK. The default is the convention
  // every family already stored under, so the word is additive: writing it moves the corpus, and
  // leaving it out moves nothing.
  let mut blob = frames(None);
  blob.kind = NodeKind::Blob;
  blob.index = ident("PosterFrame");
  blob.embeddings = Vec::new();
  blob.engines = Vec::new();
  blob.stores = vec![Engine::bare(ident("fs"))];

  let default = blob.emit().to_string();
  assert!(
    default.contains("\"poster_frame\""),
    "the default is `snake_case(<declaration name>)`",
  );

  blob.slot = Some(syn::LitStr::new(
    "archive_2019",
    proc_macro2::Span::call_site(),
  ));
  let named = blob.emit().to_string();
  assert!(named.contains("\"archive_2019\""), "{named}");
  assert!(
    !named.contains("\"poster_frame\""),
    "one family lives in ONE place: {named}",
  );
}