use heck::{ToLowerCamelCase as _, ToShoutySnakeCase as _, ToUpperCamelCase as _};
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;
use crate::{
emit::{framework, leading, substrate},
engine::FieldEngines,
index::{Elected, Fold, IndexGraphql, IndexModel, IndexRename, RenamePiece},
model::{GraphqlKind, NodeKind},
};
#[cfg(test)]
mod columns;
#[cfg(test)]
mod doors;
#[cfg(test)]
mod engines;
#[cfg(test)]
mod fanned;
#[cfg(test)]
mod skins;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy)]
pub struct Tier<'a> {
pub krate: &'a syn::Path,
pub vis: &'a syn::Visibility,
pub index: &'a syn::Ident,
pub kind: NodeKind,
pub embeddings: &'a [Elected],
pub searchable: &'a [syn::Ident],
pub engines: &'a [FieldEngines],
pub field_numbers: &'a [crate::index::FieldNumbers],
pub graphql: Option<&'a IndexGraphql>,
pub rename: Option<&'a IndexRename>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Doors {
pub fulltext: bool,
pub vector: bool,
pub mixed: bool,
}
impl Doors {
#[must_use]
pub const fn of(fulltext: usize, vector: usize) -> Self {
Self {
fulltext: fulltext >= 2,
vector: vector >= 2,
mixed: fulltext >= 1 && vector >= 1,
}
}
#[must_use]
pub const fn any(self) -> bool {
self.fulltext || self.vector || self.mixed
}
}
#[derive(Debug)]
pub struct Row {
member: syn::Ident,
wire: String,
ty: proc_macro2::TokenStream,
noun: String,
crosses: bool,
}
#[must_use]
pub fn score_param(field: &syn::Ident) -> syn::Ident {
format_ident!(
"__INGRAPH_SCORE_{}__",
field.to_string().to_shouty_snake_case()
)
}
#[must_use]
pub fn engine_param(field: &syn::Ident) -> syn::Ident {
format_ident!(
"__INGRAPH_ENGINE_{}__",
field.to_string().to_shouty_snake_case()
)
}
#[must_use]
pub fn error_param(field: &syn::Ident) -> syn::Ident {
format_ident!(
"__INGRAPH_ERROR_{}__",
field.to_string().to_shouty_snake_case()
)
}
fn spelled(path: Option<&syn::Path>) -> String {
path.map_or_else(String::new, |path| {
quote!(#path).to_string().replace(' ', "")
})
}
fn collision(rows: &[Row]) -> Option<String> {
let mut seen = std::collections::HashSet::new();
rows
.iter()
.find(|row| !seen.insert(row.member.to_string()))
.map(|row| row.member.to_string())
}
impl Row {
#[must_use]
pub fn new(member: &syn::Ident, ty: proc_macro2::TokenStream, noun: &str) -> Self {
Self {
wire: member.to_string().to_lower_camel_case(),
member: member.clone(),
ty,
noun: noun.to_owned(),
crosses: true,
}
}
#[must_use]
pub fn rust_side(mut self) -> Self {
self.crosses = false;
self
}
}
impl<'a> Tier<'a> {
#[must_use]
pub fn emit(&self) -> proc_macro2::TokenStream {
match self.kind {
NodeKind::Fulltext => self.fulltext(),
NodeKind::Vector => self.vector(),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => proc_macro2::TokenStream::new(),
}
}
#[must_use]
pub fn emitted_methods(&self) -> Vec<(syn::Ident, syn::Ident)> {
let package = |on: &syn::Ident, members: &[syn::Ident]| {
let mut methods = vec![(on.clone(), format_ident!("new"))];
for member in members {
methods.push((on.clone(), format_ident!("with_{member}")));
methods.push((on.clone(), member.clone()));
}
methods
};
match self.kind {
NodeKind::Fulltext => {
let mut methods = Vec::new();
let mut rows: Vec<syn::Ident> = Vec::new();
if !self.searchable.is_empty() {
methods.push((self.column_name(), format_ident!("column")));
}
let typed = self.fulltext_typed().unwrap_or_default();
for engine in &typed {
methods.extend(package(
&self.engine_input(self.base(), engine),
&[format_ident!("floor"), format_ident!("options")],
));
}
if !typed.is_empty() {
rows.push(format_ident!("engine"));
}
if !self.searchable.is_empty() {
rows.push(format_ident!("columns"));
}
let options = self.fulltext_options_name();
let asked = self.fulltext_question_name();
methods.extend(package(&options, &rows));
methods.extend(package(&asked, &[format_ident!("question")]));
methods
}
NodeKind::Vector => {
let mut methods = Vec::new();
for elected in self.embeddings {
if elected.label.is_set() {
methods.push((self.semantics_name(elected), format_ident!("with_fold")));
}
if self.fanned(elected) {
let mut rows = vec![format_ident!("fusion")];
let stem = self.stem(elected);
let typed = self.typed(elected);
for engine in &typed {
methods.extend(package(
&self.engine_input(&stem, engine),
&[format_ident!("floor")],
));
}
if !typed.is_empty() {
rows.push(format_ident!("engine"));
}
if elected.label.is_set() {
rows.push(format_ident!("semantics"));
}
for engine in self.participants(elected) {
let leg = self.leg_options(elected, engine);
methods.extend(package(&leg, &[]));
rows.push(engine.word.clone());
}
methods.extend(package(&self.slot_options(elected), &rows));
} else {
let mut rows: Vec<syn::Ident> = Vec::new();
let stem = self.stem(elected);
let typed = self.typed(elected);
for engine in &typed {
methods.extend(package(
&self.engine_input(&stem, engine),
&[format_ident!("floor"), format_ident!("options")],
));
}
if !typed.is_empty() {
rows.push(format_ident!("engine"));
}
if elected.label.is_set() {
rows.push(format_ident!("semantics"));
}
methods.extend(package(&self.slot_options(elected), &rows));
}
methods.extend(package(
&self.slot_question(elected),
&[format_ident!("question"), format_ident!("coordinates")],
));
}
if self.embeddings.len() > 1 {
let mut rows = vec![format_ident!("fusion")];
rows.extend(self.embeddings.iter().map(|elected| elected.field.clone()));
let options = self.fuse_options_name();
methods.extend(package(&options, &rows));
let mut rows = vec![format_ident!("question")];
rows.extend(self.embeddings.iter().map(|elected| elected.field.clone()));
let asked = self.fuse_question_name();
methods.extend(package(&asked, &rows));
}
methods
}
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => Vec::new(),
}
}
#[must_use]
pub fn emitted_types(&self) -> Vec<syn::Ident> {
match self.kind {
NodeKind::Fulltext => {
let mut types = Vec::new();
if !self.searchable.is_empty() {
types.push(self.column_name());
}
let typed = self.fulltext_typed().unwrap_or_default();
types.extend(
typed
.iter()
.map(|engine| self.engine_input(self.base(), engine)),
);
if !typed.is_empty() {
types.push(self.minted(RenamePiece::EngineInput, "EngineInput"));
}
types.push(self.fulltext_options_name());
types.push(self.fulltext_question_name());
types
}
NodeKind::Vector => {
let mut types = Vec::new();
for elected in self.embeddings {
if elected.label.is_set() {
types.push(self.semantics_name(elected));
}
let stem = self.stem(elected);
let typed = self.typed(elected);
if self.fanned(elected) {
for engine in self.participants(elected) {
types.push(self.leg_options(elected, engine));
}
}
types.extend(typed.iter().map(|engine| self.engine_input(&stem, engine)));
if !typed.is_empty() {
types.push(format_ident!("{stem}EngineInput"));
}
types.push(self.slot_options(elected));
if self.fanned(elected) {
types.push(self.slot_evidence_name(elected));
types.push(self.slot_error_name(elected));
}
types.push(self.slot_question(elected));
}
if self.embeddings.len() > 1 {
types.push(self.fuse_options_name());
types.push(self.fuse_question_name());
}
if self.doors().any() {
types.push(self.evidence_name());
types.push(self.fused_error_name());
}
types
}
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => Vec::new(),
}
}
#[must_use]
pub fn options_name(&self) -> Option<syn::Ident> {
match self.kind {
NodeKind::Fulltext => Some(self.fulltext_options_name()),
NodeKind::Vector => Some(match self.embeddings {
[only] => self.slot_options(only),
_ => self.fuse_options_name(),
}),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => None,
}
}
#[must_use]
pub fn question_name(&self) -> Option<syn::Ident> {
match self.kind {
NodeKind::Fulltext => Some(self.fulltext_question_name()),
NodeKind::Vector => Some(match self.embeddings {
[only] => self.slot_question(only),
_ => self.fuse_question_name(),
}),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => None,
}
}
fn fusable(&self, options: &syn::Ident, question: &syn::Ident) -> proc_macro2::TokenStream {
let Tier { krate, index, .. } = self;
let fusable = framework(krate, &["retrieve"], "Fusable");
quote! {
const _: () = {
#[automatically_derived]
impl #fusable for #index {
type Options = #options;
type Question = #question;
}
};
}
}
#[must_use]
pub fn packages(&self) -> Packages<'a> {
Packages {
krate: self.krate,
vis: self.vis,
owner: self.index,
graphql: self.graphql,
base: self.base(),
members: self.face_overrides(),
}
}
fn face_overrides(&self) -> Vec<(syn::Ident, syn::LitStr)> {
let mut members = Vec::new();
let mut push = |face: Option<syn::Ident>, spelled: Option<&syn::LitStr>| {
if let (Some(face), Some(spelled)) = (face, spelled) {
members.push((face, spelled.clone()));
}
};
if let Some(skin) = self
.graphql
.and_then(|block| block.skin(GraphqlKind::AsyncGraphql))
{
push(self.options_name(), skin.options.as_ref());
push(self.question_name(), skin.question.as_ref());
push(self.engine_selector(), skin.engine.as_ref());
}
for elected in self.embeddings {
let Some(skin) = self
.field_numbers
.iter()
.find(|written| written.field == elected.field)
.and_then(|written| written.skin(GraphqlKind::AsyncGraphql))
else {
continue;
};
let stem = self.stem(elected);
push(
Some(format_ident!("{stem}Question")),
skin.question.as_ref(),
);
push(Some(format_ident!("{stem}Engines")), skin.engines.as_ref());
push(
Some(format_ident!("{stem}Sighting")),
skin.sighting.as_ref(),
);
push(
Some(format_ident!("{stem}FusedKeyMatch")),
skin.fused_key_match.as_ref(),
);
}
members
}
#[must_use]
pub fn route_options(&self, elected: &Elected) -> syn::Ident {
self.slot_options(elected)
}
#[must_use]
pub fn route_question(&self, elected: &Elected) -> syn::Ident {
self.slot_question(elected)
}
fn slot_options(&self, elected: &Elected) -> syn::Ident {
let field = elected.field.to_string().to_upper_camel_case();
if self.fanned(elected) {
format_ident!("{}{field}FuseOptions", self.base())
} else {
format_ident!("{}{field}VectorOptions", self.base())
}
}
fn slot_question(&self, elected: &Elected) -> syn::Ident {
let field = elected.field.to_string().to_upper_camel_case();
format_ident!("{}{field}VectorQuestion", self.base())
}
fn semantics_name(&self, elected: &Elected) -> syn::Ident {
let field = elected.field.to_string().to_upper_camel_case();
format_ident!("{}{field}Semantics", self.base())
}
pub(crate) fn fanned(&self, elected: &Elected) -> bool {
self.engines.iter().any(|engines| {
engines.field == elected.field && engines.fanout && engines.participants().count() > 1
})
}
fn legs(&self, elected: &Elected) -> &'a [crate::engine::Engine] {
self
.engines
.iter()
.find(|engines| engines.field == elected.field)
.map_or(&[][..], |engines| &engines.engines)
}
fn participants(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
self
.legs(elected)
.iter()
.filter(|engine| engine.rrf)
.collect()
}
fn evidence_legs(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
self
.legs(elected)
.iter()
.filter(|engine| engine.rrf || engine.resource.is_some())
.collect()
}
#[must_use]
pub fn doors(&self) -> Doors {
match self.kind {
NodeKind::Fulltext => Doors::of(usize::from(!self.searchable.is_empty()), 0),
NodeKind::Vector => Doors::of(0, self.fused_routes().count()),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => Doors::of(0, 0),
}
}
pub fn fused_routes(&self) -> impl Iterator<Item = &'a Elected> {
self
.embeddings
.iter()
.filter(|elected| !elected.label.is_set())
}
#[must_use]
pub fn base(&self) -> &'a syn::Ident {
self
.rename
.and_then(IndexRename::base)
.unwrap_or(self.index)
}
fn engine_selector(&self) -> Option<syn::Ident> {
match self.kind {
NodeKind::Fulltext => self
.fulltext_typed()
.ok()
.filter(|typed| !typed.is_empty())
.map(|_| self.minted(RenamePiece::EngineInput, "EngineInput")),
NodeKind::Vector => {
let mut seats = self
.embeddings
.iter()
.filter(|elected| !self.fanned(elected) && !self.typed(elected).is_empty())
.map(|elected| format_ident!("{}EngineInput", self.stem(elected)));
seats.next().filter(|_| seats.next().is_none())
}
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => None,
}
}
fn minted(&self, piece: RenamePiece, suffix: &str) -> syn::Ident {
self
.rename
.and_then(|rename| rename.piece(piece))
.map_or_else(|| format_ident!("{}{suffix}", self.base()), Clone::clone)
}
#[must_use]
pub fn unmintable(&self, piece: RenamePiece) -> Option<&'static str> {
let vector = self.kind == NodeKind::Vector;
let fulltext = self.kind == NodeKind::Fulltext;
match piece {
RenamePiece::FuseOptions | RenamePiece::FuseQuestion => (vector
&& self.embeddings.len() > 1)
.then_some(())
.map_or(
Some(
"the multi-route packages belong to a VECTOR declaration electing two or more fields. \
One election's package IS the tier's — a route with nothing to fuse against — and a \
full-text declaration is one route however many fields it elects",
),
|()| None,
),
RenamePiece::FulltextOptions | RenamePiece::FulltextQuestion => fulltext.then_some(()).map_or(
Some(
"the full-text packages belong to a `fulltext` declaration. A vector tier's are \
`fuse_options` and `fuse_question`, or the slot's own where it elects one field",
),
|()| None,
),
RenamePiece::Evidence => self.doors().any().then_some(()).map_or(
Some(
"the evidence is what a FUSED DOOR answers with, and this declaration grows none: a \
fused door needs two or more routes of one modality, and a SET election is not among \
them",
),
|()| None,
),
RenamePiece::EngineInput => self.engine_selector().is_some().then_some(()).map_or(
Some(
"the selector is minted where a declaration TYPED an engine word — \
`lance(resource = \"path::To::Lance\")` — and where it mints exactly ONE. A declaration \
typing several elections mints one selector per field, and a word naming an individual \
mint has no way to say which; `rename = \"NewBase\"` re-bases them all",
),
|()| None,
),
RenamePiece::Column => (fulltext && !self.searchable.is_empty()).then_some(()).map_or(
Some(
"the column vocabulary is a FULL-TEXT declaration's, minted from the fields it elected — \
a vector retrieve narrows by election rather than by column",
),
|()| None,
),
}
}
#[must_use]
pub fn fuse_options_name(&self) -> syn::Ident {
self.minted(RenamePiece::FuseOptions, "FuseOptions")
}
#[must_use]
pub fn fuse_question_name(&self) -> syn::Ident {
self.minted(RenamePiece::FuseQuestion, "FuseQuestion")
}
#[must_use]
pub fn fulltext_options_name(&self) -> syn::Ident {
self.minted(RenamePiece::FulltextOptions, "FulltextOptions")
}
#[must_use]
pub fn fulltext_question_name(&self) -> syn::Ident {
self.minted(RenamePiece::FulltextQuestion, "FulltextQuestion")
}
#[must_use]
pub fn evidence_name(&self) -> syn::Ident {
self.minted(RenamePiece::Evidence, "FusedEvidence")
}
#[must_use]
pub fn fused_error_name(&self) -> syn::Ident {
format_ident!("{}FusedError", self.base())
}
#[must_use]
pub fn slot_evidence_name(&self, elected: &Elected) -> syn::Ident {
format_ident!(
"{}{}FusedEvidence",
self.base(),
elected.field.to_string().to_upper_camel_case()
)
}
#[must_use]
pub fn slot_error_name(&self, elected: &Elected) -> syn::Ident {
format_ident!(
"{}{}FusedError",
self.base(),
elected.field.to_string().to_upper_camel_case()
)
}
pub fn fanned_slots(&self) -> impl Iterator<Item = &'a Elected> {
self
.embeddings
.iter()
.filter(|elected| self.fanned(elected) && !elected.label.is_set())
}
#[must_use]
pub fn slot_legs(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
self.evidence_legs(elected)
}
#[must_use]
pub fn slot_participants(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
self.participants(elected)
}
#[must_use]
pub fn slot_leg_options(&self, elected: &Elected, engine: &crate::engine::Engine) -> syn::Ident {
self.leg_options(elected, engine)
}
#[must_use]
pub fn subject_selector(&self) -> Option<syn::Ident> {
self.engine_selector()
}
#[must_use]
pub fn slot_selector(&self, elected: &Elected) -> Option<syn::Ident> {
let stem = self.stem(elected);
(!self.typed(elected).is_empty()).then(|| format_ident!("{stem}EngineInput"))
}
pub fn route_params(&self) -> impl Iterator<Item = (&'a Elected, syn::Ident, syn::Ident)> {
self.fused_routes().map(|elected| {
(
elected,
engine_param(&elected.field),
score_param(&elected.field),
)
})
}
fn evidence(&self) -> proc_macro2::TokenStream {
let Tier { vis, .. } = self;
let name = self.evidence_name();
let params: Vec<syn::Ident> = self
.fused_routes()
.map(|elected| score_param(&elected.field))
.collect();
let variants = self.fused_routes().map(|elected| {
let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
let score = score_param(&elected.field);
let doc = leading(&format!(
"`{field}` ranked this root, at `{field}`'s own score — in `{field}`'s OWN engine's \
currency, which no other variant's is.",
field = elected.field,
));
quote! {
#[doc = #doc]
#variant(#score)
}
});
let doc = leading(&format!(
"WHICH of [`{index}`]'s routes agreed about a fused root, and what each of them scored it — \
the answer's provenance, one variant per route that enters a fused door, each in that \
route's own engine's currency.",
index = self.index,
));
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #name<#(#params,)*> {
#(#variants,)*
}
}
}
fn fused_error(&self) -> proc_macro2::TokenStream {
let Tier { vis, .. } = self;
let name = self.fused_error_name();
let params: Vec<syn::Ident> = self
.fused_routes()
.map(|elected| error_param(&elected.field))
.collect();
let variants = self.fused_routes().map(|elected| {
let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
let error = error_param(&elected.field);
let doc = leading(&format!(
"`{field}`'s own engine refused, in that engine's own vocabulary.",
field = elected.field,
));
quote! {
#[doc = #doc]
#variant(#error)
}
});
let arms = self.fused_routes().map(|elected| {
let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
let field = elected.field.to_string();
quote! {
Self::#variant(__ingraph_refusal) => {
::core::write!(__ingraph_formatter, "{}: {__ingraph_refusal}", #field)
}
}
});
let sources = self.fused_routes().map(|elected| {
let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
quote!(Self::#variant(__ingraph_refusal) => ::core::option::Option::Some(__ingraph_refusal))
});
let displays = params
.iter()
.map(|param| quote!(#param: ::core::fmt::Display));
let errors = params
.iter()
.map(|param| quote!(#param: ::core::error::Error + 'static));
let doc = leading(&format!(
"WHICH of [`{index}`]'s routes refused a fused query, in that route's own engine's \
vocabulary — one variant per route that enters a fused door.",
index = self.index,
));
let why = leading(
"A route's engine is its own, so its refusal is its own: a door asking two stores has two \
error types and no blanket one to widen them into. The route is NAMED rather than erased, \
which is what lets a caller tell *the vector store is down* from *the text store is down*.",
);
quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #why]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #name<#(#params,)*> {
#(#variants,)*
}
#[automatically_derived]
impl<#(#displays,)*> ::core::fmt::Display for #name<#(#params,)*> {
fn fmt(
&self,
__ingraph_formatter: &mut ::core::fmt::Formatter<'_>,
) -> ::core::fmt::Result {
match self {
#(#arms,)*
}
}
}
#[automatically_derived]
impl<#(#errors,)*> ::core::error::Error for #name<#(#params,)*> {
fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
match self {
#(#sources,)*
}
}
}
}
}
pub(crate) fn typed(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
self
.legs(elected)
.iter()
.filter(|engine| engine.resource.is_some())
.collect()
}
fn fulltext_typed(&self) -> Result<Vec<&'a crate::engine::Engine>, proc_macro2::TokenStream> {
let mut typed: Vec<&'a crate::engine::Engine> = Vec::new();
for engine in self
.engines
.iter()
.flat_map(|declared| declared.engines.iter())
.filter(|engine| engine.resource.is_some())
{
match typed.iter().find(|first| first.word == engine.word) {
None => typed.push(engine),
Some(first) if spelled(first.resource.as_ref()) == spelled(engine.resource.as_ref()) => {}
Some(first) => {
let refusal = format!(
"`{index}` binds `{word}` to `{first}` on one field and to `{second}` on another, and a \
full-text declaration is ONE ROUTE — its `engine` seat holds one vocabulary, so a word \
in it names one engine. Write the same type on both blocks, or give the second engine \
a word of its own",
index = self.index,
word = engine.word,
first = spelled(first.resource.as_ref()),
second = spelled(engine.resource.as_ref()),
);
return Err(quote!(::core::compile_error!(#refusal);));
}
}
}
Ok(typed)
}
fn seam(&self) -> proc_macro2::TokenStream {
match self.kind {
NodeKind::Fulltext => framework(self.krate, &["store"], "FulltextEngine"),
_ => framework(self.krate, &["store"], "VectorEngine"),
}
}
fn engine_seat(
&self,
stem: &syn::Ident,
engines: &[&crate::engine::Engine],
) -> Option<(proc_macro2::TokenStream, Row)> {
if engines.is_empty() {
return None;
}
let seam = self.seam();
let name = format_ident!("{stem}EngineInput");
let mut variants: Vec<(syn::Ident, syn::Ident, String)> = Vec::new();
let packages = engines
.iter()
.map(|engine| {
let word = engine.word.to_string().to_upper_camel_case();
let package = self.engine_input(stem, engine);
let ty = engine
.resource
.as_ref()
.expect("a typed engine names a type");
variants.push((
format_ident!("{word}"),
package.clone(),
engine.word.to_string().to_lower_camel_case(),
));
self.packages().package(
&package,
&format!(
"The per-request knobs `{stem}` runs under IN `{word}` — one variant of its `engine` \
choice, holding the floor in this engine's own score currency and whatever else this \
engine takes per query.",
word = engine.word,
),
&[
Row::new(
&format_ident!("floor"),
quote_spanned!(ty.span()=> <#ty as #seam>::Score),
"score floor",
),
Row::new(
&format_ident!("options"),
quote_spanned!(ty.span()=> <#ty as #seam>::SearchOptions),
"per-query knobs",
),
],
)
})
.collect::<Vec<_>>();
let oneof = self.packages().oneof(&name, stem, &variants);
let row = Row::new(&format_ident!("engine"), quote!(#name), "engine choice");
Some((
quote! {
#(#packages)*
#oneof
},
row,
))
}
fn fulltext(&self) -> proc_macro2::TokenStream {
let typed = match self.fulltext_typed() {
Ok(typed) => typed,
Err(refusal) => return refusal,
};
let subject = self.searchable_subject();
let options = self.fulltext_options_name();
let asked = self.fulltext_question_name();
let vocabulary = self.column_vocabulary();
let mut rows = Vec::new();
let (engines, engine) = match self.engine_seat(self.base(), &typed) {
Some((engines, row)) => (engines, Some(row)),
None => (proc_macro2::TokenStream::new(), None),
};
rows.extend(engine);
if !self.searchable.is_empty() {
let column = self.column_name();
rows.push(Row::new(
&format_ident!("columns"),
quote!(::std::vec::Vec<#column>),
"column subset",
));
}
let package = self.packages().package(
&options,
&format!(
"The knobs a full-text retrieve over [`{index}`] runs under — ONE package however many \
fields it elects ({subject}), because a full-text declaration is one ROUTE: its elected \
fields are COLUMNS of that route rather than routes of their own, and `columns` is where a \
request names the subset of them it wants searched. Absent means this declaration's own \
subject, whole.",
index = self.index,
),
&rows,
);
let question = self.packages().question(
&asked,
&format!(
"The question a full-text retrieve over [`{index}`] is asked with. One row, because a \
full-text route's own currency IS the tier's: text.",
index = self.index,
),
&[Row::new(
&format_ident!("question"),
quote!(::std::string::String),
"question",
)],
);
let binding = self.fusable(&options, &asked);
quote! {
#vocabulary
#engines
#package
#question
#binding
}
}
fn column_name(&self) -> syn::Ident {
self.minted(RenamePiece::Column, "Column")
}
fn column_vocabulary(&self) -> proc_macro2::TokenStream {
let Tier {
krate, vis, index, ..
} = self;
if self.searchable.is_empty() {
return proc_macro2::TokenStream::new();
}
let name = self.column_name();
let column = framework(krate, &["store"], "FulltextColumn");
let mut variants: Vec<(syn::Ident, String)> = Vec::new();
for field in self.searchable {
let spelling = field.to_string().to_upper_camel_case();
if let Some((_, other)) = variants.iter().find(|(minted, _)| *minted == spelling) {
let refusal = format!(
"`{index}` elects `{field}` and `{other}`, which spell ONE variant `{spelling}` of \
`{name}` — a column vocabulary is one word to a column, so rename one of the fields",
);
return quote!(::core::compile_error!(#refusal););
}
variants.push((format_ident!("{spelling}"), field.to_string()));
}
let declared = variants.iter().map(|(variant, field)| {
let doc = leading(&format!("`{field}`, as this declaration elected it."));
quote! {
#[doc = #doc]
#variant
}
});
let arms = variants
.iter()
.map(|(variant, field)| quote!(Self::#variant => #column::new(#field)));
let words: Vec<String> = variants
.iter()
.map(|(variant, _)| variant.to_string().to_shouty_snake_case())
.collect();
let idents: Vec<&syn::Ident> = variants.iter().map(|(variant, _)| variant).collect();
let face = self.packages().enum_face(&name, &idents, &words);
let doc = leading(&format!(
"WHICH searchable columns of [`{index}`] a retrieve runs over — its elected fields, as a \
closed vocabulary. A column this declaration never elected has no variant here to spell it \
with.",
));
let column_doc = leading(
"The seam's own name for this column — the ONE point at which this vocabulary becomes a \
`FulltextColumn`, so a variant's spelling and the name an engine is handed cannot drift.",
);
quote! {
#[doc = #doc]
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::marker::Copy,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash
)]
#vis enum #name {
#(#declared,)*
}
#[automatically_derived]
impl #name {
#[doc = #column_doc]
#[must_use]
#[inline]
#vis const fn column(self) -> #column {
match self {
#(#arms,)*
}
}
}
#face
}
}
fn searchable_subject(&self) -> String {
self
.searchable
.iter()
.map(|field| format!("`{field}`"))
.collect::<Vec<_>>()
.join(", ")
}
fn vector(&self) -> proc_macro2::TokenStream {
let leaves = self
.embeddings
.iter()
.map(|elected| self.election(elected))
.collect::<Vec<_>>();
let tier = match self.embeddings {
[_] => proc_macro2::TokenStream::new(),
_ => self.vector_tier(),
};
let options = self.options_name().expect("a vector tier retrieves");
let asked = self.question_name().expect("a vector tier retrieves");
let binding = self.fusable(&options, &asked);
let evidence = if self.doors().any() {
let provenance = self.evidence();
let refusal = self.fused_error();
quote! {
#provenance
#refusal
}
} else {
proc_macro2::TokenStream::new()
};
quote! {
#(#leaves)*
#tier
#evidence
#binding
}
}
fn election(&self, elected: &Elected) -> proc_macro2::TokenStream {
let semantics = self.semantics(elected);
let question = self.election_question(elected);
let options = if self.fanned(elected) {
self.fanned_slot(elected)
} else {
self.flat_slot(elected)
};
quote! {
#semantics
#options
#question
}
}
fn flat_slot(&self, elected: &Elected) -> proc_macro2::TokenStream {
let name = self.slot_options(elected);
let mut rows = Vec::new();
let (engines, engine) = match self.engine_seat(&self.stem(elected), &self.typed(elected)) {
Some((engines, row)) => (engines, Some(row)),
None => (proc_macro2::TokenStream::new(), None),
};
rows.extend(engine);
if elected.label.is_set() {
let semantics = self.semantics_name(elected);
rows.push(Row::new(
&format_ident!("semantics"),
quote!(#semantics),
"fold",
));
}
let package = self.packages().package(
&name,
&format!(
"The knobs a retrieve over [`{index}`]'s `{field}` runs under.",
index = self.index,
field = elected.field,
),
&rows,
);
quote! {
#engines
#package
}
}
pub(crate) fn engine_input(
&self,
stem: &syn::Ident,
engine: &crate::engine::Engine,
) -> syn::Ident {
format_ident!(
"{stem}{}EngineInput",
engine.word.to_string().to_upper_camel_case()
)
}
pub(crate) fn stem(&self, elected: &Elected) -> syn::Ident {
format_ident!(
"{}{}",
self.base(),
elected.field.to_string().to_upper_camel_case()
)
}
fn leg_options(&self, elected: &Elected, engine: &crate::engine::Engine) -> syn::Ident {
format_ident!(
"{}{}{}LegOptions",
self.base(),
elected.field.to_string().to_upper_camel_case(),
engine.word.to_string().to_upper_camel_case(),
)
}
fn fanned_slot(&self, elected: &Elected) -> proc_macro2::TokenStream {
let route = framework(self.krate, &["retrieve"], "Route");
let flavour = framework(self.krate, &["retrieve"], "FusionOptions");
let participants = self.participants(elected);
let packages = participants.iter().map(|engine| {
let name = self.leg_options(elected, engine);
self.packages().package(
&name,
&format!(
"The knobs [`{index}`]'s `{elected}` runs under IN THE `{engine}` STORE — one leg of a \
fanned slot, and a route of the mini tier below.",
index = self.index,
elected = elected.field,
engine = engine.word,
),
&[],
)
});
let mut rows = vec![Row::new(
&format_ident!("fusion"),
quote!(#flavour),
"fusion flavour",
)];
let (selector, seat) = match self.engine_seat(&self.stem(elected), &self.typed(elected)) {
Some((packages, row)) => (packages, Some(row)),
None => (proc_macro2::TokenStream::new(), None),
};
rows.extend(seat);
if elected.label.is_set() {
let semantics = self.semantics_name(elected);
rows.push(Row::new(
&format_ident!("semantics"),
quote!(#semantics),
"fold",
));
}
rows.extend(participants.iter().map(|engine| {
let leg = self.leg_options(elected, engine);
Row::new(
&engine.word,
quote!(#route<#leg>),
&format!("`{}` leg", engine.word),
)
}));
let tier = self.packages().package(
&self.slot_options(elected),
&format!(
"The knobs a retrieve over [`{index}`]'s FANNED `{field}` runs under — a tier rather than a \
leaf, because several declared engines are live at once and each of them is a route.",
index = self.index,
field = elected.field,
),
&rows,
);
let evidence = self.slot_evidence(elected);
quote! {
#(#packages)*
#selector
#tier
#evidence
}
}
fn slot_evidence(&self, elected: &Elected) -> proc_macro2::TokenStream {
let Tier { vis, .. } = self;
let legs = self.evidence_legs(elected);
let name = self.slot_evidence_name(elected);
let refusal = self.slot_error_name(elected);
let scores: Vec<syn::Ident> = legs
.iter()
.map(|engine| score_param(&engine.word))
.collect();
let errors: Vec<syn::Ident> = legs
.iter()
.map(|engine| error_param(&engine.word))
.collect();
let variants = legs.iter().zip(&scores).map(|(engine, score)| {
let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
let doc = leading(&format!(
"The `{word}` store ranked this root, at that store's own score.",
word = engine.word,
));
quote! {
#[doc = #doc]
#variant(#score)
}
});
let refusals = legs.iter().zip(&errors).map(|(engine, error)| {
let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
let doc = leading(&format!(
"The `{word}` store refused, in that store's own vocabulary.",
word = engine.word,
));
quote! {
#[doc = #doc]
#variant(#error)
}
});
let arms = legs.iter().map(|engine| {
let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
let word = engine.word.to_string();
quote! {
Self::#variant(__ingraph_refusal) => {
::core::write!(__ingraph_formatter, "{}: {__ingraph_refusal}", #word)
}
}
});
let sources = legs.iter().map(|engine| {
let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
quote!(Self::#variant(__ingraph_refusal) => ::core::option::Option::Some(__ingraph_refusal))
});
let displays = errors
.iter()
.map(|param| quote!(#param: ::core::fmt::Display));
let bounds = errors
.iter()
.map(|param| quote!(#param: ::core::error::Error + 'static));
let doc = leading(&format!(
"WHICH of [`{index}`]'s `{field}` STORES agreed about a fused root, and what each of them \
scored it — one variant per leg the slot's answer can name, each in that store's own \
currency.",
index = self.index,
field = elected.field,
));
let both = leading(
"The FUSED road fills one variant per participating leg; the SELECTOR road fills exactly one, \
for whichever leg the request named. One type answers both, which is what *the same answer \
shape* means here.",
);
let refusal_doc = leading(&format!(
"WHICH of [`{index}`]'s `{field}` stores refused, in that store's own vocabulary.",
index = self.index,
field = elected.field,
));
quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #both]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #name<#(#scores,)*> {
#(#variants,)*
}
#[doc = #refusal_doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #refusal<#(#errors,)*> {
#(#refusals,)*
}
#[automatically_derived]
impl<#(#displays,)*> ::core::fmt::Display for #refusal<#(#errors,)*> {
fn fmt(
&self,
__ingraph_formatter: &mut ::core::fmt::Formatter<'_>,
) -> ::core::fmt::Result {
match self {
#(#arms,)*
}
}
}
#[automatically_derived]
impl<#(#bounds,)*> ::core::error::Error for #refusal<#(#errors,)*> {
fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
match self {
#(#sources,)*
}
}
}
}
}
fn election_question(&self, elected: &Elected) -> proc_macro2::TokenStream {
let marker = framework(self.krate, &["election"], "EmbeddingMarker");
let ty = &elected.ty;
let point = quote!(<#ty as #marker>::Item);
let coordinates = if elected.label.is_set() {
quote!(::std::vec::Vec<#point>)
} else {
point
};
self.packages().question(
&self.slot_question(elected),
&format!(
"The question [`{index}`]'s `{field}` is asked with — the text question its ask road walks, \
or the coordinates a caller already holds, IN THIS ELECTION'S OWN SPACE.",
index = self.index,
field = elected.field,
),
&[
Row::new(
&format_ident!("question"),
quote!(::std::string::String),
"question",
),
Row::new(&format_ident!("coordinates"), coordinates, "coordinates").rust_side(),
],
)
}
fn vector_tier(&self) -> proc_macro2::TokenStream {
let route = framework(self.krate, &["retrieve"], "Route");
let flavour = framework(self.krate, &["retrieve"], "FusionOptions");
let mut rows = vec![Row::new(
&format_ident!("fusion"),
quote!(#flavour),
"fusion flavour",
)];
rows.extend(self.embeddings.iter().map(|elected| {
let package = self.slot_options(elected);
Row::new(
&elected.field,
quote!(#route<#package>),
&format!("`{}` route", elected.field),
)
}));
let options = self.packages().package(
&self.fuse_options_name(),
&format!(
"The knobs a FUSED retrieve over [`{index}`] runs under — one route per election, each \
wearing the edge facts its parent holds about it.",
index = self.index,
),
&rows,
);
let mut asked = vec![Row::new(
&format_ident!("question"),
quote!(::std::string::String),
"question",
)];
asked.extend(self.embeddings.iter().map(|elected| {
let package = self.slot_question(elected);
Row::new(
&elected.field,
quote!(#package),
&format!("`{}` route", elected.field),
)
}));
let asked = self.packages().question(
&self.fuse_question_name(),
&format!(
"The question a FUSED retrieve over [`{index}`] is asked with — this tier's own, and one \
package per route for the routes that ask something else.",
index = self.index,
),
&asked,
);
quote! {
#options
#asked
}
}
fn semantics(&self, elected: &Elected) -> proc_macro2::TokenStream {
if !elected.label.is_set() {
return proc_macro2::TokenStream::new();
}
let Tier { krate, vis, .. } = self;
let name = self.semantics_name(elected);
let visitor = framework(krate, &["retrieve"], "FoldVisitor");
let shipped = |citizen: &str| framework(krate, &["retrieve"], citizen);
let mut arms: Vec<(syn::Ident, proc_macro2::TokenStream, String)> = vec![
(
format_ident!("Sum"),
shipped("Sum"),
"`Σⱼ bⱼ` — standard MaxSim / late-interaction.".to_owned(),
),
(
format_ident!("Max"),
shipped("Max"),
"`maxⱼ bⱼ` — the best single (query vector, set member) pair.".to_owned(),
),
];
if let Some(Fold::Custom(path)) = &elected.fold {
let word = path
.segments
.last()
.map_or_else(|| "Custom".to_owned(), |segment| segment.ident.to_string());
let variant = word.to_upper_camel_case();
if arms.iter().any(|(shipped, _, _)| shipped == &variant) {
let refusal = format!(
"`{path}` ends in `{word}`, which is the word this framework's own `{word}` fold already \
holds in `{index}`'s `{field}` vocabulary — rename the fold, or alias it, so the \
election's words stay one to a fold",
path = quote!(#path).to_string().replace(' ', ""),
index = self.index,
field = elected.field,
);
return quote!(::core::compile_error!(#refusal););
}
arms.push((
format_ident!("{variant}"),
quote!(#path),
format!("`{word}` — the fold this declaration named."),
));
}
let declared = match &elected.fold {
None | Some(Fold::Sum) => format_ident!("Sum"),
Some(Fold::Max) => format_ident!("Max"),
Some(Fold::Custom(path)) => format_ident!(
"{}",
path
.segments
.last()
.map_or_else(|| "Custom".to_owned(), |segment| segment.ident.to_string())
.to_upper_camel_case()
),
};
let variants = arms.iter().map(|(variant, _, doc)| {
let doc = leading(doc);
quote! {
#[doc = #doc]
#variant
}
});
let semantics = framework(krate, &["retrieve"], "FoldSemantics");
let dispatch = arms.iter().map(|(variant, ty, _)| {
quote!(Self::#variant => #visitor::visit(__ingraph_visitor, <#ty as ::core::default::Default>::default()))
});
let obligations = arms
.iter()
.map(|(_, ty, _)| quote!(#ty: #semantics<__INGRAPH_SCORE__>));
let words: Vec<String> = arms
.iter()
.map(|(variant, _, _)| variant.to_string().to_shouty_snake_case())
.collect();
let idents: Vec<&syn::Ident> = arms.iter().map(|(variant, _, _)| variant).collect();
let doc = leading(&format!(
"WHICH fold [`{index}`]'s `{field}` set query runs under — the wire's closed vocabulary over \
an open set of types.",
index = self.index,
field = elected.field,
));
let declared_doc =
leading("The fold this DECLARATION named, and what a request that names none resolves to.");
let with_doc = leading(
"Spend this word's fold. The arms produce DIFFERENT TYPES, so the visitor rather than a \
return value is what crosses back — each arm monomorphizes, and the door below is the \
statically dispatched door it would have been had the caller spelled the type.",
);
let face = self.packages().enum_face(&name, &idents, &words);
quote! {
#[doc = #doc]
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::marker::Copy,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash
)]
#vis enum #name {
#(#variants,)*
}
#[automatically_derived]
impl #name {
#[doc = #declared_doc]
#vis const DECLARED: Self = Self::#declared;
#[doc = #with_doc]
#[inline]
#vis fn with_fold<__INGRAPH_SCORE__, __INGRAPH_VISITOR__>(
self,
__ingraph_visitor: __INGRAPH_VISITOR__,
) -> <__INGRAPH_VISITOR__ as #visitor<__INGRAPH_SCORE__>>::Output
where
__INGRAPH_VISITOR__: #visitor<__INGRAPH_SCORE__>,
#(#obligations,)*
{
match self {
#(#dispatch,)*
}
}
}
#face
}
}
}
#[derive(Debug, Clone)]
pub struct Packages<'a> {
pub krate: &'a syn::Path,
pub vis: &'a syn::Visibility,
pub owner: &'a syn::Ident,
pub graphql: Option<&'a IndexGraphql>,
pub base: &'a syn::Ident,
pub members: Vec<(syn::Ident, syn::LitStr)>,
}
impl<'a> Packages<'a> {
pub fn package(
&self,
name: &syn::Ident,
subject: &str,
rows: &[Row],
) -> proc_macro2::TokenStream {
self.shaped(name, subject, rows)
}
pub fn question(
&self,
name: &syn::Ident,
subject: &str,
rows: &[Row],
) -> proc_macro2::TokenStream {
self.shaped(name, subject, rows)
}
fn shaped(&self, name: &syn::Ident, subject: &str, rows: &[Row]) -> proc_macro2::TokenStream {
let Packages { vis, .. } = self;
if let Some(taken) = collision(rows) {
let refusal = format!(
"`{name}` would carry two rows named `{taken}` — one is this framework's own and one is \
`{owner}`'s, and a package's rows are one to a name; rename the member, the election or \
the engine word that spells `{taken}`",
owner = self.owner,
);
return quote!(::core::compile_error!(#refusal););
}
let members = substrate();
let fields = rows.iter().map(|Row { member, ty, noun, .. }| {
let doc = leading(&format!(
"The {noun}, where the request named one — absent means the declaration's own.",
));
let why = "a package's members are read through its own accessors, and which of them any one \
deployment reads is not this emission's business";
quote! {
#[doc = #doc]
#[allow(dead_code, reason = #why)]
#members #member: ::core::option::Option<#ty>
}
});
let accessors = rows.iter().map(
|Row {
member, ty, noun, ..
}| {
let with = format_ident!("with_{member}");
let set = leading(&format!("The same package carrying a {noun}."));
let get = leading(&format!("The {noun} this package names, if it names one."));
quote! {
#[doc = #set]
#[must_use]
#[inline]
#vis fn #with(mut self, #member: #ty) -> Self {
self.#member = ::core::option::Option::Some(#member);
self
}
#[doc = #get]
#[must_use]
#[inline]
#vis const fn #member(&self) -> ::core::option::Option<&#ty> {
::core::option::Option::as_ref(&self.#member)
}
}
},
);
let empty = rows
.iter()
.map(|Row { member, .. }| quote!(#member: ::core::option::Option::None));
let doc = leading(subject);
let new_doc = leading(
"A package that names nothing — every row absent, every one of them deferring to the \
declaration's own. The head of the factory chain, and what `Default` is.",
);
let face = self.input_face(name, rows);
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis struct #name {
#(#fields,)*
}
#[automatically_derived]
impl #name {
#[doc = #new_doc]
#[must_use]
#[inline]
#vis const fn new() -> Self {
Self { #(#empty,)* }
}
#(#accessors)*
}
#[automatically_derived]
impl ::core::default::Default for #name {
#[inline]
fn default() -> Self {
Self::new()
}
}
#face
}
}
fn input_face(&self, name: &syn::Ident, rows: &[Row]) -> proc_macro2::TokenStream {
if !self.dressed(GraphqlKind::AsyncGraphql) {
return proc_macro2::TokenStream::new();
}
let Packages { krate, .. } = self;
let gate = framework(krate, &["gate"], "if_async_graphql");
let ag = framework(krate, &[], "async_graphql");
let sdl = self.sdl(name);
let crossing = || rows.iter().filter(|row| row.crosses);
let entries = crossing().map(|Row { wire, ty, .. }| {
quote! {
__ingraph_fields.insert(
::std::string::String::from(#wire),
#ag::registry::MetaInputValue {
name: ::std::string::String::from(#wire),
description: ::core::option::Option::None,
ty: <::core::option::Option<#ty> as #ag::InputType>::create_type_info(
__ingraph_registry,
),
deprecation: #ag::registry::Deprecation::NoDeprecated,
default_value: ::core::option::Option::None,
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
is_secret: false,
directive_invocations: ::std::vec::Vec::new(),
},
);
}
});
let reads = rows.iter().map(
|Row {
member,
wire,
ty,
crosses,
..
}| {
if !crosses {
return quote!(#member: ::core::option::Option::None);
}
quote! {
#member: <::core::option::Option<#ty> as #ag::InputType>::parse(
#ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
)
.map_err(#ag::InputValueError::propagate)?
}
},
);
let writes = crossing().map(|Row { member, wire, .. }| {
quote! {
__ingraph_map.insert(
#ag::Name::new(#wire),
#ag::InputType::to_value(&self.#member),
);
}
});
quote! {
#gate! {
const _: () = {
#[automatically_derived]
impl #ag::InputType for #name {
type RawValueType = Self;
#[inline]
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#sdl)
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_input_type::<Self, _>(
#ag::registry::MetaTypeId::InputObject,
|__ingraph_registry| #ag::registry::MetaType::InputObject {
name: ::std::string::String::from(#sdl),
description: ::core::option::Option::None,
input_fields: {
let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
#(#entries)*
__ingraph_fields
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
oneof: false,
directive_invocations: ::std::vec::Vec::new(),
},
)
}
fn parse(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> #ag::InputValueResult<Self> {
if let ::core::option::Option::Some(#ag::Value::Object(__ingraph_object)) =
__ingraph_value
{
return ::core::result::Result::Ok(Self { #(#reads,)* });
}
::core::result::Result::Err(#ag::InputValueError::expected_type(
::core::option::Option::unwrap_or_default(__ingraph_value),
))
}
fn to_value(&self) -> #ag::Value {
let mut __ingraph_map = #ag::indexmap::IndexMap::new();
#(#writes)*
#ag::Value::Object(__ingraph_map)
}
#[inline]
fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
::core::option::Option::Some(self)
}
}
#[automatically_derived]
impl #ag::InputObjectType for #name {}
};
}
}
}
pub fn oneof(
&self,
name: &syn::Ident,
stem: &syn::Ident,
variants: &[(syn::Ident, syn::Ident, String)],
) -> proc_macro2::TokenStream {
let Packages { krate, vis, .. } = self;
let gate = framework(krate, &["gate"], "if_async_graphql");
let ag = framework(krate, &[], "async_graphql");
let sdl = self.sdl(name);
let declared = variants.iter().map(|(variant, package, word)| {
let doc = leading(&format!(
"The knobs `{word}` takes, in `{word}`'s own currencies."
));
quote! {
#[doc = #doc]
#variant(#package)
}
});
let entries = variants.iter().map(|(_, package, word)| {
quote! {
__ingraph_fields.insert(
::std::string::String::from(#word),
#ag::registry::MetaInputValue {
name: ::std::string::String::from(#word),
description: ::core::option::Option::None,
ty: <::core::option::Option<#package> as #ag::InputType>::create_type_info(
__ingraph_registry,
),
deprecation: #ag::registry::Deprecation::NoDeprecated,
default_value: ::core::option::Option::None,
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
is_secret: false,
directive_invocations: ::std::vec::Vec::new(),
},
);
}
});
let reads = variants.iter().map(|(variant, _, word)| {
quote! {
if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #word)
&& __ingraph_object.len() == 1
{
let __ingraph_chosen = #ag::InputType::parse(
#ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #word),
)
.map_err(#ag::InputValueError::propagate)?;
return ::core::result::Result::Ok(Self::#variant(__ingraph_chosen));
}
}
});
let writes = variants.iter().map(|(variant, _, word)| {
quote! {
Self::#variant(__ingraph_chosen) => {
__ingraph_map.insert(
#ag::Name::new(#word),
#ag::InputType::to_value(__ingraph_chosen),
);
}
}
});
let doc = leading(&format!(
"WHICH engine a retrieve over `{stem}` is tuned for, and the knobs it is tuned with — one \
variant per engine this declaration TYPED, each holding the numbers that only mean anything \
in that engine's own currencies. A choice rather than a record: naming two engines in one \
request is two requests.",
));
let face = if self.dressed(GraphqlKind::AsyncGraphql) {
quote! {
#gate! {
const _: () = {
#[automatically_derived]
impl #ag::InputType for #name {
type RawValueType = Self;
#[inline]
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#sdl)
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_input_type::<Self, _>(
#ag::registry::MetaTypeId::InputObject,
|__ingraph_registry| #ag::registry::MetaType::InputObject {
name: ::std::string::String::from(#sdl),
description: ::core::option::Option::None,
input_fields: {
let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
#(#entries)*
__ingraph_fields
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
oneof: true,
directive_invocations: ::std::vec::Vec::new(),
},
)
}
fn parse(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> #ag::InputValueResult<Self> {
if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
__ingraph_value
{
#(#reads)*
return ::core::result::Result::Err(#ag::InputValueError::expected_type(
#ag::Value::Object(__ingraph_object),
));
}
::core::result::Result::Err(#ag::InputValueError::expected_type(
::core::option::Option::unwrap_or_default(__ingraph_value),
))
}
fn to_value(&self) -> #ag::Value {
let mut __ingraph_map = #ag::indexmap::IndexMap::new();
match self {
#(#writes)*
}
#ag::Value::Object(__ingraph_map)
}
#[inline]
fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
::core::option::Option::Some(self)
}
}
#[automatically_derived]
impl #ag::InputObjectType for #name {}
#[automatically_derived]
impl #ag::OneofObjectType for #name {}
};
}
}
} else {
proc_macro2::TokenStream::new()
};
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #name {
#(#declared,)*
}
#face
}
}
pub fn enum_face(
&self,
name: &syn::Ident,
variants: &[&syn::Ident],
words: &[String],
) -> proc_macro2::TokenStream {
if !self.dressed(GraphqlKind::AsyncGraphql) {
return proc_macro2::TokenStream::new();
}
let Packages { krate, .. } = self;
let gate = framework(krate, &["gate"], "if_async_graphql");
let ag = framework(krate, &[], "async_graphql");
let sdl = self.sdl(name);
let items = variants.iter().zip(words).map(|(variant, word)| {
quote! {
#ag::resolver_utils::EnumItem { name: #word, value: #name::#variant }
}
});
let values = words.iter().map(|word| {
quote! {
__ingraph_values.insert(
::std::string::String::from(#word),
#ag::registry::MetaEnumValue {
name: ::std::string::String::from(#word),
description: ::core::option::Option::None,
deprecation: #ag::registry::Deprecation::NoDeprecated,
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
directive_invocations: ::std::vec::Vec::new(),
},
);
}
});
quote! {
#gate! {
const _: () = {
#[automatically_derived]
impl #ag::resolver_utils::EnumType for #name {
fn items() -> &'static [#ag::resolver_utils::EnumItem<#name>] {
&[#(#items,)*]
}
}
#[automatically_derived]
impl #ag::InputType for #name {
type RawValueType = Self;
#[inline]
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#sdl)
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_input_type::<Self, _>(
#ag::registry::MetaTypeId::Enum,
|_| #ag::registry::MetaType::Enum {
name: ::std::string::String::from(#sdl),
description: ::core::option::Option::None,
enum_values: {
let mut __ingraph_values = #ag::indexmap::IndexMap::new();
#(#values)*
__ingraph_values
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
directive_invocations: ::std::vec::Vec::new(),
requires_scopes: ::std::vec::Vec::new(),
},
)
}
fn parse(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> #ag::InputValueResult<Self> {
#ag::resolver_utils::parse_enum(
::core::option::Option::unwrap_or_default(__ingraph_value),
)
}
fn to_value(&self) -> #ag::Value {
#ag::resolver_utils::enum_value(*self)
}
#[inline]
fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
::core::option::Option::Some(self)
}
}
};
}
}
}
fn dressed(&self, kind: GraphqlKind) -> bool {
self.graphql.is_some_and(|block| block.renders(kind))
}
pub(crate) fn sdl(&self, name: &syn::Ident) -> String {
let rust = name.to_string();
if let Some((_, spelled)) = self.members.iter().find(|(face, _)| face == name) {
return spelled.value();
}
let Some(skin) = self
.graphql
.and_then(|block| block.skin(GraphqlKind::AsyncGraphql))
else {
return rust;
};
let Some(base) = skin.prefix.as_ref() else {
return rust;
};
let base = base.value().to_upper_camel_case();
rust
.strip_prefix(&self.base.to_string())
.map_or(rust.clone(), |rest| format!("{base}{rest}"))
}
}
impl IndexModel {
#[must_use]
pub fn tier(&self) -> Tier<'_> {
Tier {
krate: &self.krate,
vis: &self.vis,
index: &self.index,
kind: self.kind,
embeddings: &self.embeddings,
searchable: &self.searchable,
engines: &self.engines,
graphql: self.graphql.as_ref(),
rename: self.rename.as_ref(),
field_numbers: &self.field_numbers,
}
}
}