use quote::ToTokens as _;
use crate::{
engine::{Engine, FieldEngines},
index::{Dedup, Elected, ElectionLabel, IndexGraphql, IndexModel, Upstream},
model::{GraphqlKind, NodeKind},
prefix::EmissionPrefix,
};
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn index(name: &str, kind: NodeKind) -> IndexModel {
IndexModel {
prefix: EmissionPrefix::default(),
numbers: crate::index::Numbers::default(),
field_numbers: Vec::new(),
index: ident(name),
kind,
vis: syn::parse_quote!(pub),
krate: syn::parse_quote!(::ingraph),
source: Upstream {
node: syn::parse_quote!(Caption),
projections: Vec::new(),
},
dedup: Dedup::Hash,
embeddings: Vec::new(),
labelled: Vec::new(),
searchable: Vec::new(),
engines: Vec::new(),
stores: Vec::new(),
extension: None,
data: false,
keys: false,
subscribe: false,
graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
rename: None,
slot: None,
fields: Vec::new(),
}
}
fn fulltext() -> IndexModel {
let mut model = index("Transcript", NodeKind::Fulltext);
model.searchable = vec![ident("body"), ident("title")];
model.engines = vec![
FieldEngines {
field: ident("body"),
engines: vec![Engine::bare(ident("tantivy"))],
fanout: false,
},
FieldEngines {
field: ident("title"),
engines: vec![Engine::bare(ident("tantivy"))],
fanout: false,
},
];
model
}
fn one_slot() -> IndexModel {
let mut model = index("Captions", NodeKind::Vector);
model.embeddings = vec![Elected::new(
ident("image_embedding"),
ElectionLabel::Embedding,
syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
None,
)];
model.engines = vec![FieldEngines {
field: ident("image_embedding"),
engines: vec![Engine::bare(ident("hnsw"))],
fanout: false,
}];
model
}
fn blob() -> IndexModel {
let mut model = index("Posters", NodeKind::Blob);
model.stores = vec![Engine::bare(ident("fs"))];
model
}
fn emission(model: &IndexModel) -> syn::File {
syn::parse2(model.tier().emit()).expect("the tier emission is a parsable file")
}
fn vocabulary(model: &IndexModel, name: &str) -> Option<syn::ItemEnum> {
emission(model)
.items
.into_iter()
.find_map(|item| match item {
syn::Item::Enum(declared) if declared.ident == name => Some(declared),
_ => None,
})
}
fn enums(model: &IndexModel) -> Vec<String> {
emission(model)
.items
.into_iter()
.filter_map(|item| match item {
syn::Item::Enum(declared) => Some(declared.ident.to_string()),
_ => None,
})
.collect()
}
fn rows(model: &IndexModel, name: &str) -> Vec<String> {
emission(model)
.items
.into_iter()
.find_map(|item| match item {
syn::Item::Struct(declared) if declared.ident == name => Some(declared),
_ => None,
})
.expect("the package is emitted")
.fields
.iter()
.map(|field| {
format!(
"{}: {}",
field.ident.as_ref().expect("a named field"),
field.ty.to_token_stream().to_string().replace(' ', ""),
)
})
.collect()
}
#[test]
fn the_vocabulary_is_the_elected_fields_in_declared_order() {
let minted = vocabulary(&fulltext(), "TranscriptColumn").expect("the vocabulary is emitted");
assert_eq!(
minted
.variants
.iter()
.map(|variant| variant.ident.to_string())
.collect::<Vec<_>>(),
["Body", "Title"],
"one variant per election, in the order the declaration wrote them",
);
}
#[test]
fn every_variant_translates_to_its_own_column_at_one_point() {
let file = emission(&fulltext());
let translations: Vec<syn::ImplItemFn> = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Impl(declared) if declared.trait_.is_none() => Some(declared),
_ => None,
})
.flat_map(|declared| declared.items.iter())
.filter_map(|inner| match inner {
syn::ImplItem::Fn(method) if method.sig.ident == "column" => Some(method.clone()),
_ => None,
})
.collect();
assert_eq!(
translations.len(),
1,
"the vocabulary translates at exactly ONE function; two would be two places to learn a \
different answer",
);
let body = translations[0]
.block
.to_token_stream()
.to_string()
.replace(' ', "");
for (variant, column, other) in [("Body", "body", "title"), ("Title", "title", "body")] {
let arm = body
.split(&format!("Self::{variant}=>"))
.nth(1)
.map(|rest| rest.split("Self::").next().unwrap_or(rest).to_owned())
.unwrap_or_else(|| panic!("`{variant}` has an arm: {body}"));
assert!(
arm.contains(&format!("FulltextColumn::new(\"{column}\")")),
"`{variant}` names `{column}`: {arm}",
);
assert!(
!arm.contains(&format!("\"{other}\"")),
"and never the other election's: {arm}",
);
}
}
#[test]
fn the_translation_is_const_and_takes_the_variant_by_value() {
let file = emission(&fulltext());
let method = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Impl(declared) if declared.trait_.is_none() => Some(declared),
_ => None,
})
.flat_map(|declared| declared.items.iter())
.find_map(|inner| match inner {
syn::ImplItem::Fn(method) if method.sig.ident == "column" => Some(method.clone()),
_ => None,
})
.expect("the translation is emitted");
assert!(method.sig.constness.is_some(), "`column` is `const`");
let receiver = method
.sig
.inputs
.first()
.expect("`column` takes a receiver")
.to_token_stream()
.to_string();
assert_eq!(
receiver, "self",
"`column` takes `self` by value, not by reference: {receiver}",
);
}
#[test]
fn the_wire_words_are_screaming_snake() {
let mut model = fulltext();
model.searchable = vec![ident("spoken_labels"), ident("title")];
let said = model.tier().emit().to_string();
assert!(
said.contains("\"SPOKEN_LABELS\""),
"a multi-word field screams with its underscores kept: {said}",
);
assert!(said.contains("\"TITLE\""), "{said}");
assert!(
!said.contains("\"spokenLabels\""),
"and the input-object casing does not leak onto an enum: {said}",
);
}
#[test]
fn two_fields_spelling_one_variant_are_refused_by_name() {
let mut model = fulltext();
model.searchable = vec![ident("spoken_labels"), ident("spokenLabels")];
let said = model.tier().emit().to_string();
assert!(said.contains("compile_error"), "it is refused: {said}");
assert!(said.contains("spoken_labels"), "naming the first: {said}");
assert!(said.contains("spokenLabels"), "and the second: {said}");
assert!(
said.contains("SpokenLabels"),
"and the variant they collide on: {said}",
);
}
#[test]
fn the_package_carries_a_columns_row_over_this_tier_s_own_vocabulary() {
assert_eq!(
rows(&fulltext(), "TranscriptFulltextOptions"),
["columns: ::core::option::Option<::std::vec::Vec<TranscriptColumn>>"],
"the de-Option law holds over the new row too: absent means the declaration's own subject",
);
}
#[test]
fn a_vector_tier_mints_no_column_vocabulary() {
assert!(
!enums(&one_slot())
.iter()
.any(|minted| minted.ends_with("Column")),
"a vector tier's enums are its fold vocabularies alone: {:?}",
enums(&one_slot()),
);
assert!(
!rows(&one_slot(), "CaptionsImageEmbeddingVectorOptions")
.iter()
.any(|row| row.starts_with("columns:")),
"and no vector package grows a column subset",
);
}
#[test]
fn a_blob_family_mints_no_column_vocabulary() {
assert!(
blob().tier().emit().is_empty(),
"the kind that does not retrieve emits no package and no vocabulary",
);
}
#[test]
fn no_election_mints_no_vocabulary_and_no_row() {
let mut model = fulltext();
model.searchable = Vec::new();
assert!(
!enums(&model)
.iter()
.any(|minted| minted == "TranscriptColumn"),
"no elected field, no vocabulary: {:?}",
enums(&model),
);
assert_eq!(
rows(&model, "TranscriptFulltextOptions"),
[] as [&str; 0],
"and the package carries no row at all",
);
}