ingraph_codegen/fuse.rs
1//! THE FUSION TREE, as a declaration mints it: the leaf packages a slot is configured and asked
2//! with, the tier packages that fuse them, and the one [`Fusable`] impl that hands the whole subtree
3//! to a parent by projection.
4//!
5//! ```text
6//! #[ingraph::vector(upstream(node = "Keyframe", …))]
7//! pub struct Frames {
8//! #[ingraph(list(embedding), knn(semantics(fold = "app::PositionWeighted")))]
9//! frames: Vec<Embedding<f32, DIM, Clip>>,
10//! #[ingraph(embedding, knn)]
11//! poster: Embedding<f32, DIM, Clip>,
12//! }
13//! ```
14//!
15//! mints, at module scope:
16//!
17//! ```text
18//! FramesFramesSemantics SUM | MAX | POSITION_WEIGHTED the wire fold vocabulary
19//! FramesFramesVectorOptions { semantics } one slot's knobs
20//! FramesFramesVectorQuestion { question, coordinates } one slot's question
21//! FramesPosterVectorOptions { }
22//! FramesPosterVectorQuestion { question, coordinates }
23//! FramesFuseOptions { fusion, frames: Route<…>, poster: Route<…> }
24//! FramesFuseQuestion { question, frames: …, poster: … }
25//! impl Fusable for Frames Options = FramesFuseOptions, Question = FramesFuseQuestion
26//! ```
27//!
28//! # THE BINDING TABLE is the whole of what a parent sees
29//!
30//! A member's package shape is its own business, and a parent absorbs whichever it is through one
31//! projection. Three shapes, picked here and nowhere else:
32//!
33//! | the tier | its `Fusable::Options` |
34//! |---|---|
35//! | a full-text declaration (one subject, always) | `<Tier>FulltextOptions` |
36//! | a vector declaration electing ONE field, single-write | `<Index><Field>VectorOptions` |
37//! | a vector declaration electing one FANNED field | `<Index><Field>FuseOptions` |
38//! | a vector declaration electing several | `<Index>FuseOptions` |
39//!
40//! # THE FUSED DOORS STAND BESIDE THE PER-KIND ONES AND NEVER INSTEAD OF THEM
41//!
42//! [`Doors`] is the additive door law in one place: a tier with two or more routes of one modality
43//! grows that modality's door, a tier with one route of EACH grows the mixed `fuse`, and every
44//! per-election door goes on emitting whatever happens. At the index grain the law resolves to
45//! `vector_fuse` alone — a full-text declaration is ONE route however many fields it elects, and a
46//! declaration's kind is its modality, so the other two doors have no route set here. Their home is
47//! a SEARCH RECIPE, which lists the members it fuses and mints one door over exactly them.
48//!
49//! # THE MODALITY PRESENCE LAW, at the grain this derive can see
50//!
51//! A full-text declaration emits NOTHING vector-flavoured and a vector declaration emits NOTHING
52//! full-text-flavoured — not an empty package, not a package behind a bound nobody satisfies, but no
53//! type at all. It is free here because a declaration's KIND is one of the three and its elections
54//! are all of that kind, so the law is the `match` at the top of [`Tier::emit`] rather than a filter
55//! anybody has to remember. A BLOB family emits nothing at all and gets no [`Fusable`] impl, which
56//! is what makes *this member does not retrieve* a compile fact at every parent's projection.
57//!
58//! # THE FRACTAL DESCENDS ONE MORE LEVEL AT A FANNED SLOT
59//!
60//! A `fanout` election writes every declared engine at once, so its legs are routes: the slot's
61//! package becomes a mini tier — a `fusion` flavour of its own and one [`Route`] per leg — and the
62//! parent wraps THAT in a route exactly as it wraps a flat leaf. Nothing about the parent changes,
63//! which is the property being built rather than a coincidence: a route's interior is opaque to its
64//! parent.
65//!
66//! What is per-LEG and what is per-FIELD is the one asymmetry worth reading twice. A fold is what
67//! turns `m` per-query numbers into one for a FIELD, and the field is one field however many engines
68//! hold it, so the semantics row rides the mini tier; a leg's own package holds whatever is that
69//! ENGINE's alone. The question side has no per-leg row at all, for the same reason: the legs are one
70//! field's coordinates in several stores.
71//!
72//! The leg package is EMPTY today, and the wall law is why: its one row was the request-side
73//! `ceiling`, and a protective number never crosses the wire. What a request still says about a leg
74//! it says on the leg's `Route` — the parent's weight, whether to walk it, and how deep.
75//!
76//! # THE ENGINE SEAT IS THE ONE ROW WHOSE TYPE THE DECLARATION NAMES
77//!
78//! Every other row of every package is typed by this emission — a count, a fold word, a flavour
79//! request, another package. The `engine` row is not: its variants hold numbers in ENGINE
80//! currencies, and there is no blanket type for one. So the declaration writes
81//! `lance(resource = "path::To::Lance")`, the leaf grows an `@oneOf` over the words that did, and each
82//! variant projects `<T as VectorEngine>::Score` and `<T as VectorEngine>::SearchOptions` off the
83//! type its word named — the ruled per-variant shape `{floor, options}`. The teeth come free with
84//! the projection — a type implementing no engine trait is `E0277` where its author wrote it.
85//!
86//! It is ADDITIVE in both directions: an untyped word contributes no variant, and a slot whose
87//! words are all untyped grows no seat at all. Today's state IS the fallback.
88//!
89//! # `Option` EVERYWHERE HERE, and that is the de-Option law rather than a habit
90//!
91//! Every row of every package is an [`Option`], and every one of them DEFERS: a row nobody wrote
92//! takes the declaration's own — its declared fold, its declared floor. There is no value of any of
93//! these types that means *the declaration's*, so absence is the only spelling available and the law
94//! is satisfied rather than worked around. The two fields that do NOT defer are on [`Route`], where
95//! they are bare and carry their constants.
96//!
97//! A declared CEILING is not among them and cannot be: it is a WALL, so there is nothing for a
98//! request to defer to it with.
99
100use heck::{ToLowerCamelCase as _, ToShoutySnakeCase as _, ToUpperCamelCase as _};
101use quote::{format_ident, quote, quote_spanned};
102use syn::spanned::Spanned as _;
103
104use crate::{
105 emit::{framework, leading, substrate},
106 engine::FieldEngines,
107 index::{Elected, Fold, IndexGraphql, IndexModel, IndexRename, RenamePiece},
108 model::{GraphqlKind, NodeKind},
109};
110
111#[cfg(test)]
112mod columns;
113#[cfg(test)]
114mod doors;
115#[cfg(test)]
116mod engines;
117#[cfg(test)]
118mod fanned;
119#[cfg(test)]
120mod skins;
121#[cfg(test)]
122mod tests;
123
124/// ONE TIER of the fusion tree — a declaration, read for what it routes to.
125///
126/// A borrow of the lists [`IndexModel`] already holds rather than a second copy of them, for
127/// [`OptionsSpine`](crate::options::OptionsSpine)'s reason.
128#[derive(Debug, Clone, Copy)]
129pub struct Tier<'a> {
130 /// Where `ingraph` lives, as the declaration named it.
131 pub krate: &'a syn::Path,
132 /// The declaration's own visibility — what every emitted package takes.
133 pub vis: &'a syn::Visibility,
134 /// The declaration this tier is.
135 pub index: &'a syn::Ident,
136 /// WHICH of the three storages it is — the modality presence law's whole input.
137 pub kind: NodeKind,
138 /// The knn elections, in declared order — a vector tier's routes.
139 pub embeddings: &'a [Elected],
140 /// The searchable fields, in declared order — a full-text tier's ONE subject.
141 pub searchable: &'a [syn::Ident],
142 /// WHERE each election is written, kept in step with the lists above.
143 pub engines: &'a [FieldEngines],
144 /// WHAT EACH ELECTION WROTE ABOUT ITSELF — its numbers and its own skin blocks, kept in step with
145 /// the lists above for [`engines`](Self::engines)' reason.
146 ///
147 /// Here rather than left on [`IndexModel`] because the per-election TYPE seats
148 /// (`question(rename = …)`, `engines(rename = …)`) resolve inside [`Packages::sdl`], which is
149 /// reached from emitters that hold a tier and never the model. A seat the naming home cannot see
150 /// is a seat that silently falls back to the derived name.
151 pub field_numbers: &'a [crate::index::FieldNumbers],
152 /// WHICH BACKENDS DRESS THIS TIER — the declaration's `graphql(…)` block, or [`None`] where it
153 /// named none.
154 ///
155 /// Every package above is emitted whatever this holds. What it decides is the SKIN: the
156 /// hand-written faces below — [`input_face`](Self::input_face), [`oneof`](Self::oneof) and
157 /// [`enum_face`](Self::enum_face) — are one backend's impls over these types, and a declaration
158 /// that named no backend has no backend for them to be impls *for*.
159 pub graphql: Option<&'a IndexGraphql>,
160 /// WHAT THIS TIER'S MINTED RUST TYPES ARE CALLED — the declaration's top-level `rename`, or
161 /// [`None`] where its own ident is the base.
162 ///
163 /// Every `format_ident!` below reads [`base`](Self::base) or one of the named accessors rather
164 /// than [`index`](Self::index), which is what makes the roster the proof: a mint whose name did
165 /// not come through here would show up as a roster row the emission does not declare.
166 pub rename: Option<&'a IndexRename>,
167}
168
169/// WHICH of the three fused doors a tier emits — the ADDITIVE DOOR LAW, decided in one place.
170///
171/// # Additive, which is the whole of the ruling
172///
173/// The per-kind doors keep emitting at every level. These stand BESIDE them and never instead of
174/// them, so a tier that grows a second route of one modality grows a door and loses nothing: a
175/// client written against `retrieve_keys_by_<field>` goes on working the day the declaration fans.
176///
177/// # Two modalities, three doors, and the third is not a spelling of the first two
178///
179/// A tier with two full-text routes gets `fulltext_fuse` and a tier with two vector routes gets
180/// `vector_fuse`, because RRF over one modality is a pure question about that modality. `fuse` is
181/// the MIXED door and needs at least one route of EACH: over a single-modality route set it would
182/// be a second spelling of the modality door, which is two names for one behaviour and the thing
183/// this law exists to keep out.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct Doors {
186 /// `fulltext_fuse` — two or more full-text routes.
187 pub fulltext: bool,
188 /// `vector_fuse` — two or more vector routes.
189 pub vector: bool,
190 /// `fuse` — at least one route of EACH modality.
191 pub mixed: bool,
192}
193
194impl Doors {
195 /// The law itself, over one tier's per-modality route counts.
196 ///
197 /// A constructor over two numbers rather than a method on [`Tier`], because the ROOT tier's
198 /// counts come from its members' KINDS and an index tier's from its own elections — two callers,
199 /// one rule, and nowhere for the rule to be restated differently.
200 #[must_use]
201 pub const fn of(fulltext: usize, vector: usize) -> Self {
202 Self {
203 fulltext: fulltext >= 2,
204 vector: vector >= 2,
205 mixed: fulltext >= 1 && vector >= 1,
206 }
207 }
208
209 /// Whether this tier emits any fused door at all.
210 #[must_use]
211 pub const fn any(self) -> bool {
212 self.fulltext || self.vector || self.mixed
213 }
214}
215
216/// ONE ROW of an emitted package: a Rust member, the wire name it renders under, and the type it
217/// holds.
218///
219/// The struct field is `Option<ty>` in every case — see the module note's reading of the de-Option
220/// law — so the row carries the INTERIOR and the emission adds the wrapper.
221///
222/// PUBLIC because [`Packages`] is: the root grain builds its own rows and mints them through the
223/// same emitter, and a row it could not name is an emitter it could not reach.
224#[derive(Debug)]
225pub struct Row {
226 member: syn::Ident,
227 wire: String,
228 ty: proc_macro2::TokenStream,
229 noun: String,
230 crosses: bool,
231}
232
233/// The SCORE parameter one route's currency rides — `__INGRAPH_SCORE_<FIELD>__`.
234///
235/// # The `__…__` fence is the law and not a decoration
236///
237/// A per-route parameter is one per ROUTE, so a bare `S1`/`S2` would be a name minted from a
238/// counter — and a counter's names collide with whatever the declaring scope already calls `S1`.
239/// The fence is this crate's standing answer for every emitted ident: both ends reserved, the field
240/// it belongs to spelled inside it, so two routes cannot mint one name and no declaration can
241/// collide with either.
242///
243/// A FUNCTION and not a `format_ident!` at each site, because the evidence enum, the error enum and
244/// the doors all spell it — and a name spelled four times is a name that can drift.
245#[must_use]
246pub fn score_param(field: &syn::Ident) -> syn::Ident {
247 format_ident!(
248 "__INGRAPH_SCORE_{}__",
249 field.to_string().to_shouty_snake_case()
250 )
251}
252
253/// The ENGINE parameter one route is asked through — `__INGRAPH_ENGINE_<FIELD>__`, by
254/// [`score_param`]'s reading.
255#[must_use]
256pub fn engine_param(field: &syn::Ident) -> syn::Ident {
257 format_ident!(
258 "__INGRAPH_ENGINE_{}__",
259 field.to_string().to_shouty_snake_case()
260 )
261}
262
263/// The ERROR parameter one route's refusal rides — `__INGRAPH_ERROR_<FIELD>__`, by the same law.
264///
265/// It exists for the reason the per-route SCORE parameter does, one axis over: two engines have two
266/// `Error` types and there is no blanket one, so a door asking both routes has two refusals to carry
267/// and no single type to carry them in.
268#[must_use]
269pub fn error_param(field: &syn::Ident) -> syn::Ident {
270 format_ident!(
271 "__INGRAPH_ERROR_{}__",
272 field.to_string().to_shouty_snake_case()
273 )
274}
275
276/// A REFER-QUOTED path as the declaration wrote it, for a refusal that has to quote two of them and
277/// for the comparison that decides whether it is owed.
278///
279/// The tokens rather than the segments, because what two blocks have to agree on is the whole
280/// spelling — generic arguments included, a type being one type only with them.
281fn spelled(path: Option<&syn::Path>) -> String {
282 path.map_or_else(String::new, |path| {
283 quote!(#path).to_string().replace(' ', "")
284 })
285}
286
287/// The FIRST name two rows of one package share, if any — see [`Tier::shaped`] for what it costs a
288/// declaration that hits it.
289fn collision(rows: &[Row]) -> Option<String> {
290 let mut seen = std::collections::HashSet::new();
291 rows
292 .iter()
293 .find(|row| !seen.insert(row.member.to_string()))
294 .map(|row| row.member.to_string())
295}
296
297impl Row {
298 /// One row: the Rust member, the type it holds, and the noun its doc sentence uses.
299 #[must_use]
300 pub fn new(member: &syn::Ident, ty: proc_macro2::TokenStream, noun: &str) -> Self {
301 Self {
302 wire: member.to_string().to_lower_camel_case(),
303 member: member.clone(),
304 ty,
305 noun: noun.to_owned(),
306 crosses: true,
307 }
308 }
309
310 /// The same row, RUST-SIDE — present on the struct, absent from its wire face.
311 ///
312 /// # One row and not a whole package, which is what the measurement changed
313 ///
314 /// The question tree carried no face at all while `coordinates` was the reason: an
315 /// [`Embedding<E, N, S>`](../../ingraph/struct.Embedding.html) has no `async_graphql::InputType`
316 /// and cannot generically — its element type, width and space are all the declaration's — so
317 /// emitting one was `E0277` at the declaration. But the tree's OTHER rows cross fine: a question
318 /// is a `String`, and a child route is another question package. Refusing the whole tree for one
319 /// row's sake published nothing where the text half was always publishable.
320 ///
321 /// So the grain moves to the ROW. A package whose rows all cross is unchanged; a package holding
322 /// this one publishes the rest, and a request that reaches it leaves the row [`None`] — which is
323 /// what it means over the wire anyway, coordinates being the thing a client does not have.
324 ///
325 /// `to_value` omits it for the same reason, so the crossing is lossy in exactly one direction and
326 /// says so: a package built in Rust with coordinates and rendered to a `Value` renders its text.
327 /// The raw-coordinate wire form that would close the gap needs an element-typed list crossing into
328 /// `Embedding`, which nothing has yet.
329 #[must_use]
330 pub fn rust_side(mut self) -> Self {
331 self.crosses = false;
332 self
333 }
334}
335
336impl<'a> Tier<'a> {
337 /// The WHOLE emission: every package this declaration mints, and the impl that hands them up.
338 ///
339 /// Empty for a kind that does not retrieve, which is the presence law stated once.
340 #[must_use]
341 pub fn emit(&self) -> proc_macro2::TokenStream {
342 match self.kind {
343 NodeKind::Fulltext => self.fulltext(),
344 NodeKind::Vector => self.vector(),
345 NodeKind::Operator
346 | NodeKind::Entity
347 | NodeKind::Record
348 | NodeKind::Aggregate
349 | NodeKind::Blob => proc_macro2::TokenStream::new(),
350 }
351 }
352
353 /// Every (TYPE, METHOD) pair this tier mints, in emission order — the audits' half of [`emit`].
354 ///
355 /// One source of truth: each arm mirrors the predicate the emission itself asks (a `columns` seat
356 /// only where a vocabulary exists, a `semantics` row only on a set election, a mini tier only
357 /// where a slot fans), so a knob cannot be added without its roster row appearing beside it.
358 ///
359 /// [`emit`]: Self::emit
360 #[must_use]
361 pub fn emitted_methods(&self) -> Vec<(syn::Ident, syn::Ident)> {
362 let package = |on: &syn::Ident, members: &[syn::Ident]| {
363 let mut methods = vec![(on.clone(), format_ident!("new"))];
364 for member in members {
365 methods.push((on.clone(), format_ident!("with_{member}")));
366 methods.push((on.clone(), member.clone()));
367 }
368 methods
369 };
370 match self.kind {
371 NodeKind::Fulltext => {
372 let mut methods = Vec::new();
373 let mut rows: Vec<syn::Ident> = Vec::new();
374 if !self.searchable.is_empty() {
375 methods.push((self.column_name(), format_ident!("column")));
376 }
377 let typed = self.fulltext_typed().unwrap_or_default();
378 for engine in &typed {
379 methods.extend(package(
380 &self.engine_input(self.base(), engine),
381 &[format_ident!("floor"), format_ident!("options")],
382 ));
383 }
384 if !typed.is_empty() {
385 rows.push(format_ident!("engine"));
386 }
387 if !self.searchable.is_empty() {
388 rows.push(format_ident!("columns"));
389 }
390 let options = self.fulltext_options_name();
391 let asked = self.fulltext_question_name();
392 methods.extend(package(&options, &rows));
393 methods.extend(package(&asked, &[format_ident!("question")]));
394 methods
395 }
396 NodeKind::Vector => {
397 let mut methods = Vec::new();
398 for elected in self.embeddings {
399 if elected.label.is_set() {
400 methods.push((self.semantics_name(elected), format_ident!("with_fold")));
401 }
402 if self.fanned(elected) {
403 let mut rows = vec![format_ident!("fusion")];
404 let stem = self.stem(elected);
405 let typed = self.typed(elected);
406 for engine in &typed {
407 methods.extend(package(
408 &self.engine_input(&stem, engine),
409 &[format_ident!("floor")],
410 ));
411 }
412 if !typed.is_empty() {
413 rows.push(format_ident!("engine"));
414 }
415 if elected.label.is_set() {
416 rows.push(format_ident!("semantics"));
417 }
418 for engine in self.participants(elected) {
419 let leg = self.leg_options(elected, engine);
420 methods.extend(package(&leg, &[]));
421 rows.push(engine.word.clone());
422 }
423 methods.extend(package(&self.slot_options(elected), &rows));
424 } else {
425 let mut rows: Vec<syn::Ident> = Vec::new();
426 let stem = self.stem(elected);
427 let typed = self.typed(elected);
428 for engine in &typed {
429 methods.extend(package(
430 &self.engine_input(&stem, engine),
431 &[format_ident!("floor"), format_ident!("options")],
432 ));
433 }
434 if !typed.is_empty() {
435 rows.push(format_ident!("engine"));
436 }
437 if elected.label.is_set() {
438 rows.push(format_ident!("semantics"));
439 }
440 methods.extend(package(&self.slot_options(elected), &rows));
441 }
442 methods.extend(package(
443 &self.slot_question(elected),
444 &[format_ident!("question"), format_ident!("coordinates")],
445 ));
446 }
447 if self.embeddings.len() > 1 {
448 let mut rows = vec![format_ident!("fusion")];
449 rows.extend(self.embeddings.iter().map(|elected| elected.field.clone()));
450 let options = self.fuse_options_name();
451 methods.extend(package(&options, &rows));
452 let mut rows = vec![format_ident!("question")];
453 rows.extend(self.embeddings.iter().map(|elected| elected.field.clone()));
454 let asked = self.fuse_question_name();
455 methods.extend(package(&asked, &rows));
456 }
457 methods
458 }
459 NodeKind::Operator
460 | NodeKind::Entity
461 | NodeKind::Record
462 | NodeKind::Aggregate
463 | NodeKind::Blob => Vec::new(),
464 }
465 }
466
467 /// Every TYPE this tier lands in the declaring scope, in emission order — [`emitted_methods`]'
468 /// one-level-up half, by the same mirroring rule.
469 ///
470 /// [`emitted_methods`]: Self::emitted_methods
471 #[must_use]
472 pub fn emitted_types(&self) -> Vec<syn::Ident> {
473 match self.kind {
474 NodeKind::Fulltext => {
475 let mut types = Vec::new();
476 if !self.searchable.is_empty() {
477 types.push(self.column_name());
478 }
479 let typed = self.fulltext_typed().unwrap_or_default();
480 types.extend(
481 typed
482 .iter()
483 .map(|engine| self.engine_input(self.base(), engine)),
484 );
485 if !typed.is_empty() {
486 types.push(self.minted(RenamePiece::EngineInput, "EngineInput"));
487 }
488 types.push(self.fulltext_options_name());
489 types.push(self.fulltext_question_name());
490 types
491 }
492 NodeKind::Vector => {
493 let mut types = Vec::new();
494 for elected in self.embeddings {
495 if elected.label.is_set() {
496 types.push(self.semantics_name(elected));
497 }
498 let stem = self.stem(elected);
499 let typed = self.typed(elected);
500 if self.fanned(elected) {
501 for engine in self.participants(elected) {
502 types.push(self.leg_options(elected, engine));
503 }
504 }
505 types.extend(typed.iter().map(|engine| self.engine_input(&stem, engine)));
506 if !typed.is_empty() {
507 types.push(format_ident!("{stem}EngineInput"));
508 }
509 types.push(self.slot_options(elected));
510 if self.fanned(elected) {
511 types.push(self.slot_evidence_name(elected));
512 types.push(self.slot_error_name(elected));
513 }
514 types.push(self.slot_question(elected));
515 }
516 if self.embeddings.len() > 1 {
517 types.push(self.fuse_options_name());
518 types.push(self.fuse_question_name());
519 }
520 if self.doors().any() {
521 types.push(self.evidence_name());
522 types.push(self.fused_error_name());
523 }
524 types
525 }
526 NodeKind::Operator
527 | NodeKind::Entity
528 | NodeKind::Record
529 | NodeKind::Aggregate
530 | NodeKind::Blob => Vec::new(),
531 }
532 }
533
534 /// This tier's `Fusable::Options` — the binding table's pick, or [`None`] where the kind does not
535 /// retrieve.
536 #[must_use]
537 pub fn options_name(&self) -> Option<syn::Ident> {
538 match self.kind {
539 NodeKind::Fulltext => Some(self.fulltext_options_name()),
540 NodeKind::Vector => Some(match self.embeddings {
541 [only] => self.slot_options(only),
542 _ => self.fuse_options_name(),
543 }),
544 NodeKind::Operator
545 | NodeKind::Entity
546 | NodeKind::Record
547 | NodeKind::Aggregate
548 | NodeKind::Blob => None,
549 }
550 }
551
552 /// This tier's `Fusable::Question` — the sister tree's pick, by the same table.
553 #[must_use]
554 pub fn question_name(&self) -> Option<syn::Ident> {
555 match self.kind {
556 NodeKind::Fulltext => Some(self.fulltext_question_name()),
557 NodeKind::Vector => Some(match self.embeddings {
558 [only] => self.slot_question(only),
559 _ => self.fuse_question_name(),
560 }),
561 NodeKind::Operator
562 | NodeKind::Entity
563 | NodeKind::Record
564 | NodeKind::Aggregate
565 | NodeKind::Blob => None,
566 }
567 }
568
569 /// The `Fusable` impl — the one item a PARENT ever reaches, and the reason a parent needs to know
570 /// none of the names above.
571 fn fusable(&self, options: &syn::Ident, question: &syn::Ident) -> proc_macro2::TokenStream {
572 let Tier { krate, index, .. } = self;
573 let fusable = framework(krate, &["retrieve"], "Fusable");
574 quote! {
575 const _: () = {
576 #[automatically_derived]
577 impl #fusable for #index {
578 type Options = #options;
579 type Question = #question;
580 }
581 };
582 }
583 }
584
585 /// The PACKAGE EMITTER this tier mints through — see [`Packages`] for what moved off `Tier` and
586 /// why.
587 #[must_use]
588 pub fn packages(&self) -> Packages<'a> {
589 Packages {
590 krate: self.krate,
591 vis: self.vis,
592 owner: self.index,
593 graphql: self.graphql,
594 base: self.base(),
595 members: self.face_overrides(),
596 }
597 }
598
599 /// EVERY PER-FACE OVERRIDE this declaration wrote, resolved to the minted name each moves.
600 ///
601 /// # Two grains in one list, because the resolution is one question
602 ///
603 /// The HEAD's three seats name the packages a parent absorbs and the selector over the typed
604 /// engines. An ELECTION's four are its own two sides: the pair a request BUILDS by hand — the
605 /// `@oneOf` it states a point in and the product it states a floor per leg in — and the pair a
606 /// request READS, the fused answer's union and the row that carries it. Both grains are answered
607 /// by [`Packages::sdl`], which is handed a minted Rust name and nothing else, so both have to be
608 /// resolved to that name HERE: the alternative is two lookups in the naming home, one of which a
609 /// later face would forget.
610 ///
611 /// A seat whose target this declaration does not mint contributes NOTHING rather than a row that
612 /// matches no name — `options_name` and its neighbours already answer [`None`] on a kind that
613 /// mints none, and an election that is not fanned mints no `<Stem>Engines`. The word is then
614 /// simply unspent, which is the same state the flat road words have always been in on a shape that
615 /// does not publish their road.
616 fn face_overrides(&self) -> Vec<(syn::Ident, syn::LitStr)> {
617 let mut members = Vec::new();
618 let mut push = |face: Option<syn::Ident>, spelled: Option<&syn::LitStr>| {
619 if let (Some(face), Some(spelled)) = (face, spelled) {
620 members.push((face, spelled.clone()));
621 }
622 };
623 if let Some(skin) = self
624 .graphql
625 .and_then(|block| block.skin(GraphqlKind::AsyncGraphql))
626 {
627 push(self.options_name(), skin.options.as_ref());
628 push(self.question_name(), skin.question.as_ref());
629 push(self.engine_selector(), skin.engine.as_ref());
630 }
631 for elected in self.embeddings {
632 let Some(skin) = self
633 .field_numbers
634 .iter()
635 .find(|written| written.field == elected.field)
636 .and_then(|written| written.skin(GraphqlKind::AsyncGraphql))
637 else {
638 continue;
639 };
640 let stem = self.stem(elected);
641 push(
642 Some(format_ident!("{stem}Question")),
643 skin.question.as_ref(),
644 );
645 push(Some(format_ident!("{stem}Engines")), skin.engines.as_ref());
646 // THE ANSWER SIDE's two, resolved the same way the request side's are: a seat whose target
647 // this election does not mint — an election that is not fanned mints neither of these —
648 // contributes a pair the lookup below never matches, which is the unspent state the doc above
649 // states for every other word here.
650 push(
651 Some(format_ident!("{stem}Sighting")),
652 skin.sighting.as_ref(),
653 );
654 push(
655 Some(format_ident!("{stem}FusedKeyMatch")),
656 skin.fused_key_match.as_ref(),
657 );
658 }
659 members
660 }
661
662 /// ONE ROUTE's options package, as a PARENT names it — [`slot_options`](Self::slot_options) under
663 /// the fused doors' own noun, so an emitter reading routes is not reading about slots.
664 #[must_use]
665 pub fn route_options(&self, elected: &Elected) -> syn::Ident {
666 self.slot_options(elected)
667 }
668
669 /// ONE ROUTE's question package, by the same reading.
670 #[must_use]
671 pub fn route_question(&self, elected: &Elected) -> syn::Ident {
672 self.slot_question(elected)
673 }
674
675 /// ONE ELECTION's options package — the mini tier where the slot is fanned, the flat leaf where it
676 /// is not.
677 fn slot_options(&self, elected: &Elected) -> syn::Ident {
678 let field = elected.field.to_string().to_upper_camel_case();
679 if self.fanned(elected) {
680 format_ident!("{}{field}FuseOptions", self.base())
681 } else {
682 format_ident!("{}{field}VectorOptions", self.base())
683 }
684 }
685
686 /// ONE ELECTION's question package — the same for a fanned slot and a flat one, because the legs
687 /// are one field's coordinates in several stores.
688 fn slot_question(&self, elected: &Elected) -> syn::Ident {
689 let field = elected.field.to_string().to_upper_camel_case();
690 format_ident!("{}{field}VectorQuestion", self.base())
691 }
692
693 /// The wire FOLD vocabulary of one set election.
694 fn semantics_name(&self, elected: &Elected) -> syn::Ident {
695 let field = elected.field.to_string().to_upper_camel_case();
696 format_ident!("{}{field}Semantics", self.base())
697 }
698
699 /// Whether this election's slot is a TIER — a fan whose legs form a leaderboard.
700 ///
701 /// # `fanout` is the write half and `rrf` is the read half, and BOTH are asked here
702 ///
703 /// A fan writes every declared engine at once, and what the fan is FOR is the question `rrf`
704 /// answers: a LEADERBOARD, where each leg's ranking is separate evidence a fold joins, or
705 /// REDUNDANCY, where one content lives in several stores and a read comes from one of them.
706 ///
707 /// So the count is over PARTICIPANTS rather than over legs, and the two degenerate cases fall out
708 /// of the one rule the top-level tier already states — *a one-route tier IS its route, and a fuse
709 /// package above one route would be a fold over a list of one*:
710 ///
711 /// | participants | the slot's package |
712 /// |---|---|
713 /// | 0 — every leg `rrf = false` | the FLAT leaf: pure multi-write, the fused face absent entirely |
714 /// | 1 | the FLAT leaf: one route is its own tier |
715 /// | ≥ 2 | the mini TIER: `fusion`, one `Route` seat per participant, and the mini fuse door |
716 ///
717 /// The SELECTOR seat is orthogonal to all of it and rides both shapes — see
718 /// [`typed`](Self::typed), whose input is the legs a `resource =` word made ADDRESSABLE regardless of
719 /// what `rrf` says about them.
720 pub(crate) fn fanned(&self, elected: &Elected) -> bool {
721 self.engines.iter().any(|engines| {
722 engines.field == elected.field && engines.fanout && engines.participants().count() > 1
723 })
724 }
725
726 /// The engines one election declared, in written order.
727 fn legs(&self, elected: &Elected) -> &'a [crate::engine::Engine] {
728 self
729 .engines
730 .iter()
731 .find(|engines| engines.field == elected.field)
732 .map_or(&[][..], |engines| &engines.engines)
733 }
734
735 /// The legs of one election that ENTER its fused road, in written order — the `rrf` half.
736 fn participants(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
737 self
738 .legs(elected)
739 .iter()
740 .filter(|engine| engine.rrf)
741 .collect()
742 }
743
744 /// The legs one fanned slot's ANSWER can name — its participants, plus every leg a `resource =` word
745 /// made directly readable.
746 ///
747 /// # It is a UNION, and the fourth quadrant is why
748 ///
749 /// `resource =` is addressability and `rrf =` is leaderboard membership, and the orthogonality law
750 /// says all four combinations mean something. A TYPED, NON-PARTICIPATING leg is the third
751 /// quadrant: not in the fold, but nameable by a request through the selector seat — and a request
752 /// that names it is answered in the SAME shape as the fused road, so the evidence enum needs a
753 /// variant for it or the direct read has nothing to report its provenance in.
754 ///
755 /// The fused road never constructs those variants; the selector road never constructs more than
756 /// one. Both halves are the same type, which is what *answering the same wire shape* costs and
757 /// buys.
758 fn evidence_legs(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
759 self
760 .legs(elected)
761 .iter()
762 .filter(|engine| engine.rrf || engine.resource.is_some())
763 .collect()
764 }
765
766 /// The routes this tier contributes to a FUSED door, by modality — the door law's whole input.
767 ///
768 /// # A full-text tier is ONE route however many fields it elects
769 ///
770 /// `FulltextRead::search` takes no column selector at the route grain: an elected field is a
771 /// COLUMN of one subject rather than a subject of its own, which is what the `columns` row on the
772 /// package says. So the count is one wherever anything is elected, and a full-text declaration
773 /// never reaches its own `fulltext_fuse` — that door's home is a SEARCH RECIPE, where two
774 /// full-text MEMBERS can meet.
775 ///
776 /// # A SET election is not a route, and that is a measurement
777 ///
778 /// RRF reads an ORDINAL, and `fuse`'s own note says which one: the hit's position in the
779 /// ENGINE's raw stream. A `list(embedding)` election answers in [`Folded`], whose order the FOLD
780 /// authored — there are `m` engine streams and deliberately no ordinal minted across them, so
781 /// there is no number to hand the fold that means what it reads. Passing the folded answer's
782 /// POSITION would produce a perfectly ordered result on every fixture whose floor let everything
783 /// through, which is exactly the silent defect `fuse` warns about.
784 ///
785 /// The RRF-as-fold citizen that would close this is lettered in the β4 supplement and
786 /// deliberately unbuilt, so a set election is absent from the walk at EMISSION — a compile-time
787 /// absence with a name, rather than a route that silently contributes the wrong number.
788 ///
789 /// [`Folded`]: ../../ingraph/retrieve/struct.Folded.html
790 #[must_use]
791 pub fn doors(&self) -> Doors {
792 match self.kind {
793 NodeKind::Fulltext => Doors::of(usize::from(!self.searchable.is_empty()), 0),
794 NodeKind::Vector => Doors::of(0, self.fused_routes().count()),
795 NodeKind::Operator
796 | NodeKind::Entity
797 | NodeKind::Record
798 | NodeKind::Aggregate
799 | NodeKind::Blob => Doors::of(0, 0),
800 }
801 }
802
803 /// The elections that ENTER this tier's fused doors, in declared order — see [`doors`] for why a
804 /// set election is not among them.
805 ///
806 /// [`doors`]: Self::doors
807 pub fn fused_routes(&self) -> impl Iterator<Item = &'a Elected> {
808 self
809 .embeddings
810 .iter()
811 .filter(|elected| !elected.label.is_set())
812 }
813
814 /// THE BASE EVERY MINTED NAME IS BUILT ON — the declaration's top-level `rename`, or its own
815 /// ident. [`IndexModel::base`]'s answer, read through the borrow this tier holds.
816 #[must_use]
817 pub fn base(&self) -> &'a syn::Ident {
818 self
819 .rename
820 .and_then(IndexRename::base)
821 .unwrap_or(self.index)
822 }
823 /// The `@oneOf` SELECTOR this declaration mints, where it mints exactly one.
824 ///
825 /// [`None`] where there is none to name and where there are SEVERAL — a vector electing two typed
826 /// fields has one selector per field, and `engine(rename = …)` names a face rather than a set, so
827 /// it is refused at the front end rather than applied to whichever came first.
828 fn engine_selector(&self) -> Option<syn::Ident> {
829 match self.kind {
830 // The refused fork — one word bound to two types — has no selector to name, so it answers here
831 // exactly as an untyped declaration does. The refusal itself is the emission's.
832 NodeKind::Fulltext => self
833 .fulltext_typed()
834 .ok()
835 .filter(|typed| !typed.is_empty())
836 .map(|_| self.minted(RenamePiece::EngineInput, "EngineInput")),
837 NodeKind::Vector => {
838 let mut seats = self
839 .embeddings
840 .iter()
841 .filter(|elected| !self.fanned(elected) && !self.typed(elected).is_empty())
842 .map(|elected| format_ident!("{}EngineInput", self.stem(elected)));
843 seats.next().filter(|_| seats.next().is_none())
844 }
845 NodeKind::Operator
846 | NodeKind::Entity
847 | NodeKind::Record
848 | NodeKind::Aggregate
849 | NodeKind::Blob => None,
850 }
851 }
852
853 /// ONE MINT'S NAME — what the declaration called `piece`, or `<base><suffix>` where it named that
854 /// one nothing.
855 ///
856 /// THE NAMING HOME for every type the piece vocabulary covers, so that a rename cannot reach the
857 /// emission and miss the roster: `emitted_types` calls these same accessors, and the audit that
858 /// walks the emission against the roster is what proves the two agree.
859 fn minted(&self, piece: RenamePiece, suffix: &str) -> syn::Ident {
860 self
861 .rename
862 .and_then(|rename| rename.piece(piece))
863 .map_or_else(|| format_ident!("{}{suffix}", self.base()), Clone::clone)
864 }
865
866 /// WHY THIS DECLARATION MINTS NO `piece`, or [`None`] where it mints exactly one.
867 ///
868 /// The predicate the front end's named-mint audit spends, written HERE because every clause is a
869 /// fact about the emission: which packages a tier lands is decided a few lines up, and a second
870 /// copy of that decision in the grammar is how the two come to disagree.
871 ///
872 /// Each arm mirrors the condition the emitter itself asks, so a mint cannot become conditional
873 /// without its clause appearing beside it.
874 #[must_use]
875 pub fn unmintable(&self, piece: RenamePiece) -> Option<&'static str> {
876 let vector = self.kind == NodeKind::Vector;
877 let fulltext = self.kind == NodeKind::Fulltext;
878 match piece {
879 RenamePiece::FuseOptions | RenamePiece::FuseQuestion => (vector
880 && self.embeddings.len() > 1)
881 .then_some(())
882 .map_or(
883 Some(
884 "the multi-route packages belong to a VECTOR declaration electing two or more fields. \
885 One election's package IS the tier's — a route with nothing to fuse against — and a \
886 full-text declaration is one route however many fields it elects",
887 ),
888 |()| None,
889 ),
890 RenamePiece::FulltextOptions | RenamePiece::FulltextQuestion => fulltext.then_some(()).map_or(
891 Some(
892 "the full-text packages belong to a `fulltext` declaration. A vector tier's are \
893 `fuse_options` and `fuse_question`, or the slot's own where it elects one field",
894 ),
895 |()| None,
896 ),
897 RenamePiece::Evidence => self.doors().any().then_some(()).map_or(
898 Some(
899 "the evidence is what a FUSED DOOR answers with, and this declaration grows none: a \
900 fused door needs two or more routes of one modality, and a SET election is not among \
901 them",
902 ),
903 |()| None,
904 ),
905 RenamePiece::EngineInput => self.engine_selector().is_some().then_some(()).map_or(
906 Some(
907 "the selector is minted where a declaration TYPED an engine word — \
908 `lance(resource = \"path::To::Lance\")` — and where it mints exactly ONE. A declaration \
909 typing several elections mints one selector per field, and a word naming an individual \
910 mint has no way to say which; `rename = \"NewBase\"` re-bases them all",
911 ),
912 |()| None,
913 ),
914 RenamePiece::Column => (fulltext && !self.searchable.is_empty()).then_some(()).map_or(
915 Some(
916 "the column vocabulary is a FULL-TEXT declaration's, minted from the fields it elected — \
917 a vector retrieve narrows by election rather than by column",
918 ),
919 |()| None,
920 ),
921 }
922 }
923
924 /// `<Index>FuseOptions` — a vector tier's multi-route options package.
925 #[must_use]
926 pub fn fuse_options_name(&self) -> syn::Ident {
927 self.minted(RenamePiece::FuseOptions, "FuseOptions")
928 }
929
930 /// `<Index>FuseQuestion` — its sister.
931 #[must_use]
932 pub fn fuse_question_name(&self) -> syn::Ident {
933 self.minted(RenamePiece::FuseQuestion, "FuseQuestion")
934 }
935
936 /// `<Index>FulltextOptions` — a full-text tier's options package.
937 #[must_use]
938 pub fn fulltext_options_name(&self) -> syn::Ident {
939 self.minted(RenamePiece::FulltextOptions, "FulltextOptions")
940 }
941
942 /// `<Index>FulltextQuestion` — its sister.
943 #[must_use]
944 pub fn fulltext_question_name(&self) -> syn::Ident {
945 self.minted(RenamePiece::FulltextQuestion, "FulltextQuestion")
946 }
947
948 /// This tier's EVIDENCE enum — `<Index>FusedEvidence<S₁, …>`, one variant AND ONE CURRENCY per
949 /// fused route.
950 #[must_use]
951 pub fn evidence_name(&self) -> syn::Ident {
952 self.minted(RenamePiece::Evidence, "FusedEvidence")
953 }
954
955 /// This tier's fused REFUSAL enum — `<Index>FusedError<E₁, …>`, one variant per fused route.
956 #[must_use]
957 pub fn fused_error_name(&self) -> syn::Ident {
958 format_ident!("{}FusedError", self.base())
959 }
960
961 /// ONE FANNED SLOT's evidence enum — `<Index><Field>FusedEvidence<S₁, …>`, the tier's own type at
962 /// slot grain.
963 #[must_use]
964 pub fn slot_evidence_name(&self, elected: &Elected) -> syn::Ident {
965 format_ident!(
966 "{}{}FusedEvidence",
967 self.base(),
968 elected.field.to_string().to_upper_camel_case()
969 )
970 }
971
972 /// ONE FANNED SLOT's refusal enum — `<Index><Field>FusedError<E₁, …>`.
973 #[must_use]
974 pub fn slot_error_name(&self, elected: &Elected) -> syn::Ident {
975 format_ident!(
976 "{}{}FusedError",
977 self.base(),
978 elected.field.to_string().to_upper_camel_case()
979 )
980 }
981
982 /// The ELECTIONS whose slot gets a MINI FUSE DOOR, in declared order.
983 ///
984 /// A fanned tier ([`fanned`](Self::fanned)) that is not a SET election, and the second half is
985 /// [`doors`](Self::doors)' own measurement read one grain down: RRF reads the ordinal an engine
986 /// gave a hit, a `list(embedding)` election answers in `Folded` whose order the FOLD authored, and
987 /// there is no number across its `m` streams that means what RRF reads. The exclusion is
988 /// therefore at EMISSION on both grains rather than stated once and forgotten on the other.
989 ///
990 /// The PACKAGES are not gated by this: a fanned set slot still mints its mini tier, because that
991 /// package describes the write fan and crosses the wire. What it does not get is a door.
992 pub fn fanned_slots(&self) -> impl Iterator<Item = &'a Elected> {
993 self
994 .embeddings
995 .iter()
996 .filter(|elected| self.fanned(elected) && !elected.label.is_set())
997 }
998
999 /// The legs one fanned slot's mini door asks and answers over, in written order — public for the
1000 /// door emitter, which lives a module away.
1001 #[must_use]
1002 pub fn slot_legs(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
1003 self.evidence_legs(elected)
1004 }
1005
1006 /// The legs one fanned slot's FUSED road walks, in written order.
1007 #[must_use]
1008 pub fn slot_participants(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
1009 self.participants(elected)
1010 }
1011
1012 /// ONE fanned slot's `Route`-wrapped leg package, as the mini door's edge reader names it.
1013 #[must_use]
1014 pub fn slot_leg_options(&self, elected: &Elected, engine: &crate::engine::Engine) -> syn::Ident {
1015 self.leg_options(elected, engine)
1016 }
1017
1018 /// THE DECLARATION'S OWN `engine` SELECTOR, where it mints exactly one — what a FULL-TEXT wire
1019 /// leg reads its floor and its knobs out of.
1020 ///
1021 /// A full-text declaration is ONE ROUTE however many fields it elects, so its selector is at the
1022 /// declaration grain where a vector election's is per field. This is deliberately not a second
1023 /// road to the same answer: `engine_selector` holds the whole rule, and this only makes it
1024 /// reachable from the emitter.
1025 #[must_use]
1026 pub fn subject_selector(&self) -> Option<syn::Ident> {
1027 self.engine_selector()
1028 }
1029
1030 /// ONE fanned slot's `engine` SELECTOR enum, where the slot has one — `<Index><Field>EngineInput`.
1031 #[must_use]
1032 pub fn slot_selector(&self, elected: &Elected) -> Option<syn::Ident> {
1033 let stem = self.stem(elected);
1034 (!self.typed(elected).is_empty()).then(|| format_ident!("{stem}EngineInput"))
1035 }
1036
1037 /// The per-route generic parameters this tier's fused door takes, in route order — the ENGINE, the
1038 /// currency it scores in, and the refusal it can speak.
1039 ///
1040 /// One list rather than three walks, because all three are read together everywhere they are read
1041 /// and a route's three names have to stay in step.
1042 pub fn route_params(&self) -> impl Iterator<Item = (&'a Elected, syn::Ident, syn::Ident)> {
1043 self.fused_routes().map(|elected| {
1044 (
1045 elected,
1046 engine_param(&elected.field),
1047 score_param(&elected.field),
1048 )
1049 })
1050 }
1051
1052 /// The evidence enum a fused door answers with: WHICH route agreed about a root, and at what
1053 /// score in that route's own currency.
1054 ///
1055 /// # Generic where every package is concrete, and the engine is why
1056 ///
1057 /// A package holds a request and is built before any engine is named. Evidence is what a door
1058 /// ANSWERS, and a door is generic over the engines it asked — so the score's type is
1059 /// `<E as VectorEngine>::Score` at the call, and the enum carries it as a parameter rather than
1060 /// picking a width no engine agreed to.
1061 ///
1062 /// # ONE PARAMETER PER ROUTE, which is the heterogeneous door's whole shape
1063 ///
1064 /// It carried ONE `__INGRAPH_SCORE__` while the door took one engine, and that was the SAME-ENGINE
1065 /// special case wearing the general name: two routes written in two stores score in two
1066 /// currencies, and a single parameter forced them to be one type. Each variant now holds its own
1067 /// route's currency, so `ShotsClipFusedEvidence<f64, f32>` is a sentence the type system can say —
1068 /// and the homogeneous tier writes the same width twice, which is the degenerate case rather than
1069 /// a second shape.
1070 ///
1071 /// # The score is carried and never compared ACROSS variants
1072 ///
1073 /// Two routes' scores are two currencies, which is the whole reason the fold reads ordinals. What
1074 /// the evidence is for is telling a client WHICH routes agreed — the arithmetic already happened,
1075 /// and `FusedScore` is where its answer is. RRF is untouched by the widening for exactly that
1076 /// reason: it never read a score to begin with.
1077 fn evidence(&self) -> proc_macro2::TokenStream {
1078 let Tier { vis, .. } = self;
1079 let name = self.evidence_name();
1080 let params: Vec<syn::Ident> = self
1081 .fused_routes()
1082 .map(|elected| score_param(&elected.field))
1083 .collect();
1084 let variants = self.fused_routes().map(|elected| {
1085 let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
1086 let score = score_param(&elected.field);
1087 let doc = leading(&format!(
1088 "`{field}` ranked this root, at `{field}`'s own score — in `{field}`'s OWN engine's \
1089 currency, which no other variant's is.",
1090 field = elected.field,
1091 ));
1092 quote! {
1093 #[doc = #doc]
1094 #variant(#score)
1095 }
1096 });
1097 let doc = leading(&format!(
1098 "WHICH of [`{index}`]'s routes agreed about a fused root, and what each of them scored it — \
1099 the answer's provenance, one variant per route that enters a fused door, each in that \
1100 route's own engine's currency.",
1101 index = self.index,
1102 ));
1103 quote! {
1104 #[doc = #doc]
1105 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
1106 #vis enum #name<#(#params,)*> {
1107 #(#variants,)*
1108 }
1109 }
1110 }
1111
1112 /// The REFUSAL enum a heterogeneous fused door answers with: WHICH route refused, in that route's
1113 /// own engine's vocabulary.
1114 ///
1115 /// # It is forced by the per-route engine, exactly as the evidence enum is
1116 ///
1117 /// A door over one engine refuses in `<E as VectorEngine>::Error`. A door over N engines has N of
1118 /// those and no blanket type to unify them — the same wall the score hit one row up, and the same
1119 /// answer: one parameter per route, one variant per route, and the ROUTE NAMED. A caller learns
1120 /// which store failed rather than being handed an error whose provenance the fold ate.
1121 ///
1122 /// The backend's own error is carried WHOLE and untranslated, which is
1123 /// [`OwnReadError`](../../ingraph/retrieve/enum.OwnReadError.html)'s law read onto this axis.
1124 fn fused_error(&self) -> proc_macro2::TokenStream {
1125 let Tier { vis, .. } = self;
1126 let name = self.fused_error_name();
1127 let params: Vec<syn::Ident> = self
1128 .fused_routes()
1129 .map(|elected| error_param(&elected.field))
1130 .collect();
1131 let variants = self.fused_routes().map(|elected| {
1132 let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
1133 let error = error_param(&elected.field);
1134 let doc = leading(&format!(
1135 "`{field}`'s own engine refused, in that engine's own vocabulary.",
1136 field = elected.field,
1137 ));
1138 quote! {
1139 #[doc = #doc]
1140 #variant(#error)
1141 }
1142 });
1143 let arms = self.fused_routes().map(|elected| {
1144 let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
1145 let field = elected.field.to_string();
1146 quote! {
1147 Self::#variant(__ingraph_refusal) => {
1148 ::core::write!(__ingraph_formatter, "{}: {__ingraph_refusal}", #field)
1149 }
1150 }
1151 });
1152 let sources = self.fused_routes().map(|elected| {
1153 let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
1154 quote!(Self::#variant(__ingraph_refusal) => ::core::option::Option::Some(__ingraph_refusal))
1155 });
1156 let displays = params
1157 .iter()
1158 .map(|param| quote!(#param: ::core::fmt::Display));
1159 let errors = params
1160 .iter()
1161 .map(|param| quote!(#param: ::core::error::Error + 'static));
1162 let doc = leading(&format!(
1163 "WHICH of [`{index}`]'s routes refused a fused query, in that route's own engine's \
1164 vocabulary — one variant per route that enters a fused door.",
1165 index = self.index,
1166 ));
1167 let why = leading(
1168 "A route's engine is its own, so its refusal is its own: a door asking two stores has two \
1169 error types and no blanket one to widen them into. The route is NAMED rather than erased, \
1170 which is what lets a caller tell *the vector store is down* from *the text store is down*.",
1171 );
1172 quote! {
1173 #[doc = #doc]
1174 #[doc = ""]
1175 #[doc = #why]
1176 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
1177 #vis enum #name<#(#params,)*> {
1178 #(#variants,)*
1179 }
1180
1181 #[automatically_derived]
1182 impl<#(#displays,)*> ::core::fmt::Display for #name<#(#params,)*> {
1183 fn fmt(
1184 &self,
1185 __ingraph_formatter: &mut ::core::fmt::Formatter<'_>,
1186 ) -> ::core::fmt::Result {
1187 match self {
1188 #(#arms,)*
1189 }
1190 }
1191 }
1192
1193 #[automatically_derived]
1194 impl<#(#errors,)*> ::core::error::Error for #name<#(#params,)*> {
1195 fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
1196 match self {
1197 #(#sources,)*
1198 }
1199 }
1200 }
1201 }
1202 }
1203
1204 /// The engines of ONE election that NAMED A TYPE, in written order — the `engine` seat's whole
1205 /// input at a vector leaf.
1206 pub(crate) fn typed(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
1207 self
1208 .legs(elected)
1209 .iter()
1210 .filter(|engine| engine.resource.is_some())
1211 .collect()
1212 }
1213
1214 /// The engines a FULL-TEXT declaration typed, deduplicated by word — its ONE route's vocabulary.
1215 ///
1216 /// The union across the declaration's fields rather than one field's, because a full-text tier is
1217 /// ONE route however many fields it elects and its package is one: the words a request can name
1218 /// are the words this declaration writes anywhere. Two fields repeating a word is the ordinary
1219 /// shape — *that is two slots rather than a repeat* — and it dedups silently while they agree.
1220 ///
1221 /// [`Err`] where they do not: one word naming two engine types is one vocabulary with two
1222 /// meanings, refused BY NAME here rather than left to `E0308` inside a package nobody wrote.
1223 fn fulltext_typed(&self) -> Result<Vec<&'a crate::engine::Engine>, proc_macro2::TokenStream> {
1224 let mut typed: Vec<&'a crate::engine::Engine> = Vec::new();
1225 for engine in self
1226 .engines
1227 .iter()
1228 .flat_map(|declared| declared.engines.iter())
1229 .filter(|engine| engine.resource.is_some())
1230 {
1231 match typed.iter().find(|first| first.word == engine.word) {
1232 None => typed.push(engine),
1233 Some(first) if spelled(first.resource.as_ref()) == spelled(engine.resource.as_ref()) => {}
1234 Some(first) => {
1235 let refusal = format!(
1236 "`{index}` binds `{word}` to `{first}` on one field and to `{second}` on another, and a \
1237 full-text declaration is ONE ROUTE — its `engine` seat holds one vocabulary, so a word \
1238 in it names one engine. Write the same type on both blocks, or give the second engine \
1239 a word of its own",
1240 index = self.index,
1241 word = engine.word,
1242 first = spelled(first.resource.as_ref()),
1243 second = spelled(engine.resource.as_ref()),
1244 );
1245 return Err(quote!(::core::compile_error!(#refusal);));
1246 }
1247 }
1248 }
1249 Ok(typed)
1250 }
1251
1252 /// The ENGINE SEAM this kind's declared types are asked to implement — the trait a floor's
1253 /// currency is projected through, and the E0277 a wrong type lands on.
1254 fn seam(&self) -> proc_macro2::TokenStream {
1255 match self.kind {
1256 NodeKind::Fulltext => framework(self.krate, &["store"], "FulltextEngine"),
1257 _ => framework(self.krate, &["store"], "VectorEngine"),
1258 }
1259 }
1260
1261 /// The `engine` SEAT of one leaf: the per-word variant packages, the `@oneOf` over them, and the
1262 /// row the leaf carries — or nothing at all where no word named a type.
1263 ///
1264 /// # The floor is INSIDE the variant, and that is the `FloorSpec` law reaching the wire
1265 ///
1266 /// A floor is a number in ONE engine's currency: a cosine distance and a BM25 relevance are not
1267 /// the same kind of thing, and there is no type that is both. A blanket `floor` row on the leaf
1268 /// would have to pick one, so the row lives one level down where the engine is known and its
1269 /// currency is `<T as Engine>::Score` — projected off the type the declaration NAMED, so two
1270 /// engines scoring in two widths publish two rows at two scalar types.
1271 ///
1272 /// # The `@oneOf` is uniform at ONE variant, and that is deliberate
1273 ///
1274 /// A slot naming one typed engine still publishes the choice-shaped input. A second engine is then
1275 /// an added variant rather than a changed shape, which is the difference between a client that
1276 /// keeps working and one that has to be rewritten the day a deployment fans.
1277 ///
1278 /// # The `options` row is the floor's twin, and it completes the ruled shape `{floor, options}`
1279 ///
1280 /// A floor is a number in the engine's SCORE currency; `options` is everything else the engine
1281 /// takes per QUERY, in its own vocabulary — `<T as Engine>::SearchOptions`, projected off the
1282 /// same named type by the same rule. Two rows rather than one because they are answered by two
1283 /// different members and a backend commonly has one and not the other: a score currency every
1284 /// engine has, where per-query knobs are a thing many engines simply do not take.
1285 ///
1286 /// The WIRE DUTY the projection creates is the third party's and is the same duty `floor` already
1287 /// carries: an engine a declaration NAMES publishes both types. An engine with no per-query knobs
1288 /// writes the framework's `Noop`, a GraphQL input object being unable to hold zero fields;
1289 /// `()` stays the answer for every engine no typed word names.
1290 ///
1291 /// # The TEETH are the projection itself
1292 ///
1293 /// `<T as VectorEngine>::Score` is `E0277` at the declaration when `T` implements no such trait,
1294 /// naming the type the author wrote — no marker trait, no check to forget. The derive list adds
1295 /// its own obligations to the same span: a floor is compared, cloned and printed like every other
1296 /// row of a package, so an engine whose `Score` is none of those cannot publish one. `options`
1297 /// inherits every word of that, one member over.
1298 fn engine_seat(
1299 &self,
1300 stem: &syn::Ident,
1301 engines: &[&crate::engine::Engine],
1302 ) -> Option<(proc_macro2::TokenStream, Row)> {
1303 if engines.is_empty() {
1304 return None;
1305 }
1306 let seam = self.seam();
1307 let name = format_ident!("{stem}EngineInput");
1308 let mut variants: Vec<(syn::Ident, syn::Ident, String)> = Vec::new();
1309 let packages = engines
1310 .iter()
1311 .map(|engine| {
1312 let word = engine.word.to_string().to_upper_camel_case();
1313 let package = self.engine_input(stem, engine);
1314 let ty = engine
1315 .resource
1316 .as_ref()
1317 .expect("a typed engine names a type");
1318 variants.push((
1319 format_ident!("{word}"),
1320 package.clone(),
1321 engine.word.to_string().to_lower_camel_case(),
1322 ));
1323 self.packages().package(
1324 &package,
1325 &format!(
1326 "The per-request knobs `{stem}` runs under IN `{word}` — one variant of its `engine` \
1327 choice, holding the floor in this engine's own score currency and whatever else this \
1328 engine takes per query.",
1329 word = engine.word,
1330 ),
1331 &[
1332 // SPANNED AT THE PATH THE AUTHOR WROTE. These two rows are the first place a pointed
1333 // leg's kind is projected through, so a resource of the wrong kind reports here — and
1334 // an unspanned projection lands on the whole `#[ingraph::vector(…)]` attribute, which
1335 // is a caret a reader cannot act on. The kind audit beside them already reports on the
1336 // word; this is the same courtesy for the errors that arrive first.
1337 Row::new(
1338 &format_ident!("floor"),
1339 quote_spanned!(ty.span()=> <#ty as #seam>::Score),
1340 "score floor",
1341 ),
1342 Row::new(
1343 &format_ident!("options"),
1344 quote_spanned!(ty.span()=> <#ty as #seam>::SearchOptions),
1345 "per-query knobs",
1346 ),
1347 ],
1348 )
1349 })
1350 .collect::<Vec<_>>();
1351 let oneof = self.packages().oneof(&name, stem, &variants);
1352 let row = Row::new(&format_ident!("engine"), quote!(#name), "engine choice");
1353 Some((
1354 quote! {
1355 #(#packages)*
1356 #oneof
1357 },
1358 row,
1359 ))
1360 }
1361
1362 // ---------------------------------------------------------------------------------------------
1363 // The FULL-TEXT tier: one subject, one route, and no vector-flavoured type anywhere.
1364 // ---------------------------------------------------------------------------------------------
1365
1366 fn fulltext(&self) -> proc_macro2::TokenStream {
1367 let typed = match self.fulltext_typed() {
1368 Ok(typed) => typed,
1369 Err(refusal) => return refusal,
1370 };
1371 let subject = self.searchable_subject();
1372 let options = self.fulltext_options_name();
1373 let asked = self.fulltext_question_name();
1374 let vocabulary = self.column_vocabulary();
1375 let mut rows = Vec::new();
1376 let (engines, engine) = match self.engine_seat(self.base(), &typed) {
1377 Some((engines, row)) => (engines, Some(row)),
1378 None => (proc_macro2::TokenStream::new(), None),
1379 };
1380 rows.extend(engine);
1381 // The M-of-N GRAIN's seat, and it exists only where there is a vocabulary to spell one in. A
1382 // declaration electing nothing mints no enum, so a row typed on one would name a type this
1383 // expansion did not emit.
1384 if !self.searchable.is_empty() {
1385 let column = self.column_name();
1386 rows.push(Row::new(
1387 &format_ident!("columns"),
1388 quote!(::std::vec::Vec<#column>),
1389 "column subset",
1390 ));
1391 }
1392 let package = self.packages().package(
1393 &options,
1394 &format!(
1395 "The knobs a full-text retrieve over [`{index}`] runs under — ONE package however many \
1396 fields it elects ({subject}), because a full-text declaration is one ROUTE: its elected \
1397 fields are COLUMNS of that route rather than routes of their own, and `columns` is where a \
1398 request names the subset of them it wants searched. Absent means this declaration's own \
1399 subject, whole.",
1400 index = self.index,
1401 ),
1402 &rows,
1403 );
1404 let question = self.packages().question(
1405 &asked,
1406 &format!(
1407 "The question a full-text retrieve over [`{index}`] is asked with. One row, because a \
1408 full-text route's own currency IS the tier's: text.",
1409 index = self.index,
1410 ),
1411 &[Row::new(
1412 &format_ident!("question"),
1413 quote!(::std::string::String),
1414 "question",
1415 )],
1416 );
1417 let binding = self.fusable(&options, &asked);
1418 quote! {
1419 #vocabulary
1420 #engines
1421 #package
1422 #question
1423 #binding
1424 }
1425 }
1426
1427 /// The COLUMN VOCABULARY's type name — `<Tier>Column`.
1428 fn column_name(&self) -> syn::Ident {
1429 self.minted(RenamePiece::Column, "Column")
1430 }
1431
1432 /// The emitted `<Tier>Column` enum: this declaration's searchable fields as a CLOSED vocabulary,
1433 /// and the ONE point at which a variant becomes the seam's `FulltextColumn`.
1434 ///
1435 /// # Why the vocabulary is a TYPE and not the seam's newtype
1436 ///
1437 /// `FulltextColumn::new("titel")` type-checks. It is a `&'static str` behind a name, and a name is
1438 /// all the SEAM can carry — an engine takes columns from callers it never saw and cannot hold any
1439 /// declaration's list of fields. So the closed half lives HERE, where the fields ARE known: a
1440 /// column this declaration never elected has no variant to write with, and a misspelt one is a
1441 /// compile error at the caller's own line rather than an empty result set at run time.
1442 ///
1443 /// The two halves meet at exactly one function. [`column`] is the whole translation surface, so a
1444 /// variant's spelling and the name an engine is handed cannot drift — there is no second site that
1445 /// could learn a different answer.
1446 ///
1447 /// # It rides no engine gate
1448 ///
1449 /// The variants are the declaration's own fields, so nothing here names a concrete engine and the
1450 /// type exists in a build that compiled no backend at all. That is the road impls' law read onto
1451 /// this axis — only what names a concrete type may ride a gate, since a shut gate DELETES it — and
1452 /// it is what lets the PORTABLE declaration have a vocabulary too.
1453 ///
1454 /// SCREAMING_SNAKE on the wire, through the same [`enum_face`](Self::enum_face) the fold
1455 /// vocabulary crosses on.
1456 ///
1457 /// [`column`]: #
1458 fn column_vocabulary(&self) -> proc_macro2::TokenStream {
1459 let Tier {
1460 krate, vis, index, ..
1461 } = self;
1462 if self.searchable.is_empty() {
1463 return proc_macro2::TokenStream::new();
1464 }
1465 let name = self.column_name();
1466 let column = framework(krate, &["store"], "FulltextColumn");
1467 let mut variants: Vec<(syn::Ident, String)> = Vec::new();
1468 for field in self.searchable {
1469 let spelling = field.to_string().to_upper_camel_case();
1470 // TWO FIELDS UNDER ONE VARIANT is refused BY NAME rather than left to `E0428` on a type nobody
1471 // wrote — `shaped`'s collision check, one grain over. `spoken_labels` and `spokenLabels` are
1472 // two legal fields of one struct and one variant of this enum.
1473 if let Some((_, other)) = variants.iter().find(|(minted, _)| *minted == spelling) {
1474 let refusal = format!(
1475 "`{index}` elects `{field}` and `{other}`, which spell ONE variant `{spelling}` of \
1476 `{name}` — a column vocabulary is one word to a column, so rename one of the fields",
1477 );
1478 return quote!(::core::compile_error!(#refusal););
1479 }
1480 variants.push((format_ident!("{spelling}"), field.to_string()));
1481 }
1482 let declared = variants.iter().map(|(variant, field)| {
1483 let doc = leading(&format!("`{field}`, as this declaration elected it."));
1484 quote! {
1485 #[doc = #doc]
1486 #variant
1487 }
1488 });
1489 let arms = variants
1490 .iter()
1491 .map(|(variant, field)| quote!(Self::#variant => #column::new(#field)));
1492 let words: Vec<String> = variants
1493 .iter()
1494 .map(|(variant, _)| variant.to_string().to_shouty_snake_case())
1495 .collect();
1496 let idents: Vec<&syn::Ident> = variants.iter().map(|(variant, _)| variant).collect();
1497 let face = self.packages().enum_face(&name, &idents, &words);
1498 let doc = leading(&format!(
1499 "WHICH searchable columns of [`{index}`] a retrieve runs over — its elected fields, as a \
1500 closed vocabulary. A column this declaration never elected has no variant here to spell it \
1501 with.",
1502 ));
1503 let column_doc = leading(
1504 "The seam's own name for this column — the ONE point at which this vocabulary becomes a \
1505 `FulltextColumn`, so a variant's spelling and the name an engine is handed cannot drift.",
1506 );
1507 quote! {
1508 #[doc = #doc]
1509 #[derive(
1510 ::core::fmt::Debug,
1511 ::core::clone::Clone,
1512 ::core::marker::Copy,
1513 ::core::cmp::PartialEq,
1514 ::core::cmp::Eq,
1515 ::core::hash::Hash
1516 )]
1517 #vis enum #name {
1518 #(#declared,)*
1519 }
1520
1521 #[automatically_derived]
1522 impl #name {
1523 #[doc = #column_doc]
1524 #[must_use]
1525 #[inline]
1526 #vis const fn column(self) -> #column {
1527 match self {
1528 #(#arms,)*
1529 }
1530 }
1531 }
1532
1533 #face
1534 }
1535 }
1536
1537 /// The elected fields, as a doc sentence names them.
1538 fn searchable_subject(&self) -> String {
1539 self
1540 .searchable
1541 .iter()
1542 .map(|field| format!("`{field}`"))
1543 .collect::<Vec<_>>()
1544 .join(", ")
1545 }
1546
1547 // ---------------------------------------------------------------------------------------------
1548 // The VECTOR tier: one package per election, and a fuse package above them where there are two.
1549 // ---------------------------------------------------------------------------------------------
1550
1551 fn vector(&self) -> proc_macro2::TokenStream {
1552 let leaves = self
1553 .embeddings
1554 .iter()
1555 .map(|elected| self.election(elected))
1556 .collect::<Vec<_>>();
1557 let tier = match self.embeddings {
1558 // A one-route tier IS its route: the leaf package is what the parent absorbs, and a fuse
1559 // package above one route would be a fold over a list of one.
1560 [_] => proc_macro2::TokenStream::new(),
1561 _ => self.vector_tier(),
1562 };
1563 let options = self.options_name().expect("a vector tier retrieves");
1564 let asked = self.question_name().expect("a vector tier retrieves");
1565 let binding = self.fusable(&options, &asked);
1566 // The EVIDENCE and REFUSAL enums ride the DOORS and not the packages: a tier that fuses nothing
1567 // answers nothing that needs saying which route agreed — or which one refused — so the presence
1568 // law reaches both types.
1569 let evidence = if self.doors().any() {
1570 let provenance = self.evidence();
1571 let refusal = self.fused_error();
1572 quote! {
1573 #provenance
1574 #refusal
1575 }
1576 } else {
1577 proc_macro2::TokenStream::new()
1578 };
1579 quote! {
1580 #(#leaves)*
1581 #tier
1582 #evidence
1583 #binding
1584 }
1585 }
1586
1587 /// EVERY package one election mints: its fold vocabulary where it has one, its question package,
1588 /// and either a flat leaf or the mini tier a fan descends into.
1589 fn election(&self, elected: &Elected) -> proc_macro2::TokenStream {
1590 let semantics = self.semantics(elected);
1591 let question = self.election_question(elected);
1592 let options = if self.fanned(elected) {
1593 self.fanned_slot(elected)
1594 } else {
1595 self.flat_slot(elected)
1596 };
1597 quote! {
1598 #semantics
1599 #options
1600 #question
1601 }
1602 }
1603
1604 /// A SINGLE-WRITE slot's package: the knobs of one corpus.
1605 fn flat_slot(&self, elected: &Elected) -> proc_macro2::TokenStream {
1606 let name = self.slot_options(elected);
1607 let mut rows = Vec::new();
1608 let (engines, engine) = match self.engine_seat(&self.stem(elected), &self.typed(elected)) {
1609 Some((engines, row)) => (engines, Some(row)),
1610 None => (proc_macro2::TokenStream::new(), None),
1611 };
1612 rows.extend(engine);
1613 if elected.label.is_set() {
1614 let semantics = self.semantics_name(elected);
1615 rows.push(Row::new(
1616 &format_ident!("semantics"),
1617 quote!(#semantics),
1618 "fold",
1619 ));
1620 }
1621 let package = self.packages().package(
1622 &name,
1623 &format!(
1624 "The knobs a retrieve over [`{index}`]'s `{field}` runs under.",
1625 index = self.index,
1626 field = elected.field,
1627 ),
1628 &rows,
1629 );
1630 quote! {
1631 #engines
1632 #package
1633 }
1634 }
1635
1636 /// ONE typed engine's variant package — `<Stem><Word>EngineInput`.
1637 ///
1638 /// A function rather than a `format_ident!` at each of its three call sites, because the roster
1639 /// and the emission both spell it and a name spelled twice is a name that can drift.
1640 pub(crate) fn engine_input(
1641 &self,
1642 stem: &syn::Ident,
1643 engine: &crate::engine::Engine,
1644 ) -> syn::Ident {
1645 format_ident!(
1646 "{stem}{}EngineInput",
1647 engine.word.to_string().to_upper_camel_case()
1648 )
1649 }
1650
1651 /// The NAME STEM one election's own types are minted from — `<Index><Field>`.
1652 pub(crate) fn stem(&self, elected: &Elected) -> syn::Ident {
1653 format_ident!(
1654 "{}{}",
1655 self.base(),
1656 elected.field.to_string().to_upper_camel_case()
1657 )
1658 }
1659
1660 /// ONE LEG's own options package — `<Index><Field><Word>LegOptions`.
1661 ///
1662 /// A function rather than a `format_ident!` at each of its four call sites, for
1663 /// [`engine_input`](Self::engine_input)'s reason.
1664 fn leg_options(&self, elected: &Elected, engine: &crate::engine::Engine) -> syn::Ident {
1665 format_ident!(
1666 "{}{}{}LegOptions",
1667 self.base(),
1668 elected.field.to_string().to_upper_camel_case(),
1669 engine.word.to_string().to_upper_camel_case(),
1670 )
1671 }
1672
1673 /// A FANNED slot's packages: one leg package per PARTICIPANT, the selector seat over its
1674 /// ADDRESSABLE legs, and the mini tier that fuses them.
1675 ///
1676 /// # The two words are read on two different lists, and that is the orthogonality law
1677 ///
1678 /// `rrf` decides the `Route` seats — a leg outside the leaderboard has no edge for a parent to
1679 /// weight and no depth for a fold to narrow, so it has no seat and no leg package. `resource =`
1680 /// decides the SELECTOR — a leg a request can NAME, whether or not it ranks. The two lists
1681 /// overlap and neither contains the other.
1682 fn fanned_slot(&self, elected: &Elected) -> proc_macro2::TokenStream {
1683 let route = framework(self.krate, &["retrieve"], "Route");
1684 let flavour = framework(self.krate, &["retrieve"], "FusionOptions");
1685 let participants = self.participants(elected);
1686 let packages = participants.iter().map(|engine| {
1687 let name = self.leg_options(elected, engine);
1688 self.packages().package(
1689 &name,
1690 &format!(
1691 "The knobs [`{index}`]'s `{elected}` runs under IN THE `{engine}` STORE — one leg of a \
1692 fanned slot, and a route of the mini tier below.",
1693 index = self.index,
1694 elected = elected.field,
1695 engine = engine.word,
1696 ),
1697 // NO ROWS TODAY. Its one row was the request-side `ceiling`, which the wall law retired —
1698 // a protective number does not cross the wire — and the package stays because the mini
1699 // tier's `Route<…>` seat needs a type to wrap: the PARENT's three facts about this leg
1700 // (weight, enabled, depth) live on that route and are what a request configures a leg
1701 // through. A leg knob that is genuinely the requester's lands here when one is ruled.
1702 &[],
1703 )
1704 });
1705 let mut rows = vec![Row::new(
1706 &format_ident!("fusion"),
1707 quote!(#flavour),
1708 "fusion flavour",
1709 )];
1710 // THE SELECTOR SEAT — the same `engine` row a flat leaf carries, at the mini tier's grain. It is
1711 // the ADDRESSABILITY half: absent picks the fused road, present picks one leg and reads it
1712 // directly, in the same answer shape.
1713 let (selector, seat) = match self.engine_seat(&self.stem(elected), &self.typed(elected)) {
1714 Some((packages, row)) => (packages, Some(row)),
1715 None => (proc_macro2::TokenStream::new(), None),
1716 };
1717 rows.extend(seat);
1718 if elected.label.is_set() {
1719 let semantics = self.semantics_name(elected);
1720 rows.push(Row::new(
1721 &format_ident!("semantics"),
1722 quote!(#semantics),
1723 "fold",
1724 ));
1725 }
1726 rows.extend(participants.iter().map(|engine| {
1727 let leg = self.leg_options(elected, engine);
1728 Row::new(
1729 &engine.word,
1730 quote!(#route<#leg>),
1731 &format!("`{}` leg", engine.word),
1732 )
1733 }));
1734 let tier = self.packages().package(
1735 &self.slot_options(elected),
1736 &format!(
1737 "The knobs a retrieve over [`{index}`]'s FANNED `{field}` runs under — a tier rather than a \
1738 leaf, because several declared engines are live at once and each of them is a route.",
1739 index = self.index,
1740 field = elected.field,
1741 ),
1742 &rows,
1743 );
1744 let evidence = self.slot_evidence(elected);
1745 quote! {
1746 #(#packages)*
1747 #selector
1748 #tier
1749 #evidence
1750 }
1751 }
1752
1753 /// A FANNED slot's EVIDENCE and REFUSAL enums — the tier pair at slot grain, one variant per leg
1754 /// the slot's answer can name.
1755 ///
1756 /// The parameters are spelled per LEG rather than per route (`__INGRAPH_SCORE_<WORD>__`), because
1757 /// at this grain the leg IS the engine: one field's coordinates in several stores, each store
1758 /// scoring in its own currency.
1759 fn slot_evidence(&self, elected: &Elected) -> proc_macro2::TokenStream {
1760 let Tier { vis, .. } = self;
1761 let legs = self.evidence_legs(elected);
1762 let name = self.slot_evidence_name(elected);
1763 let refusal = self.slot_error_name(elected);
1764 let scores: Vec<syn::Ident> = legs
1765 .iter()
1766 .map(|engine| score_param(&engine.word))
1767 .collect();
1768 let errors: Vec<syn::Ident> = legs
1769 .iter()
1770 .map(|engine| error_param(&engine.word))
1771 .collect();
1772 let variants = legs.iter().zip(&scores).map(|(engine, score)| {
1773 let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
1774 let doc = leading(&format!(
1775 "The `{word}` store ranked this root, at that store's own score.",
1776 word = engine.word,
1777 ));
1778 quote! {
1779 #[doc = #doc]
1780 #variant(#score)
1781 }
1782 });
1783 let refusals = legs.iter().zip(&errors).map(|(engine, error)| {
1784 let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
1785 let doc = leading(&format!(
1786 "The `{word}` store refused, in that store's own vocabulary.",
1787 word = engine.word,
1788 ));
1789 quote! {
1790 #[doc = #doc]
1791 #variant(#error)
1792 }
1793 });
1794 let arms = legs.iter().map(|engine| {
1795 let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
1796 let word = engine.word.to_string();
1797 quote! {
1798 Self::#variant(__ingraph_refusal) => {
1799 ::core::write!(__ingraph_formatter, "{}: {__ingraph_refusal}", #word)
1800 }
1801 }
1802 });
1803 let sources = legs.iter().map(|engine| {
1804 let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
1805 quote!(Self::#variant(__ingraph_refusal) => ::core::option::Option::Some(__ingraph_refusal))
1806 });
1807 let displays = errors
1808 .iter()
1809 .map(|param| quote!(#param: ::core::fmt::Display));
1810 let bounds = errors
1811 .iter()
1812 .map(|param| quote!(#param: ::core::error::Error + 'static));
1813 let doc = leading(&format!(
1814 "WHICH of [`{index}`]'s `{field}` STORES agreed about a fused root, and what each of them \
1815 scored it — one variant per leg the slot's answer can name, each in that store's own \
1816 currency.",
1817 index = self.index,
1818 field = elected.field,
1819 ));
1820 let both = leading(
1821 "The FUSED road fills one variant per participating leg; the SELECTOR road fills exactly one, \
1822 for whichever leg the request named. One type answers both, which is what *the same answer \
1823 shape* means here.",
1824 );
1825 let refusal_doc = leading(&format!(
1826 "WHICH of [`{index}`]'s `{field}` stores refused, in that store's own vocabulary.",
1827 index = self.index,
1828 field = elected.field,
1829 ));
1830 quote! {
1831 #[doc = #doc]
1832 #[doc = ""]
1833 #[doc = #both]
1834 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
1835 #vis enum #name<#(#scores,)*> {
1836 #(#variants,)*
1837 }
1838
1839 #[doc = #refusal_doc]
1840 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
1841 #vis enum #refusal<#(#errors,)*> {
1842 #(#refusals,)*
1843 }
1844
1845 #[automatically_derived]
1846 impl<#(#displays,)*> ::core::fmt::Display for #refusal<#(#errors,)*> {
1847 fn fmt(
1848 &self,
1849 __ingraph_formatter: &mut ::core::fmt::Formatter<'_>,
1850 ) -> ::core::fmt::Result {
1851 match self {
1852 #(#arms,)*
1853 }
1854 }
1855 }
1856
1857 #[automatically_derived]
1858 impl<#(#bounds,)*> ::core::error::Error for #refusal<#(#errors,)*> {
1859 fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
1860 match self {
1861 #(#sources,)*
1862 }
1863 }
1864 }
1865 }
1866 }
1867
1868 /// ONE ELECTION's question package — the tier's text question, and the raw coordinates a caller
1869 /// may hand it instead.
1870 fn election_question(&self, elected: &Elected) -> proc_macro2::TokenStream {
1871 // THE ELECTION'S POINT, projected — and the DECLARED CARRIER was measured here and rejected.
1872 //
1873 // The carrier is a STORAGE fact: how an entity holds its own set, which a third party may
1874 // supply by implementing `EmbeddingMarker` for a type of its own. The QUESTION is `m` query
1875 // vectors, which is `Embedding<E, N, S>` for every carrier there will ever be — the spec's own
1876 // words, *an `Embedding<E, N, S>` for a vector slot, its own space*.
1877 //
1878 // Spelling the carrier instead compiled and was wrong twice over: a package deriving `Debug`,
1879 // `Clone` and `PartialEq` would have demanded all three OF THE CARRIER, so
1880 // `tests/election_carriers.rs`'s third-party `Keyframes` — a type that derives none of them and
1881 // has no reason to — stopped compiling; and it would have made the query type differ per
1882 // carrier where the door below it takes one shape.
1883 let marker = framework(self.krate, &["election"], "EmbeddingMarker");
1884 let ty = &elected.ty;
1885 let point = quote!(<#ty as #marker>::Item);
1886 // A SET election is asked with a set — the `m` the emitted `_with` door takes — so the row is a
1887 // list where a single election's is one point.
1888 let coordinates = if elected.label.is_set() {
1889 quote!(::std::vec::Vec<#point>)
1890 } else {
1891 point
1892 };
1893 self.packages().question(
1894 &self.slot_question(elected),
1895 &format!(
1896 "The question [`{index}`]'s `{field}` is asked with — the text question its ask road walks, \
1897 or the coordinates a caller already holds, IN THIS ELECTION'S OWN SPACE.",
1898 index = self.index,
1899 field = elected.field,
1900 ),
1901 &[
1902 Row::new(
1903 &format_ident!("question"),
1904 quote!(::std::string::String),
1905 "question",
1906 ),
1907 // THE ONE ROW OF EITHER TREE WITH NO WIRE FORM — see `Row::rust_side` for the measurement.
1908 Row::new(&format_ident!("coordinates"), coordinates, "coordinates").rust_side(),
1909 ],
1910 )
1911 }
1912
1913 /// The tier package a vector declaration electing SEVERAL fields mints, and its question twin.
1914 fn vector_tier(&self) -> proc_macro2::TokenStream {
1915 let route = framework(self.krate, &["retrieve"], "Route");
1916 let flavour = framework(self.krate, &["retrieve"], "FusionOptions");
1917 let mut rows = vec![Row::new(
1918 &format_ident!("fusion"),
1919 quote!(#flavour),
1920 "fusion flavour",
1921 )];
1922 rows.extend(self.embeddings.iter().map(|elected| {
1923 let package = self.slot_options(elected);
1924 Row::new(
1925 &elected.field,
1926 quote!(#route<#package>),
1927 &format!("`{}` route", elected.field),
1928 )
1929 }));
1930 let options = self.packages().package(
1931 &self.fuse_options_name(),
1932 &format!(
1933 "The knobs a FUSED retrieve over [`{index}`] runs under — one route per election, each \
1934 wearing the edge facts its parent holds about it.",
1935 index = self.index,
1936 ),
1937 &rows,
1938 );
1939 let mut asked = vec![Row::new(
1940 &format_ident!("question"),
1941 quote!(::std::string::String),
1942 "question",
1943 )];
1944 asked.extend(self.embeddings.iter().map(|elected| {
1945 let package = self.slot_question(elected);
1946 Row::new(
1947 &elected.field,
1948 quote!(#package),
1949 &format!("`{}` route", elected.field),
1950 )
1951 }));
1952 let asked = self.packages().question(
1953 &self.fuse_question_name(),
1954 &format!(
1955 "The question a FUSED retrieve over [`{index}`] is asked with — this tier's own, and one \
1956 package per route for the routes that ask something else.",
1957 index = self.index,
1958 ),
1959 &asked,
1960 );
1961 quote! {
1962 #options
1963 #asked
1964 }
1965 }
1966
1967 // ---------------------------------------------------------------------------------------------
1968 // The wire FOLD vocabulary.
1969 // ---------------------------------------------------------------------------------------------
1970
1971 /// The `@enum` a SET election's fold is named by on the wire — the closed set of words this
1972 /// election's open set of fold TYPES is reached through.
1973 ///
1974 /// Emitted per election rather than once for the framework, which is
1975 /// [`semantics`](../../ingraph/retrieve/semantics/index.html)' own ruling: the vocabulary IS the
1976 /// trait, so a closed enum can only exist where the set is closed — at a declaration, whose
1977 /// `semantics(fold = …)` word says which folds this election has.
1978 fn semantics(&self, elected: &Elected) -> proc_macro2::TokenStream {
1979 if !elected.label.is_set() {
1980 return proc_macro2::TokenStream::new();
1981 }
1982 let Tier { krate, vis, .. } = self;
1983 let name = self.semantics_name(elected);
1984 let visitor = framework(krate, &["retrieve"], "FoldVisitor");
1985 let shipped = |citizen: &str| framework(krate, &["retrieve"], citizen);
1986 // The SHIPPED citizens, and then whatever the declaration named beside them — the custom is a
1987 // THIRD word rather than a replacement, because a declared default does not take the others
1988 // away from a client who asks for one.
1989 let mut arms: Vec<(syn::Ident, proc_macro2::TokenStream, String)> = vec![
1990 (
1991 format_ident!("Sum"),
1992 shipped("Sum"),
1993 "`Σⱼ bⱼ` — standard MaxSim / late-interaction.".to_owned(),
1994 ),
1995 (
1996 format_ident!("Max"),
1997 shipped("Max"),
1998 "`maxⱼ bⱼ` — the best single (query vector, set member) pair.".to_owned(),
1999 ),
2000 ];
2001 if let Some(Fold::Custom(path)) = &elected.fold {
2002 let word = path
2003 .segments
2004 .last()
2005 .map_or_else(|| "Custom".to_owned(), |segment| segment.ident.to_string());
2006 let variant = word.to_upper_camel_case();
2007 // A CUSTOM WHOSE LAST SEGMENT IS A CITIZEN'S is refused BY NAME rather than left to `E0428`
2008 // on a type nobody wrote. `app::Sum` is a different fold from this framework's `Sum` and both
2009 // want the word `SUM` on the wire, which is one vocabulary with two meanings — the exact
2010 // collision the shipped-word table refuses one family over.
2011 if arms.iter().any(|(shipped, _, _)| shipped == &variant) {
2012 let refusal = format!(
2013 "`{path}` ends in `{word}`, which is the word this framework's own `{word}` fold already \
2014 holds in `{index}`'s `{field}` vocabulary — rename the fold, or alias it, so the \
2015 election's words stay one to a fold",
2016 path = quote!(#path).to_string().replace(' ', ""),
2017 index = self.index,
2018 field = elected.field,
2019 );
2020 return quote!(::core::compile_error!(#refusal););
2021 }
2022 arms.push((
2023 format_ident!("{variant}"),
2024 quote!(#path),
2025 format!("`{word}` — the fold this declaration named."),
2026 ));
2027 }
2028 let declared = match &elected.fold {
2029 None | Some(Fold::Sum) => format_ident!("Sum"),
2030 Some(Fold::Max) => format_ident!("Max"),
2031 Some(Fold::Custom(path)) => format_ident!(
2032 "{}",
2033 path
2034 .segments
2035 .last()
2036 .map_or_else(|| "Custom".to_owned(), |segment| segment.ident.to_string())
2037 .to_upper_camel_case()
2038 ),
2039 };
2040 let variants = arms.iter().map(|(variant, _, doc)| {
2041 let doc = leading(doc);
2042 quote! {
2043 #[doc = #doc]
2044 #variant
2045 }
2046 });
2047 let semantics = framework(krate, &["retrieve"], "FoldSemantics");
2048 let dispatch = arms.iter().map(|(variant, ty, _)| {
2049 quote!(Self::#variant => #visitor::visit(__ingraph_visitor, <#ty as ::core::default::Default>::default()))
2050 });
2051 // ONE PREDICATE PER ARM, and the list is the whole reason `with_fold` can be generic over the
2052 // currency at all: `Sum` scores anything that clones and adds, `Max` anything that compares, and
2053 // a declared custom whatever its own impl says. No single bound covers them, and the union is
2054 // not this emission's to invent — so each arm states its own obligation and a caller whose
2055 // currency one of them cannot score is `E0277` naming that arm.
2056 let obligations = arms
2057 .iter()
2058 .map(|(_, ty, _)| quote!(#ty: #semantics<__INGRAPH_SCORE__>));
2059 let words: Vec<String> = arms
2060 .iter()
2061 .map(|(variant, _, _)| variant.to_string().to_shouty_snake_case())
2062 .collect();
2063 let idents: Vec<&syn::Ident> = arms.iter().map(|(variant, _, _)| variant).collect();
2064 let doc = leading(&format!(
2065 "WHICH fold [`{index}`]'s `{field}` set query runs under — the wire's closed vocabulary over \
2066 an open set of types.",
2067 index = self.index,
2068 field = elected.field,
2069 ));
2070 let declared_doc =
2071 leading("The fold this DECLARATION named, and what a request that names none resolves to.");
2072 let with_doc = leading(
2073 "Spend this word's fold. The arms produce DIFFERENT TYPES, so the visitor rather than a \
2074 return value is what crosses back — each arm monomorphizes, and the door below is the \
2075 statically dispatched door it would have been had the caller spelled the type.",
2076 );
2077 let face = self.packages().enum_face(&name, &idents, &words);
2078 quote! {
2079 #[doc = #doc]
2080 #[derive(
2081 ::core::fmt::Debug,
2082 ::core::clone::Clone,
2083 ::core::marker::Copy,
2084 ::core::cmp::PartialEq,
2085 ::core::cmp::Eq,
2086 ::core::hash::Hash
2087 )]
2088 #vis enum #name {
2089 #(#variants,)*
2090 }
2091
2092 #[automatically_derived]
2093 impl #name {
2094 #[doc = #declared_doc]
2095 #vis const DECLARED: Self = Self::#declared;
2096
2097 #[doc = #with_doc]
2098 #[inline]
2099 #vis fn with_fold<__INGRAPH_SCORE__, __INGRAPH_VISITOR__>(
2100 self,
2101 __ingraph_visitor: __INGRAPH_VISITOR__,
2102 ) -> <__INGRAPH_VISITOR__ as #visitor<__INGRAPH_SCORE__>>::Output
2103 where
2104 __INGRAPH_VISITOR__: #visitor<__INGRAPH_SCORE__>,
2105 #(#obligations,)*
2106 {
2107 match self {
2108 #(#dispatch,)*
2109 }
2110 }
2111 }
2112
2113 #face
2114 }
2115 }
2116}
2117
2118/// THE PACKAGE EMITTER, at any GRAIN — the options-pattern struct, its wire face, and the two enum
2119/// faces the fusion tree publishes.
2120///
2121/// # It was `Tier`'s, and the ROOT is why it is not
2122///
2123/// Every one of these emitters was written as a method on [`Tier`] while the only thing that minted
2124/// a package was an index declaration. A ROOT mints packages too — its members are its routes — and
2125/// it is not a tier: it has no kind, no elections and no engines, so it could reach none of this
2126/// without carrying an index model it does not have.
2127///
2128/// What the emitters actually READ off a tier is three things: where the framework lives, what
2129/// visibility to take, and whose name a refusal quotes. So that is what this holds, and a tier is
2130/// one caller of it rather than its owner.
2131#[derive(Debug, Clone)]
2132pub struct Packages<'a> {
2133 /// Where `ingraph` lives, as the declaration named it.
2134 pub krate: &'a syn::Path,
2135 /// The declaration's own visibility — what every emitted package takes.
2136 pub vis: &'a syn::Visibility,
2137 /// WHOSE packages these are, for a refusal that has to name the declaration at fault — an index
2138 /// at tier grain, a root at root grain.
2139 pub owner: &'a syn::Ident,
2140 /// WHICH BACKENDS DRESS THESE PACKAGES — the declaration's `graphql(…)` block, or [`None`] at a
2141 /// grain whose grammar has no block (the root today), which the skin law reads as undressed: the
2142 /// Rust surface emits whole and no wire face is minted.
2143 pub graphql: Option<&'a IndexGraphql>,
2144 /// The RENAME-AWARE BASE every minted name leads with — the tier's [`base`](Tier::base), the
2145 /// root's own ident. What [`sdl`](Self::sdl)'s re-basing swaps out.
2146 pub base: &'a syn::Ident,
2147 /// EVERY PER-FACE OVERRIDE this declaration wrote, as the minted Rust name it targets paired with
2148 /// the word a schema is to publish instead.
2149 ///
2150 /// # One list where there used to be a fixed three, because the seats stopped being three
2151 ///
2152 /// The head's `options`/`question`/`engine` were the whole vocabulary and a `[_; 3]` zipped
2153 /// against them read fine. The 2026-08-16 rename ruling added `question(rename = …)` and
2154 /// `engines(rename = …)` on every ELECTION, so the count is now one grain's three plus two per
2155 /// election — a number no array can be sized to. A list of resolved PAIRS also moves the *which
2156 /// word belongs to which mint* decision to the one place that knows both, so [`sdl`](Self::sdl)
2157 /// answers by lookup rather than by re-deriving names it would have to keep in step.
2158 ///
2159 /// EMPTY at a grain whose grammar has no block — the root today — which is the same state a
2160 /// declaration that wrote no override is in.
2161 pub members: Vec<(syn::Ident, syn::LitStr)>,
2162}
2163
2164impl<'a> Packages<'a> {
2165 /// ONE PACKAGE, whole: the struct, its factory chain, its readers, its `Default` and its wire
2166 /// face — over the rows that HAVE one, which is [`Row::rust_side`]'s whole subject.
2167 ///
2168 /// # BOTH trees cross now, and the grain is the ROW
2169 ///
2170 /// Every row of an options package crosses: a count, a fold word, a flavour request, an engine
2171 /// choice, another package. The question tree's rows are all but one — a question is a `String`
2172 /// and a child route is another question package — and the exception is `coordinates`, which is
2173 /// the declaration's own `Embedding<E, N, S>` and has no `InputType` to cross on. Refusing the
2174 /// whole sister tree for that one row published nothing where the text half was always
2175 /// publishable, so the exclusion moved down a level.
2176 pub fn package(
2177 &self,
2178 name: &syn::Ident,
2179 subject: &str,
2180 rows: &[Row],
2181 ) -> proc_macro2::TokenStream {
2182 self.shaped(name, subject, rows)
2183 }
2184
2185 /// ONE QUESTION PACKAGE — [`package`](Self::package) under the sister tree's name, so a reader
2186 /// scanning the emitters sees which tree is being built.
2187 pub fn question(
2188 &self,
2189 name: &syn::Ident,
2190 subject: &str,
2191 rows: &[Row],
2192 ) -> proc_macro2::TokenStream {
2193 self.shaped(name, subject, rows)
2194 }
2195
2196 fn shaped(&self, name: &syn::Ident, subject: &str, rows: &[Row]) -> proc_macro2::TokenStream {
2197 let Packages { vis, .. } = self;
2198 // TWO ROWS UNDER ONE NAME IS REFUSED HERE, once, for every package there is. A package's rows
2199 // come from two sources — the framework's own (`fusion`, `question`, `semantics`) and
2200 // the declaration's (an election's field name, an engine's word) — so a field elected as
2201 // `fusion` or an engine bound as `question` collides, and rustc would report `E0124` about a
2202 // struct nobody wrote. One check at the one place every package is built through, rather than a
2203 // reserved-word list each call site could forget.
2204 if let Some(taken) = collision(rows) {
2205 let refusal = format!(
2206 "`{name}` would carry two rows named `{taken}` — one is this framework's own and one is \
2207 `{owner}`'s, and a package's rows are one to a name; rename the member, the election or \
2208 the engine word that spells `{taken}`",
2209 owner = self.owner,
2210 );
2211 return quote!(::core::compile_error!(#refusal););
2212 }
2213 let members = substrate();
2214 let fields = rows.iter().map(|Row { member, ty, noun, .. }| {
2215 let doc = leading(&format!(
2216 "The {noun}, where the request named one — absent means the declaration's own.",
2217 ));
2218 let why = "a package's members are read through its own accessors, and which of them any one \
2219 deployment reads is not this emission's business";
2220 quote! {
2221 #[doc = #doc]
2222 #[allow(dead_code, reason = #why)]
2223 #members #member: ::core::option::Option<#ty>
2224 }
2225 });
2226 let accessors = rows.iter().map(
2227 |Row {
2228 member, ty, noun, ..
2229 }| {
2230 let with = format_ident!("with_{member}");
2231 let set = leading(&format!("The same package carrying a {noun}."));
2232 let get = leading(&format!("The {noun} this package names, if it names one."));
2233 quote! {
2234 #[doc = #set]
2235 #[must_use]
2236 #[inline]
2237 #vis fn #with(mut self, #member: #ty) -> Self {
2238 self.#member = ::core::option::Option::Some(#member);
2239 self
2240 }
2241
2242 #[doc = #get]
2243 #[must_use]
2244 #[inline]
2245 #vis const fn #member(&self) -> ::core::option::Option<&#ty> {
2246 ::core::option::Option::as_ref(&self.#member)
2247 }
2248 }
2249 },
2250 );
2251 let empty = rows
2252 .iter()
2253 .map(|Row { member, .. }| quote!(#member: ::core::option::Option::None));
2254 let doc = leading(subject);
2255 let new_doc = leading(
2256 "A package that names nothing — every row absent, every one of them deferring to the \
2257 declaration's own. The head of the factory chain, and what `Default` is.",
2258 );
2259 let face = self.input_face(name, rows);
2260 quote! {
2261 #[doc = #doc]
2262 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
2263 #vis struct #name {
2264 #(#fields,)*
2265 }
2266
2267 #[automatically_derived]
2268 impl #name {
2269 #[doc = #new_doc]
2270 #[must_use]
2271 #[inline]
2272 #vis const fn new() -> Self {
2273 Self { #(#empty,)* }
2274 }
2275
2276 #(#accessors)*
2277 }
2278
2279 #[automatically_derived]
2280 impl ::core::default::Default for #name {
2281 #[inline]
2282 fn default() -> Self {
2283 Self::new()
2284 }
2285 }
2286
2287 #face
2288 }
2289 }
2290
2291 /// The WIRE FACE of one package — an ordinary input object, every field nullable and therefore
2292 /// wholly omissible.
2293 ///
2294 /// Hand-written rather than derived, for `emit::wire`'s measured reason: a derive belongs to the
2295 /// type's own declaration, which is written OUTSIDE the binding gate, and a type that existed only
2296 /// where the binding does would vanish from every build without it.
2297 ///
2298 /// # A ROW THAT DOES NOT CROSS is absent from all three halves at once
2299 ///
2300 /// The schema does not publish it, `to_value` does not write it, and `parse` fills it with
2301 /// [`None`] — one predicate, read three times, so a row cannot be published and unreadable or
2302 /// readable and unpublished. See [`Row::rust_side`] for the measurement that put a row here
2303 /// instead of a whole package.
2304 fn input_face(&self, name: &syn::Ident, rows: &[Row]) -> proc_macro2::TokenStream {
2305 if !self.dressed(GraphqlKind::AsyncGraphql) {
2306 return proc_macro2::TokenStream::new();
2307 }
2308 let Packages { krate, .. } = self;
2309 let gate = framework(krate, &["gate"], "if_async_graphql");
2310 let ag = framework(krate, &[], "async_graphql");
2311 let sdl = self.sdl(name);
2312 let crossing = || rows.iter().filter(|row| row.crosses);
2313 let entries = crossing().map(|Row { wire, ty, .. }| {
2314 quote! {
2315 __ingraph_fields.insert(
2316 ::std::string::String::from(#wire),
2317 #ag::registry::MetaInputValue {
2318 name: ::std::string::String::from(#wire),
2319 description: ::core::option::Option::None,
2320 ty: <::core::option::Option<#ty> as #ag::InputType>::create_type_info(
2321 __ingraph_registry,
2322 ),
2323 deprecation: #ag::registry::Deprecation::NoDeprecated,
2324 default_value: ::core::option::Option::None,
2325 visible: ::core::option::Option::None,
2326 inaccessible: false,
2327 tags: ::std::vec::Vec::new(),
2328 is_secret: false,
2329 directive_invocations: ::std::vec::Vec::new(),
2330 },
2331 );
2332 }
2333 });
2334 let reads = rows.iter().map(
2335 |Row {
2336 member,
2337 wire,
2338 ty,
2339 crosses,
2340 ..
2341 }| {
2342 if !crosses {
2343 return quote!(#member: ::core::option::Option::None);
2344 }
2345 quote! {
2346 // `.cloned()` in METHOD position, and it has to be: `Option::cloned` is `E0034` as a path,
2347 // there being one on `Option<&T>` and one on `Option<&mut T>` with nothing at the call site
2348 // to pick between them.
2349 #member: <::core::option::Option<#ty> as #ag::InputType>::parse(
2350 #ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
2351 )
2352 .map_err(#ag::InputValueError::propagate)?
2353 }
2354 },
2355 );
2356 let writes = crossing().map(|Row { member, wire, .. }| {
2357 quote! {
2358 __ingraph_map.insert(
2359 #ag::Name::new(#wire),
2360 #ag::InputType::to_value(&self.#member),
2361 );
2362 }
2363 });
2364 quote! {
2365 #gate! {
2366 const _: () = {
2367 #[automatically_derived]
2368 impl #ag::InputType for #name {
2369 type RawValueType = Self;
2370
2371 #[inline]
2372 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
2373 ::std::borrow::Cow::Borrowed(#sdl)
2374 }
2375
2376 fn create_type_info(
2377 __ingraph_registry: &mut #ag::registry::Registry,
2378 ) -> ::std::string::String {
2379 __ingraph_registry.create_input_type::<Self, _>(
2380 #ag::registry::MetaTypeId::InputObject,
2381 |__ingraph_registry| #ag::registry::MetaType::InputObject {
2382 name: ::std::string::String::from(#sdl),
2383 description: ::core::option::Option::None,
2384 input_fields: {
2385 let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
2386 #(#entries)*
2387 __ingraph_fields
2388 },
2389 visible: ::core::option::Option::None,
2390 inaccessible: false,
2391 tags: ::std::vec::Vec::new(),
2392 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
2393 oneof: false,
2394 directive_invocations: ::std::vec::Vec::new(),
2395 },
2396 )
2397 }
2398
2399 fn parse(
2400 __ingraph_value: ::core::option::Option<#ag::Value>,
2401 ) -> #ag::InputValueResult<Self> {
2402 if let ::core::option::Option::Some(#ag::Value::Object(__ingraph_object)) =
2403 __ingraph_value
2404 {
2405 return ::core::result::Result::Ok(Self { #(#reads,)* });
2406 }
2407 ::core::result::Result::Err(#ag::InputValueError::expected_type(
2408 ::core::option::Option::unwrap_or_default(__ingraph_value),
2409 ))
2410 }
2411
2412 fn to_value(&self) -> #ag::Value {
2413 let mut __ingraph_map = #ag::indexmap::IndexMap::new();
2414 #(#writes)*
2415 #ag::Value::Object(__ingraph_map)
2416 }
2417
2418 #[inline]
2419 fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
2420 ::core::option::Option::Some(self)
2421 }
2422 }
2423
2424 #[automatically_derived]
2425 impl #ag::InputObjectType for #name {}
2426 };
2427 }
2428 }
2429 }
2430
2431 /// The `@oneOf` a slot's `engine` row holds — the enum over the declared typed words, and the
2432 /// input face that publishes it as a CHOICE rather than as a record of optional fields.
2433 ///
2434 /// Hand-written for [`input_face`](Self::input_face)'s reason, and against
2435 /// `async_graphql::OneofObject`'s own expansion: `oneof: true` in the meta type, one nullable
2436 /// input field per variant, a parse that admits an object of EXACTLY ONE key, and the two marker
2437 /// impls a `@oneOf` carries beside `InputType`.
2438 pub fn oneof(
2439 &self,
2440 name: &syn::Ident,
2441 stem: &syn::Ident,
2442 variants: &[(syn::Ident, syn::Ident, String)],
2443 ) -> proc_macro2::TokenStream {
2444 let Packages { krate, vis, .. } = self;
2445 let gate = framework(krate, &["gate"], "if_async_graphql");
2446 let ag = framework(krate, &[], "async_graphql");
2447 let sdl = self.sdl(name);
2448 let declared = variants.iter().map(|(variant, package, word)| {
2449 let doc = leading(&format!(
2450 "The knobs `{word}` takes, in `{word}`'s own currencies."
2451 ));
2452 quote! {
2453 #[doc = #doc]
2454 #variant(#package)
2455 }
2456 });
2457 let entries = variants.iter().map(|(_, package, word)| {
2458 quote! {
2459 __ingraph_fields.insert(
2460 ::std::string::String::from(#word),
2461 #ag::registry::MetaInputValue {
2462 name: ::std::string::String::from(#word),
2463 description: ::core::option::Option::None,
2464 ty: <::core::option::Option<#package> as #ag::InputType>::create_type_info(
2465 __ingraph_registry,
2466 ),
2467 deprecation: #ag::registry::Deprecation::NoDeprecated,
2468 default_value: ::core::option::Option::None,
2469 visible: ::core::option::Option::None,
2470 inaccessible: false,
2471 tags: ::std::vec::Vec::new(),
2472 is_secret: false,
2473 directive_invocations: ::std::vec::Vec::new(),
2474 },
2475 );
2476 }
2477 });
2478 // EXACTLY ONE KEY, which is the whole of what `@oneOf` means and the one line a record-shaped
2479 // face would not have: an object naming two engines is two requests, and an object naming none
2480 // is not a choice.
2481 let reads = variants.iter().map(|(variant, _, word)| {
2482 quote! {
2483 if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #word)
2484 && __ingraph_object.len() == 1
2485 {
2486 let __ingraph_chosen = #ag::InputType::parse(
2487 #ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #word),
2488 )
2489 .map_err(#ag::InputValueError::propagate)?;
2490 return ::core::result::Result::Ok(Self::#variant(__ingraph_chosen));
2491 }
2492 }
2493 });
2494 let writes = variants.iter().map(|(variant, _, word)| {
2495 quote! {
2496 Self::#variant(__ingraph_chosen) => {
2497 __ingraph_map.insert(
2498 #ag::Name::new(#word),
2499 #ag::InputType::to_value(__ingraph_chosen),
2500 );
2501 }
2502 }
2503 });
2504 let doc = leading(&format!(
2505 "WHICH engine a retrieve over `{stem}` is tuned for, and the knobs it is tuned with — one \
2506 variant per engine this declaration TYPED, each holding the numbers that only mean anything \
2507 in that engine's own currencies. A choice rather than a record: naming two engines in one \
2508 request is two requests.",
2509 ));
2510 // THE ENUM IS THE BONE AND THE BLOCK BELOW IS ITS SKIN, which is why the two are built apart
2511 // here and joined at the end: the selector is a Rust type a backend-only pipeline matches on,
2512 // and only its `@oneOf` face is one backend's.
2513 let face = if self.dressed(GraphqlKind::AsyncGraphql) {
2514 quote! {
2515 #gate! {
2516 const _: () = {
2517 #[automatically_derived]
2518 impl #ag::InputType for #name {
2519 type RawValueType = Self;
2520
2521 #[inline]
2522 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
2523 ::std::borrow::Cow::Borrowed(#sdl)
2524 }
2525
2526 fn create_type_info(
2527 __ingraph_registry: &mut #ag::registry::Registry,
2528 ) -> ::std::string::String {
2529 __ingraph_registry.create_input_type::<Self, _>(
2530 #ag::registry::MetaTypeId::InputObject,
2531 |__ingraph_registry| #ag::registry::MetaType::InputObject {
2532 name: ::std::string::String::from(#sdl),
2533 description: ::core::option::Option::None,
2534 input_fields: {
2535 let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
2536 #(#entries)*
2537 __ingraph_fields
2538 },
2539 visible: ::core::option::Option::None,
2540 inaccessible: false,
2541 tags: ::std::vec::Vec::new(),
2542 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
2543 oneof: true,
2544 directive_invocations: ::std::vec::Vec::new(),
2545 },
2546 )
2547 }
2548
2549 fn parse(
2550 __ingraph_value: ::core::option::Option<#ag::Value>,
2551 ) -> #ag::InputValueResult<Self> {
2552 if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
2553 __ingraph_value
2554 {
2555 #(#reads)*
2556 return ::core::result::Result::Err(#ag::InputValueError::expected_type(
2557 #ag::Value::Object(__ingraph_object),
2558 ));
2559 }
2560 ::core::result::Result::Err(#ag::InputValueError::expected_type(
2561 ::core::option::Option::unwrap_or_default(__ingraph_value),
2562 ))
2563 }
2564
2565 fn to_value(&self) -> #ag::Value {
2566 let mut __ingraph_map = #ag::indexmap::IndexMap::new();
2567 match self {
2568 #(#writes)*
2569 }
2570 #ag::Value::Object(__ingraph_map)
2571 }
2572
2573 #[inline]
2574 fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
2575 ::core::option::Option::Some(self)
2576 }
2577 }
2578
2579 #[automatically_derived]
2580 impl #ag::InputObjectType for #name {}
2581
2582 #[automatically_derived]
2583 impl #ag::OneofObjectType for #name {}
2584 };
2585 }
2586 }
2587 } else {
2588 proc_macro2::TokenStream::new()
2589 };
2590 quote! {
2591 #[doc = #doc]
2592 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
2593 #vis enum #name {
2594 #(#declared,)*
2595 }
2596
2597 #face
2598 }
2599 }
2600
2601 /// The WIRE FACE of an emitted enum — the name/variant table and the input crossing, written the
2602 /// way `enumeration::wire` writes an `ingraph::Enum`'s.
2603 ///
2604 /// SCREAMING_SNAKE on the wire, which is the GraphQL namespace's own default casing in this
2605 /// grammar and is reached here rather than restated.
2606 pub fn enum_face(
2607 &self,
2608 name: &syn::Ident,
2609 variants: &[&syn::Ident],
2610 words: &[String],
2611 ) -> proc_macro2::TokenStream {
2612 if !self.dressed(GraphqlKind::AsyncGraphql) {
2613 return proc_macro2::TokenStream::new();
2614 }
2615 let Packages { krate, .. } = self;
2616 let gate = framework(krate, &["gate"], "if_async_graphql");
2617 let ag = framework(krate, &[], "async_graphql");
2618 let sdl = self.sdl(name);
2619 let items = variants.iter().zip(words).map(|(variant, word)| {
2620 quote! {
2621 #ag::resolver_utils::EnumItem { name: #word, value: #name::#variant }
2622 }
2623 });
2624 let values = words.iter().map(|word| {
2625 quote! {
2626 __ingraph_values.insert(
2627 ::std::string::String::from(#word),
2628 #ag::registry::MetaEnumValue {
2629 name: ::std::string::String::from(#word),
2630 description: ::core::option::Option::None,
2631 deprecation: #ag::registry::Deprecation::NoDeprecated,
2632 visible: ::core::option::Option::None,
2633 inaccessible: false,
2634 tags: ::std::vec::Vec::new(),
2635 directive_invocations: ::std::vec::Vec::new(),
2636 },
2637 );
2638 }
2639 });
2640 quote! {
2641 #gate! {
2642 const _: () = {
2643 #[automatically_derived]
2644 impl #ag::resolver_utils::EnumType for #name {
2645 fn items() -> &'static [#ag::resolver_utils::EnumItem<#name>] {
2646 &[#(#items,)*]
2647 }
2648 }
2649
2650 #[automatically_derived]
2651 impl #ag::InputType for #name {
2652 type RawValueType = Self;
2653
2654 #[inline]
2655 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
2656 ::std::borrow::Cow::Borrowed(#sdl)
2657 }
2658
2659 fn create_type_info(
2660 __ingraph_registry: &mut #ag::registry::Registry,
2661 ) -> ::std::string::String {
2662 __ingraph_registry.create_input_type::<Self, _>(
2663 #ag::registry::MetaTypeId::Enum,
2664 |_| #ag::registry::MetaType::Enum {
2665 name: ::std::string::String::from(#sdl),
2666 description: ::core::option::Option::None,
2667 enum_values: {
2668 let mut __ingraph_values = #ag::indexmap::IndexMap::new();
2669 #(#values)*
2670 __ingraph_values
2671 },
2672 visible: ::core::option::Option::None,
2673 inaccessible: false,
2674 tags: ::std::vec::Vec::new(),
2675 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
2676 directive_invocations: ::std::vec::Vec::new(),
2677 requires_scopes: ::std::vec::Vec::new(),
2678 },
2679 )
2680 }
2681
2682 fn parse(
2683 __ingraph_value: ::core::option::Option<#ag::Value>,
2684 ) -> #ag::InputValueResult<Self> {
2685 #ag::resolver_utils::parse_enum(
2686 ::core::option::Option::unwrap_or_default(__ingraph_value),
2687 )
2688 }
2689
2690 fn to_value(&self) -> #ag::Value {
2691 #ag::resolver_utils::enum_value(*self)
2692 }
2693
2694 #[inline]
2695 fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
2696 ::core::option::Option::Some(self)
2697 }
2698 }
2699 };
2700 }
2701 }
2702 }
2703
2704 /// Whether this declaration is dressed for `kind` — the ONE predicate every skin below asks.
2705 ///
2706 /// Asked in one place so that the three faces cannot come to disagree about what a missing block
2707 /// means, and so that a fourth face added later has a gate to reach for rather than a condition to
2708 /// re-derive.
2709 fn dressed(&self, kind: GraphqlKind) -> bool {
2710 self.graphql.is_some_and(|block| block.renders(kind))
2711 }
2712
2713 /// WHAT ONE EMITTED TYPE IS CALLED ON THE WIRE — the SDL naming home, and the only one.
2714 ///
2715 /// Every face below asks this rather than calling `name.to_string()`, so a rename cannot reach one
2716 /// face and miss another: the three hand-written skins and any fourth added later read one
2717 /// function, and `skins::the_backend_prefix_reaches_every_sdl_name` walks the roster through it.
2718 ///
2719 /// # Three answers, in the ruled order: MEMBER, then BASE-DERIVED, then DEFAULT
2720 ///
2721 /// A per-face override names ONE type outright, so it is carried VERBATIM — a name a declaration
2722 /// CHOSE is that declaration's, and camel-casing it would be this framework overriding the choice.
2723 /// The BASE is a stem the emission composes with a suffix, so it is upper-camel-cased at these
2724 /// positions, which is what GraphQL's own type convention is and what the ruling asks for. With
2725 /// neither, the SDL name is the Rust name, which is where this family started.
2726 ///
2727 /// The order is the 2026-08-16 ruling's second law, and it is what makes a MEMBER BLOCK
2728 /// STANDALONE-LEGAL: the member arm is answered before the base is even read, so a declaration
2729 /// that wrote `question(rename = "ClipAsk")` and no `rename = "…"` above it gets its word — one
2730 /// override is a complete declaration, not half of a pair.
2731 ///
2732 /// # The base re-bases by REPLACING the declaration's own segment
2733 ///
2734 /// Every name this family mints is the index's ident followed by at least one more camel-case
2735 /// segment — the fact `IndexModel::emitted_types` already states out loud and
2736 /// `skins::every_minted_name_is_built_on_the_declarations_own` pins. So re-basing is exactly
2737 /// swapping that leading segment, and a name that somehow did not carry it keeps its own: a
2738 /// silent double-prefix would be worse than an unrenamed type.
2739 pub(crate) fn sdl(&self, name: &syn::Ident) -> String {
2740 let rust = name.to_string();
2741 // THE MEMBER, first and without reading the skin at all — see the order above for why the base
2742 // is not a precondition of a member being spent.
2743 if let Some((_, spelled)) = self.members.iter().find(|(face, _)| face == name) {
2744 return spelled.value();
2745 }
2746 let Some(skin) = self
2747 .graphql
2748 .and_then(|block| block.skin(GraphqlKind::AsyncGraphql))
2749 else {
2750 return rust;
2751 };
2752 let Some(base) = skin.prefix.as_ref() else {
2753 return rust;
2754 };
2755 let base = base.value().to_upper_camel_case();
2756 rust
2757 .strip_prefix(&self.base.to_string())
2758 .map_or(rust.clone(), |rest| format!("{base}{rest}"))
2759 }
2760}
2761
2762impl IndexModel {
2763 /// This declaration's TIER of the fusion tree — see [`fuse`](crate::fuse) for the packages it
2764 /// mints and the binding table that picks which one a parent absorbs.
2765 ///
2766 /// A borrow of the lists this model already holds, rather than a second copy of them.
2767 #[must_use]
2768 pub fn tier(&self) -> Tier<'_> {
2769 Tier {
2770 krate: &self.krate,
2771 vis: &self.vis,
2772 index: &self.index,
2773 kind: self.kind,
2774 embeddings: &self.embeddings,
2775 searchable: &self.searchable,
2776 engines: &self.engines,
2777 graphql: self.graphql.as_ref(),
2778 rename: self.rename.as_ref(),
2779 field_numbers: &self.field_numbers,
2780 }
2781 }
2782}