ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! WHERE an elected field is written: the engine blocks a declaration wears, and the SLOT each one
//! names.
//!
//! ```text
//! #[ingraph(knn, lance, hnsw(ef = 200), fanout)]
//! pub image: Embedding<f32, 768>,
//! ```
//!
//! One field, one election, and beside it the engines that hold it. The words are BARE and they
//! carry their own options, because on an index field the ENGINE IS THE STORE — there is no second
//! axis for a `persist(…)` wrapper to namespace against, which is the whole of why the record's
//! shape is not repeated here.
//!
//! # The semantics are the RECORD's, measured and mirrored rather than reinvented
//!
//! Several blocks are declared PORTABILITY, and the default is SINGLE-WRITE. That is not a new rule:
//! it is what `persist(sqlite, postgres)` already means, and the record side answers *which one is
//! live* in two layers that this module mirrors exactly —
//!
//! | layer | the record side | here |
//! |---|---|---|
//! | COMPILE — declared ∩ compiled-in | `__private::gate::if_<db>!` around every impl naming a concrete backend | [`EngineKind::gate`], around every impl naming a concrete engine |
//! | CALL — which store this call writes | the METHOD NAME (`insert_postgres`), the driver staying a type parameter | the SLOT (`field × engine`), the engine staying a type parameter |
//!
//! The record side's own words for the second layer: *an expansion may not spell `sqlx::Sqlite`, so
//! the method NAME is where the database is chosen and the type parameter is where the driver is.*
//! Read back here, the SLOT is where the engine is chosen and the type parameter is where the engine
//! handle is — which is the shape a derived index's emitted retrieve already had before this round,
//! carrying `__INGRAPH_ENGINE__` as a method parameter.
//!
//! So *declare many, build one, and write through whichever door the deployment opened* is
//! inherited whole. [`fanout`](FieldEngines::fanout) is the ONE departure, and it is a marker
//! precisely because it departs.
//!
//! # The vocabulary is OPEN, and [`EngineKind`] is not the vocabulary
//!
//! [`DatabaseKind`](crate::model::DatabaseKind) is CLOSED — *a database the framework does not ship
//! an emitter for has nothing to be opened* — and the engine axis is the opposite case, which is why
//! the two tables look alike and mean different things. A database needs an emitter here; an engine
//! needs only an implementation of a trait `ingraph` already publishes, and third parties are
//! expected to bring them. [`EngineKind`] is therefore the SHIPPED table — the words that self-bind
//! under their own feature — and a word outside it is an ordinary declared word whose binding is the
//! graph root's `engines(…)`.

use quote::format_ident;

use crate::model::NodeKind;

/// An engine `ingraph` itself ships — the words that SELF-BIND under a feature of the framework's
/// own.
///
/// # Why a table at all, when the vocabulary is open
///
/// Three facts are true of a shipped word and of no other, and each of them is a refusal or an
/// emission that has to know:
///
/// 1. it names a CONCRETE type this crate can spell, so the impls naming one ride
///    [`gate`](Self::gate) — the record side's law, applied to the engine axis;
/// 2. it is a KIND, and kind is said ONCE — at the resource. So the word at an ELECTION is a named
///    refusal whichever kind it serves, and [`serves`](Self::serves) is what lets that sentence say
///    what the word actually holds. (It was a kind-GUARDED refusal while the word self-bound at the
///    election; the resource axis dropped the guard and kept the reading.)
/// 3. it is ALREADY BOUND, so `engines(tantivy = "…")` at a graph root is a refusal — rebinding a
///    shipped word would give one word two meanings in one program.
///
/// A word outside this table is none of those things and is refused for none of them.
///
/// # It has TWO members, and that is a measurement rather than a stub
///
/// `ingraph` ships exactly two engine implementations: `TantivyFulltext` under `feature = "tantivy"`,
/// and the local-filesystem blob store under NO feature at all. There is no `VectorEngine`
/// implementation in this workspace — *lance* appears in this repository only in prose and in the
/// unbuilt `legacy/` reference — so the vector side of the grammar is served entirely by the open
/// half, which is the strongest argument the open half has.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EngineKind {
  /// Tantivy, the shipped FULL-TEXT engine.
  Tantivy,
  /// The local filesystem, the shipped ARTIFACT store.
  Fs,
}

impl EngineKind {
  /// Every shipped engine, in the order a refusal lists them.
  pub const ALL: [Self; 2] = [Self::Tantivy, Self::Fs];

  /// The word a declaration writes.
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Tantivy => "tantivy",
      Self::Fs => "fs",
    }
  }

  /// WHICH KIND of declaration this engine serves.
  ///
  /// A full-text engine holds documents and a vector engine holds coordinates, and the two seams are
  /// different traits. It is read in two places and means the same thing in both: the BLOB walk
  /// refuses a word of another family outright, and the ELECTION's retirement sentence — which
  /// refuses every shipped word, its own kind included — spends it to say what the word holds and
  /// therefore which `#[ingraph::resource(…)]` declaration to write instead.
  #[must_use]
  pub const fn serves(self) -> NodeKind {
    match self {
      Self::Tantivy => NodeKind::Fulltext,
      Self::Fs => NodeKind::Blob,
    }
  }

  /// The CONDITIONAL-EXPANSION gate this engine's concrete impls ride — `if_tantivy`, reached on
  /// `ingraph`'s `__private::gate` shelf.
  ///
  /// Mechanical from [`as_str`](Self::as_str), exactly as
  /// [`DatabaseKind::gate`](crate::method) is: the word the declaration writes, the word the
  /// framework's feature carries and the word the gate is named after are ONE word, so the three
  /// cannot drift into naming different engines.
  ///
  /// This is the MEASURED mechanism of ruling 2, mirrored rather than reinvented. What it buys is
  /// what it buys on the record side: a declaration naming two engines in a build carrying one is
  /// bound to the one, and the other has no impl at all — `E0277` for a party that asks and silence
  /// for one that does not.
  ///
  /// # [`None`] for an engine under no feature
  ///
  /// `fs` is at the root under nothing — *a backend that needs no feature having no gate to carry*,
  /// which is `ingraph`'s own sentence about it — so there is no `if_fs` and a caller that wrapped
  /// its impls in one would name a macro that does not exist. An engine with no feature is always
  /// compiled in, which is the same answer the gate would have given, reached without inventing one.
  #[must_use]
  pub fn gate(self) -> Option<syn::Ident> {
    match self {
      Self::Tantivy => Some(format_ident!("if_{}", self.as_str())),
      Self::Fs => None,
    }
  }

  /// The word, if it is a shipped one.
  #[must_use]
  pub fn of(word: &syn::Ident) -> Option<Self> {
    Self::ALL.into_iter().find(|kind| word == kind.as_str())
  }
}

/// THE FROM-ROAD one engine block declares: how the elected field's value becomes THIS engine's
/// document text.
///
/// # `from` and no `into`, and the direction law is why
///
/// *`from` BUILDS the projection a block is about* — here, the document. There is no `into` leg and
/// there is not going to be one: a document is written and searched, never hydrated back into the
/// domain. What a hit hands back is an ADDRESS, and that pair does round-trip, which is the axis
/// this one deliberately lacks.
///
/// # The shorthands are a SEAM, not a closed pair
///
/// `join` and `multi` are the two the framework ships because they are the two loops a converter is
/// otherwise written out as, and they differ in the one thing the declaration is about: whether a
/// phrase may match ACROSS two values. A third builtin arrives as a variant here and an arm in the
/// walk — no grammar change, because the position it is written in already exists.
///
/// # Per ENGINE BLOCK, and it could not be per field
///
/// The segmentation means different things to different engines: a positional one puts a gap
/// between segments, and a single-text-column face has to flatten them — so one converter indexes
/// correctly in the first and subtly wrongly in the second, both "working" and only the results
/// differing. A field-level, engine-agnostic road is therefore not expressible, which is what puts
/// this member on the block rather than beside the election.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Road {
  /// NOTHING was declared — the IDENTITY road, the field's value being the document text as it
  /// stands.
  ///
  /// The default, and the one that can REFUSE: whether a value is text at all is not a question a
  /// front end can answer, so it is asked as a BOUND at the expansion and the refusal lands on the
  /// field's own type token. See `ingraph`'s `Searchable`.
  #[default]
  Identity,
  /// `join = "<sep>"` — ONE segment, the values written into it with the separator between them. A
  /// phrase CAN match across two values.
  Join(syn::LitStr),
  /// `multi` — ONE SEGMENT PER VALUE. A phrase CANNOT match across two of them.
  Multi,
  /// `from = "…"` / `try_from = "…"` — the conversion the declaration NAMED, in the SHIPPED family
  /// every other crossing in this grammar is written in.
  ///
  /// [`Conversion::Default`](crate::model::Conversion::Default) never reaches here: a block that
  /// named no function took [`Identity`](Self::Identity), which is a different road rather than a
  /// missing one.
  Declared(crate::model::Conversion),
}

impl Road {
  /// Whether the block wrote a road at all, or took the identity one by saying nothing.
  #[must_use]
  pub const fn declared(&self) -> bool {
    !matches!(self, Self::Identity)
  }

  /// Whether this road can FAIL — the one bit that decides the emitted slot's error type.
  ///
  /// Only a declared `try_from` can: the identity road pushes what it was handed, and both
  /// shorthands are loops over that.
  #[must_use]
  pub const fn fallible(&self) -> bool {
    match self {
      Self::Declared(conversion) => conversion.fallible(),
      Self::Identity | Self::Join(_) | Self::Multi => false,
    }
  }

  /// The WORD a refusal names this road by.
  #[must_use]
  pub const fn word(&self) -> &'static str {
    match self {
      Self::Identity => "identity",
      Self::Join(_) => "join",
      Self::Multi => "multi",
      Self::Declared(_) => "from",
    }
  }
}

/// ONE engine block as a field declared it — the word, and whatever it carried.
#[derive(Debug, Clone)]
pub struct Engine {
  /// The word, carrying its own span — where every refusal about this block lands.
  pub word: syn::Ident,
  /// The FROM-ROAD this block declares — [`Road::Identity`] where it declared none.
  pub road: Road,
  /// `stored` — this engine KEEPS the original value, retrievable.
  ///
  /// `false` unless the word was written, and the cheap default is the ruled one: only the computed
  /// result is guaranteed SEARCHABLE, and retrieval is opt-in. What it reaches in the shipped engine
  /// is tantivy's `STORED` flag on the body field.
  pub stored: bool,
  /// `resource = "path::To::Resource"` — the RESOURCE this leg is written to, as the declaration
  /// POINTED at it.
  ///
  /// # It POINTS; it does not TYPE. `type =` retired to get here
  ///
  /// The word this replaces named an ENGINE directly, which put the kind of a store in two places:
  /// on the declaration that wrote the type, and on whatever the deployment actually opened. **Kind
  /// is said once, at the resource** — `#[ingraph::resource(tantivy)] pub struct Ft;` — and every
  /// other position POINTS at that declaration. So what a leg holds is the path of a resource, and
  /// the engine underneath it is the resource's own business.
  ///
  /// # What POINTING buys that TYPING did not
  ///
  /// A slot's package still publishes knobs in the store's own currencies — a floor is a
  /// `<Ft as FulltextEngine>::Score` and a search input is that store's own — and the projection is
  /// unchanged in shape: it simply runs off the RESOURCE type rather than off an engine type.
  /// Two facts come free with the move:
  ///
  /// - the KIND CHECK is the projection itself. `<Ft as FulltextEngine>::Score` is `E0277` at the
  ///   path the author wrote when `Ft` is a vector resource, so *named → kind-verified* needs no
  ///   marker trait and no check anyone can forget to run;
  /// - two resources of ONE KIND are two TYPES and therefore two `TypeId`s, which is what lets a
  ///   deployment run two stores of the same engine and keeps a door citizen's `Shared<R>` lookup
  ///   unambiguous. A word bound to a type could not say that.
  ///
  /// # [`None`] is the ordinary state, and it is the SOLE-DEFAULT's condition
  ///
  /// An unpointed leg contributes no variant and a slot whose legs are all unpointed grows no
  /// `engine` seat at all — the presence law, unchanged. What is new is that saying nothing is no
  /// longer only a fallback: a deployment declaring exactly ONE resource of this leg's kind binds
  /// it by that fact alone, and zero or several is a START-UP refusal listing the candidates. See
  /// the binding laws on [`FieldEngines`].
  ///
  /// REFER-QUOTED, so the path resolves at the span its author wrote and a path naming nothing is
  /// `E0412` there rather than inside an expansion.
  pub resource: Option<syn::Path>,
  /// The block's contents, UNINTERPRETED, and empty where the word was written bare.
  ///
  /// # Verbatim, and it could not be otherwise
  ///
  /// `hnsw(ef = 200)` names a knob of an engine this crate has never heard of. Reading it would mean
  /// carrying every engine's option set here — the maintenance an open vocabulary exists to avoid —
  /// and refusing what it could not read would close the vocabulary through the back door. So the
  /// tokens are carried to the binding and interpreted by whoever owns the engine, which is the same
  /// division the framework already draws around a backend's own words.
  ///
  /// A [`proc_macro2::TokenStream`] rather than parsed pairs, therefore, and the spans inside it are
  /// the author's own — so an engine that refuses one of its knobs refuses it where it was written.
  ///
  /// # It is the block MINUS the framework's own words, and that is not a hole in the argument
  ///
  /// [`road`](Self::road) and [`stored`](Self::stored) are written inside these parentheses and are
  /// taken out of what is carried. The division is the same one the outer walk already draws: a
  /// FRAMEWORK word has one meaning wherever it appears, and an engine's knob has whatever meaning
  /// its engine gives it. Reading `ef = 200` would mean carrying every engine's option set here;
  /// reading `stored` means carrying one word whose meaning the framework defines, and whose whole
  /// point is that it means the same thing to every engine that has a doc store.
  ///
  /// The price is stated rather than hidden: an engine with a knob of its own called `stored`,
  /// `join`, `multi`, `from`, `try_from`, `resource` or `lanes` cannot spell it here, because the
  /// framework claimed the spelling first. That is the ordinary cost of a shared namespace, and it
  /// is bounded by seven words.
  pub options: proc_macro2::TokenStream,
  /// `rrf = <bool>` — whether this leg enters the FUSED ROAD of the slot it holds.
  ///
  /// # It is LEADERBOARD MEMBERSHIP and nothing else
  ///
  /// A fanned slot writes every declared engine at once. What that fan is FOR is two different
  /// things and the declaration could not say which: a leaderboard, where each engine's ranking is
  /// separate evidence and the fold joins them; or REDUNDANCY, where the same content lives in
  /// several stores and a read comes from one of them. `rrf = false` is the second — the leg is
  /// written and is not a route.
  ///
  /// # TRUE by absence, per the de-Option law
  ///
  /// A `bool` rather than an `Option<bool>`: there is no third state. The default is the shape a
  /// fan already had before the word existed, so a declaration that says nothing keeps exactly the
  /// slot it had — which is what makes the word purely additive.
  ///
  /// # ORTHOGONAL to [`resource`](Self::resource), and all four quadrants mean something
  ///
  /// `resource =` is ADDRESSABILITY (and the `Score` projection a package publishes floors in);
  /// `rrf =` is leaderboard membership. A pointed leg outside the leaderboard is directly readable
  /// and does not rank; an unpointed leg inside it ranks and cannot be named by a request; a leg
  /// that is neither is written for redundancy alone.
  pub rrf: bool,
  /// `lanes(zh(accepts(cmn)), en, rest(catch_all))` — the PARTITIONS this leg's corpus is cut into,
  /// in declaration order, and EMPTY where the word was not written.
  ///
  /// # Presence is the whole state, and absence is the corpus that always was
  ///
  /// An empty list is a declaration that said nothing about lanes, and what it mints is nothing: the
  /// slot takes [`Lanes`](../../ingraph/trait.Lanes.html)' own default, which is ONE lane keyed
  /// `und`. So the word is purely additive — a leg that never wrote it emits, indexes and answers
  /// exactly as it did before the word existed.
  ///
  /// # The KEY and the ALIASES are read; the ANALYZER is not here
  ///
  /// A lane's EXISTENCE shapes the slot, so it is a compile-time fact and this grammar reads it. Its
  /// INSTANCE is a value a deployment builds at boot, so a `tokenizer = "…"` written inside a lane
  /// is the ENGINE's knob and rides [`options`](Self::options) with every other one — the same
  /// partition the block around it already draws, one grain down. That division is the ruling's own:
  /// *a lane's existence is a declaration fact, its instance an assembly one.*
  pub lanes: Vec<DeclaredLane>,
}

/// ONE LANE, as a `lanes(…)` block wrote it — the framework's half of one entry.
///
/// The engine's half of the same entry is NOT here: it is carried verbatim into
/// [`Engine::options`], because a lane's analyzer is a word only the backend reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclaredLane {
  /// The lane's KEY, carrying its own span — where a refusal about this lane lands, and the one word
  /// the gate ever hands back.
  pub key: syn::Ident,
  /// `accepts(…)` — the tags this lane answers beside its own key, in the order they were written.
  pub accepts: Vec<syn::Ident>,
  /// `catch_all` — the WORD itself where it was written, so a refusal about a SECOND catch-all lands
  /// on the second one rather than on the roster.
  pub catch_all: Option<syn::Ident>,
}

impl DeclaredLane {
  /// A lane keyed `key`, accepting nothing and catching nothing — the bare `zh` entry.
  #[must_use]
  pub fn of(key: syn::Ident) -> Self {
    Self {
      key,
      accepts: Vec::new(),
      catch_all: None,
    }
  }

  /// Every WORD this lane claims — its key first, then its aliases.
  ///
  /// That order is not a preference: it is the order
  /// [`lane_claim`](../../ingraph/fn.lane_claim.html) addresses a roster's flat claim positions in,
  /// and the emitted per-word assertions are counted out against those positions. Two orders would
  /// put a refusal's sentence on the wrong word.
  pub fn claims(&self) -> impl Iterator<Item = &syn::Ident> {
    core::iter::once(&self.key).chain(self.accepts.iter())
  }
}

impl Engine {
  /// A block written BARE — `tantivy` with no parentheses at all.
  ///
  /// The most common shape by far, and the one every default is defined against: the identity road,
  /// nothing kept, NOTHING POINTED AT, no knobs carried, no lanes cut, and IN the fused road. A named
  /// constructor rather than a [`Default`], because the WORD is not defaultable and a partial default
  /// would be the thing that quietly disagrees with the grammar when an eighth framework word
  /// arrives.
  #[must_use]
  pub fn bare(word: syn::Ident) -> Self {
    Self {
      word,
      road: Road::Identity,
      stored: false,
      resource: None,
      options: proc_macro2::TokenStream::new(),
      rrf: true,
      lanes: Vec::new(),
    }
  }

  /// The shipped engine this word names, or [`None`] for a word bound at the graph root.
  #[must_use]
  pub fn shipped(&self) -> Option<EngineKind> {
    EngineKind::of(&self.word)
  }
}

/// ONE `engines(<word> = "path::To::Engine")` entry on a graph root — a WORD bound to a CONCRETE
/// TYPE.
///
/// # Why the binding is at the ROOT and not on the declaration
///
/// A word on a field is a NAME, and a name is bound where the program is assembled. Writing the path
/// on the declaration would bind it there — in a library crate that cannot know which engine the
/// application compiled, and cannot be re-pointed without editing the declaration. The root is the
/// one place that knows: it is the deployment's whole catalog already, and the same list the
/// resources are read off.
///
/// It is REFER-QUOTED for this grammar's standing reason: a word that points at something written
/// elsewhere is written in a string literal, so the path resolves at the span its author wrote.
///
/// # What it emits: the compile-time MEMBER TABLE
///
/// One marker type per bound word, carrying the concrete engine as an associated type. That table is
/// what a fused face reads to know which engines a query fans across, and it is a TYPE-level table
/// rather than a runtime map for the reason every other binding here is: a member resolved by name
/// at run time is a member no signature can be written against.
#[derive(Debug, Clone)]
pub struct EngineBinding {
  /// The WORD, exactly as a field would spell it.
  pub word: syn::Ident,
  /// The CONCRETE engine type, carried VERBATIM and resolved nowhere in this crate.
  ///
  /// The tokens are the author's own — respanned onto the string literal that named them — so a path
  /// naming nothing is `E0412` where it was written, which is the division every referring word in
  /// this grammar is under.
  pub engine: syn::Path,
}

impl EngineBinding {
  /// The ZERO-SIZED TYPE this binding is carried as — `<Root>Engine<Word>`.
  #[must_use]
  pub fn marker(&self, root: &syn::Ident) -> syn::Ident {
    use heck::ToUpperCamelCase as _;

    format_ident!(
      "{root}Engine{}",
      self.word.to_string().to_upper_camel_case()
    )
  }
}

/// ONE elected field's engines, and whether all of them are live at once.
#[derive(Debug, Clone)]
pub struct FieldEngines {
  /// The field these engines hold — one of the declaration's own elections.
  pub field: syn::Ident,
  /// The engines, in the order they were WRITTEN.
  ///
  /// Order is kept for [`Persist::backends`](crate::model::Persist)' reason: the slots emit in the
  /// order the author wrote them, so an expansion is stable and diffable. It may be EMPTY — an
  /// election that named no engine is a declaration that has not said where its index lives, which
  /// is legal and means the deployment says instead.
  pub engines: Vec<Engine>,
  /// `fanout` — ALL declared engines simultaneously live.
  ///
  /// # What the marker changes, and what it deliberately does not
  ///
  /// Without it the blocks are PORTABILITY: the deployment opens one slot and writes through it,
  /// which is the record side's *declare many, build one* inherited whole. With it every declared
  /// engine's slot is live at once — the write lane fans to all of them, and the per-engine rankings
  /// enter FUSION as separate evidence on the way back.
  ///
  /// R2 builds the WRITE half and RECORDS the read half. The read side's fan-and-fuse is the face
  /// round's to consume, and it is recorded rather than sketched for the reason this crate refuses
  /// every other promise: a word parsed into a model nothing spends is a promise rather than a rule.
  /// What is spent today is the write, and it is spent completely.
  ///
  /// On a field with FEWER THAN TWO engines the marker is a named refusal — there is nothing to fan.
  pub fanout: bool,
}

impl FieldEngines {
  /// The legs that ENTER this field's fused road — the `rrf` half of a fanned slot's declaration.
  ///
  /// Read wherever a fanned slot's mini tier is shaped: the `Route` seats it carries, the evidence
  /// variants a fold can produce, and whether the mini fuse door emits at all. Every leg still
  /// WRITES — that half is [`fanout`](Self::fanout)'s and this word does not touch it.
  pub fn participants(&self) -> impl Iterator<Item = &Engine> {
    self.engines.iter().filter(|engine| engine.rrf)
  }

  /// The SLOTS this field declares — one per engine.
  #[must_use]
  pub fn slots(&self) -> Vec<Slot> {
    self
      .engines
      .iter()
      .map(|engine| Slot {
        field: self.field.clone(),
        engine: engine.word.clone(),
      })
      .collect()
  }
}

/// ONE SLOT: a field and the engine that holds it.
///
/// # Slot identity moved, and this type is the move
///
/// It used to be the DECLARATION — one `FulltextTable::SLOT` per index, and *one declaration, one
/// slot* was the keystone the brand rested on. Under the engine grammar it is `(field × engine)`,
/// and the per-slot laws follow it there: ONE Tantivy index per slot, because BM25's corpus
/// statistics are index-wide, is now one index per `(field, engine)` — which is what makes two
/// fields of one declaration searchable independently without their scores moving under each other.
///
/// The COLUMN axis is unchanged and is one grain finer: a vector slot may still hold several
/// columns, and `VectorColumn` still says which one a knn runs over. What this type adds is the axis
/// above it, not a replacement for the one below.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Slot {
  /// The elected field.
  pub field: syn::Ident,
  /// The engine word — as WRITTEN, since a free word has no other spelling.
  pub engine: syn::Ident,
}

impl Slot {
  /// This slot's durable NAME, as the emission mints it: `<index>__<field>__<engine>`.
  ///
  /// # Why all three parts, and why the double underscore
  ///
  /// A slot name reaches a directory, a table or a virtual table, so two slots sharing one is two
  /// declarations sharing a corpus — the exact class the brand exists to keep out. All three parts
  /// are therefore in the name: two indexes may declare a field of the same name, and one field may
  /// name several engines.
  ///
  /// The separator is `__` because a single one is legal INSIDE each part — `image_embedding` is a field
  /// name — so a single-underscore join would let `a_b` × `c` and `a` × `b_c` mint one name. It is
  /// not the framework's `__…__` fence: that reservation is *both ends*, and this name has neither.
  ///
  /// SNAKE CASE from the index's own name, which is the convention
  /// [`RecordModel::table_name`](crate::model::RecordModel::table_name) already defaults a table to
  /// — one convention for every durable name a declaration mints.
  #[must_use]
  pub fn name(&self, index: &syn::Ident) -> String {
    use heck::ToSnakeCase as _;

    format!(
      "{}__{}__{}",
      index.to_string().to_snake_case(),
      self.field,
      self.engine,
    )
  }

  /// The ZERO-SIZED TYPE this slot is carried as — `<Index><Field><Engine>`.
  ///
  /// A TYPE and not a name, for the reason the election markers are types: a handle branded with a
  /// slot cannot be handed to another slot's door, and a brand is a fact carried through the types.
  /// A `SlotName` alone would put the pairing back in a value, where a swap is a runtime mistake
  /// nobody sees.
  #[must_use]
  pub fn marker(&self, index: &syn::Ident) -> syn::Ident {
    use heck::ToUpperCamelCase as _;

    format_ident!(
      "{index}{}{}",
      self.field.to_string().to_upper_camel_case(),
      self.engine.to_string().to_upper_camel_case(),
    )
  }
}

#[cfg(test)]
mod tests;