ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! WHAT THE CONVERSION GRAMMAR SPENDS — one `FulltextRoad` impl per full-text slot, and the demand
//! that lands on a `searchable` field with no engine at all.
//!
//! Beside [`engines`](super::engines) rather than inside it, on that file's own precedent: one file
//! per thing being proved. What a declaration MEANS by `join = ", "` is `ingraph-derive`'s
//! `index/roads.rs`; whether the two builtins actually segment differently is `ingraph`'s.
//!
//! # The claim these tests exist for
//!
//! `searchable`'s check is *A FROM-ROAD EXISTS*, and it is spent HERE — there is no other place it
//! could be, the front end having no type to check. So every test below is about the emission
//! carrying a DEMAND: the right call, at the right span, for every road, including the portable case
//! that has no slot to hang one on. An emission that dropped the demand would still pass a suite
//! that only counted impls.

use super::{Dedup, IndexGraphql, IndexModel, Projected, Upstream};
use crate::{
  engine::{Engine, FieldEngines, Road},
  model::{Column, Conversion, GraphqlKind, NodeKind, Projection},
  prefix::EmissionPrefix,
};

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

fn column(name: &str, ty: &str) -> Column {
  Column {
    name: ident(name),
    source: ident(name),
    ty: syn::parse_str(ty).expect("a type"),
    project: Projection::Borrowed,
  }
}

fn projected(field: &str, ty: &str) -> Projected {
  Projected {
    field: ident(field),
    from: ident(field),
    ty: syn::parse_str(ty).expect("a type"),
  }
}

/// A full-text declaration over ONE searched field, holding whatever engine blocks a test hands it.
fn document(engines: Vec<Engine>) -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    index: ident("SearchDocument"),
    kind: NodeKind::Fulltext,
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(asr::Segment),
      projections: vec![projected("labels", "Vec<String>")],
    },
    dedup: Dedup::Hash,
    embeddings: Vec::new(),
    labelled: Vec::new(),
    searchable: vec![ident("labels")],
    engines: vec![FieldEngines {
      field: ident("labels"),
      engines,
      fanout: false,
    }],
    fields: vec![column("labels", "Vec<String>")],
  }
}

/// One `tantivy` block carrying `road`, and keeping the value or not.
fn tantivy(road: Road, stored: bool) -> Engine {
  Engine {
    road,
    stored,
    ..Engine::bare(ident("tantivy"))
  }
}

/// The whole expansion with the spaces taken out — what a claim about a CALL is read off.
fn tight(model: &IndexModel) -> String {
  model.emit().to_string().replace(' ', "")
}

#[test]
fn every_slot_gets_its_own_road_impl() {
  let model = document(vec![
    tantivy(Road::Multi, false),
    Engine {
      road: Road::Join(syn::parse_quote!(", ")),
      ..Engine::bare(ident("fts5"))
    },
  ]);
  let emitted = tight(&model);
  assert!(
    emitted.contains("FulltextRoadforSearchDocumentLabelsTantivy"),
    "{emitted}"
  );
  assert!(
    emitted.contains("FulltextRoadforSearchDocumentLabelsFts5"),
    "{emitted}"
  );
}

/// THE DEFAULT REACHES THE CONSTANT. Stated as a pair, because a `const STORED` that was always
/// `false` would pass an assertion about the default alone.
#[test]
fn the_stored_word_is_the_slot_s_own_constant() {
  let plain = tight(&document(vec![tantivy(Road::Identity, false)]));
  let kept = tight(&document(vec![tantivy(Road::Identity, true)]));
  assert!(plain.contains("constSTORED:bool=false"), "{plain}");
  assert!(kept.contains("constSTORED:bool=true"), "{kept}");
}

/// THE IDENTITY ROAD IS A DEMAND, and this is the test that `searchable`'s check exists at all: the
/// emission names `Searchable` over the field, so a field that is not text is `E0277` here.
#[test]
fn a_road_that_was_not_declared_demands_the_field_be_text() {
  let emitted = tight(&document(vec![tantivy(Road::Identity, false)]));
  assert!(
    emitted.contains("Searchable::write(&entry.labels,into)"),
    "{emitted}"
  );
}

#[test]
fn the_two_shorthands_emit_the_two_builtins_and_not_one_of_them_twice() {
  let joined = tight(&document(vec![tantivy(
    Road::Join(syn::parse_quote!(" / ")),
    false,
  )]));
  let each = tight(&document(vec![tantivy(Road::Multi, false)]));
  assert!(
    joined.contains("BoxWriter::push_joined(into,&entry.labels,\"/\")"),
    "{joined}"
  );
  assert!(
    each.contains("BoxWriter::push_each(into,&entry.labels)"),
    "{each}"
  );
  assert!(
    !joined.contains("push_each"),
    "the joined road does not also push each: {joined}"
  );
  assert!(
    !each.contains("push_joined"),
    "nor the other way round: {each}"
  );
}

/// THE SINK COMES FIRST. The declared converter's signature is `fn(&mut BoxWriter, &Field)` and not
/// the record side's one-argument shape, because a road that RETURNED its text would collapse the
/// segmentation the whole grammar is about.
#[test]
fn a_declared_conversion_is_called_with_the_sink_first() {
  let model = document(vec![tantivy(
    Road::Declared(Conversion::Infallible(syn::parse_quote!(text::render))),
    false,
  )]);
  let emitted = tight(&model);
  assert!(
    emitted.contains("text::render(into,&entry.labels)"),
    "{emitted}"
  );
  assert!(
    emitted.contains("Error=::core::convert::Infallible"),
    "an infallible road names the type that says so: {emitted}"
  );
}

#[test]
fn a_fallible_conversion_takes_the_question_mark_and_the_boxed_refusal() {
  let model = document(vec![tantivy(
    Road::Declared(Conversion::Fallible(crate::model::FallibleConversion {
      path: syn::parse_quote!(text::try_render),
      escape: None,
    })),
    false,
  )]);
  let emitted = tight(&model);
  assert!(
    emitted.contains("text::try_render(into,&entry.labels)?"),
    "{emitted}"
  );
  assert!(emitted.contains("Box<dyn::core::error::Error"), "{emitted}");
}

#[test]
fn a_declared_escape_maps_the_error_at_the_crossing() {
  let model = document(vec![tantivy(
    Road::Declared(Conversion::Fallible(crate::model::FallibleConversion {
      path: syn::parse_quote!(text::try_render),
      escape: Some(syn::parse_quote!(text::wrap)),
    })),
    false,
  )]);
  let emitted = tight(&model);
  assert!(
    emitted.contains("map_err(text::try_render(into,&entry.labels),text::wrap)?"),
    "{emitted}"
  );
}

/// THE PORTABLE CASE. An election naming no engine has no slot, so there is no impl for the demand
/// to ride — and without this it would be the ONE declaration shape where `searchable` is unchecked.
#[test]
fn a_field_that_named_no_engine_is_still_held_to_a_road() {
  let emitted = tight(&document(Vec::new()));
  assert!(
    !emitted.contains("FulltextRoadforSearchDocument"),
    "there is no slot to implement it on: {emitted}"
  );
  assert!(
    emitted.contains("Searchable::write(&entry.labels,into)"),
    "and the demand is emitted anyway: {emitted}"
  );
}

/// WHERE THE SPAN CLAIM IS NOT MADE, and why. The demand is emitted through `quote_spanned` at the
/// field's own type, which is where flag B asked the refusal to land — and there is NO unit
/// assertion of that here, deliberately.
///
/// `proc-macro2`'s fallback `Debug for Span` renders the constant `"Span"` unless `span-locations`
/// is on, and it is on nowhere in this workspace: a span equation written here would compare
/// `"Span"` against `"Span"` and pass for any emitter at all. That is a measured defect of an
/// existing test in this repo (`ingraph-derive`'s
/// `a_projection_is_spanned_at_the_string_that_named_it`), and repeating it would be minting a
/// second one.
///
/// The claim is carried by `ingraph`'s trybuild golden instead —
/// `tests/roads/a_searchable_field_reaches_the_document_by_one_of_three_roads.stderr` — which is the
/// only place a span is observable at all, because it is the only place a real invocation happens.
#[test]
fn the_span_claim_lives_in_a_golden_and_not_here() {
  let emitted = tight(&document(vec![tantivy(Road::Identity, false)]));
  assert!(emitted.contains("Searchable::write"), "{emitted}");
}

/// A VECTOR declaration emits NO road at all, and the absence is structural rather than a filter
/// somebody remembered: a knn indexes coordinates, which have no document to be the text of.
#[test]
fn a_kind_that_indexes_no_text_emits_no_road() {
  let mut model = document(vec![tantivy(Road::Identity, false)]);
  model.kind = NodeKind::Vector;
  model.searchable = Vec::new();
  let emitted = tight(&model);
  assert!(!emitted.contains("FulltextRoad"), "{emitted}");
  assert!(!emitted.contains("Searchable"), "{emitted}");
}