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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! The RESOURCE declaration's emission: citizenship, the mode the declaration recorded, and — where
//! a BUILTIN KIND WORD was written — the engine the macro mints and the impls that delegate to it.
//!
//! ```ignore
//! #[ingraph::resource]          pub struct Egemma { model: EgemmaModel } // FOREIGN: hand impls
//! #[ingraph::resource(async)]   pub struct MyRemote(RemoteQdrant);       // FOREIGN, awaited faces
//! #[ingraph::resource(tantivy)] pub struct Ft;                           // BUILTIN: the macro mints
//! ```
//!
//! # THE FOREIGN FORM emits ONE ITEM, and the item is two refusals
//!
//! `impl DeclaredResource for Egemma { … }` — the CITIZENSHIP, which the walk enumerates. The trait's
//! SUPERTRAIT is what makes the same line an assert: `DeclaredResource: AsyncResource`, so a declaration
//! with no `AsyncResource` impl is `E0277` AT THE DECLARATION; and `AsyncResource: Send + Sync`, so a type
//! that cannot cross threads is refused at the same site, which is the earliest one there is.
//!
//! Its BODY is the mode the declaration recorded — `const SYNC` — and that is the whole of what the
//! `async` word buys here. The faces themselves stay the author's own hand: this is the OPEN SEAM,
//! and a macro that wrote an engine impl for a type it has never seen would be closing it.
//!
//! # A SECOND audit was written and removed, and the measurement is why
//!
//! Every other emission in this crate states a bound it wants a reader to meet as a sentence
//! through an audit CALL in an anonymous `const` —
//! [`stores_rows`](../../ingraph/fn.stores_rows.html)'s shape. One was written here, and the
//! measurement is that rustc reports the missing contract at the DECLARATION's own type name
//! either way, with the `on_unimplemented` note either way — so the audit produced a second error
//! saying exactly what the first one said. It is gone, and the note is what stops it being
//! rediscovered.
//!
//! # THE BUILTIN FORM is the same declaration with the engine filled in
//!
//! A kind word names one of the framework's own engines, so everything the foreign author writes by
//! hand is known here and is written for them: the declaration is re-emitted CARRYING the engine (a
//! kind word takes a declaration with no fields, precisely so the macro owns the one it mints), the
//! `AsyncResource` impl opens it, and the base plus the two faces of the engine's OWN MODE delegate to
//! it. No face of the other mode is emitted, because the kind word carries the mode knowledge and a
//! second face would be this crate claiming a posture the engine does not have.
//!
//! It rides the engine's own cargo gate, and the shut half carries the author's declaration back
//! beside a `compile_error!` — see [`ResourceKind::gate`].
//!
//! # No accessor family, and that is the tier rather than an omission
//!
//! A record's expansion hands its fields out; a resource's does not. A resource is reached through
//! [`Shared<R>`](../../ingraph/struct.Shared.html), which derefs to the type itself, so what a
//! member can do with one is whatever the AUTHOR's own inherent impl offers. Emitting accessors
//! would put this crate's naming convention on a type whose whole surface is somebody else's.
//!
//! The BUILTIN form has two inherent items anyway, and the line is exactly the one above: the macro
//! MINTED that engine, so the two doors onto it are this crate's to name — see
//! [`ResourceKind::emit`].

use crate::prefix::EmissionPrefix;
use quote::{format_ident, quote};

#[cfg(test)]
mod kind_tests;
#[cfg(test)]
mod tests;

/// WHICH FACE a resource's engine impls wear — the `async` word, as a closed vocabulary.
///
/// [`Block`](../../ingraph/struct.Block.html) / [`Async`](../../ingraph/struct.Async.html) at the
/// declaration's grain, and one word of the same lexicon `source(async)`, `handler(async)` and
/// `operator(async)` are written in. What it reaches is one `const SYNC` on the emitted citizenship,
/// which the ELECTION's emission reads to decide which of an engine's two face pairs to bind.
///
/// An enum rather than a `bool` for the reason every closed vocabulary in this crate is one: the two
/// ends have names, and a field called `sync` reads as an answer to a question nobody asked at the
/// declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ResourceMode {
  /// The BLOCKING face — a bare declaration, and every builtin whose engine answers without a
  /// future.
  #[default]
  Block,
  /// The AWAITED face — what the `async` word buys.
  Async,
}

impl ResourceMode {
  /// Whether this mode's verbs answer without a future — the `bool` the emitted `SYNC` carries.
  #[inline]
  #[must_use]
  pub const fn sync(self) -> bool {
    matches!(self, Self::Block)
  }
}

/// A BUILTIN ENGINE a resource declaration may name in one word — the CLOSED framework vocabulary.
///
/// # Closed, and short, and both on purpose
///
/// A kind word is a promise that this crate can write the whole engine binding, which it can only
/// keep for an engine it SHIPS. So the vocabulary holds exactly the engines in the tree, and it
/// holds them by NAME rather than by family: `tantivy` is a word because
/// `store::tantivy` is an engine; `lance` is not, because nothing in this tree implements one, and a
/// word whose emission has no target is a promise made to a reader who then cannot cash it. The
/// OPEN half of the axis is the bare form, which needs no vocabulary at all.
///
/// # It is the ONE home of the word list
///
/// The grammar refuses an unknown kind word by naming the known ones, and the emitter writes what
/// each one means. Both read [`WORDS`](Self::WORDS) and [`from_word`](Self::from_word) here, so a
/// word cannot be spellable in one and unknown in the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceKind {
  /// `tantivy` — the shipped full-text engine: a `TantivyStore` connection-manager, its per-slot
  /// `TantivyFulltext` handle, and a corpus per resource.
  Tantivy,
}

impl ResourceKind {
  /// Every builtin kind word, in the order a refusal lists them.
  pub const WORDS: &'static [&'static str] = &["tantivy"];

  /// The kind `word` names — `None` for a word this vocabulary does not hold.
  #[inline]
  #[must_use]
  pub fn from_word(word: &str) -> Option<Self> {
    match word {
      "tantivy" => Some(Self::Tantivy),
      _ => None,
    }
  }

  /// The word that names this kind.
  #[inline]
  #[must_use]
  pub const fn word(self) -> &'static str {
    match self {
      Self::Tantivy => "tantivy",
    }
  }

  /// THE MODE THE KIND CARRIES, which is why a kind word takes no `async` beside it.
  ///
  /// Tantivy is a SYNCHRONOUS engine — the shipped face does its work inline and the async twin is
  /// the blocking body with `ready` around it — so a resource of this kind wears the blocking faces,
  /// and nothing an author writes can make that untrue. This is what the word *carries its own mode*
  /// means, and what makes `resource(tantivy, async)` a refusal rather than a preference.
  #[inline]
  #[must_use]
  pub const fn mode(self) -> ResourceMode {
    match self {
      Self::Tantivy => ResourceMode::Block,
    }
  }

  /// WHAT A RESOURCE OF THIS KIND HOLDS — the facet the SOLE-DEFAULT binding is resolved against.
  ///
  /// The word carries it for the reason it carries the mode: `tantivy` IS a full-text store, and an
  /// author who wrote the word has already said so. A FOREIGN resource states it by hand — one
  /// line, the open seam's usual price — and says nothing by default, which costs exactly the
  /// sole-default convenience.
  #[must_use]
  pub fn kinds(self) -> proc_macro2::TokenStream {
    match self {
      Self::Tantivy => quote!(DOCUMENTS),
    }
  }

  /// WHAT A HOME LOOKS LIKE in a resource of this kind — the [`Habitat`] blueprint the word carries.
  ///
  /// The word knows the kind and the kind knows the vocabulary: `tantivy` holds documents, so a
  /// declaration's home in one is the CORPORA it owns there. A foreign resource states it by hand,
  /// which is one line and the open seam's usual price.
  ///
  /// [`Habitat`]: ../../ingraph/trait.Habitat.html
  #[must_use]
  pub fn blueprint(self, krate: &syn::Path) -> proc_macro2::TokenStream {
    match self {
      Self::Tantivy => {
        let schema = crate::emit::framework(krate, &["transform"], "SlotSchema");
        quote!(&'static [#schema])
      }
    }
  }

  /// THE FACTORY VISITOR a resource of this kind makes its homes with — LAYER TWO's machine, and the
  /// face its own MODE names.
  ///
  /// A builtin's machine is the framework's, because the framework wrote the engine: the word that
  /// mints the store mints the maker for it too. The pair is `(the author face to implement, the
  /// visitor type)`, and which face is [`mode`](Self::mode)'s answer — a blocking engine's maker is
  /// a [`TypeVisitor`] and an awaited one's is its twin, with no bridge between them.
  ///
  /// [`TypeVisitor`]: ../../ingraph/trait.TypeVisitor.html
  #[must_use]
  pub fn maker(self, krate: &syn::Path, name: &syn::Ident) -> proc_macro2::TokenStream {
    match self {
      Self::Tantivy => {
        let habitat = crate::emit::framework(krate, &["transform"], "Habitat");
        let initialize = crate::emit::framework(krate, &["drive"], "Initialize");
        let shared = crate::emit::framework(krate, &["resource"], "Shared");
        let maker = crate::emit::framework(krate, &["store"], "TantivySlotMaker");
        let blueprint = self.blueprint(krate);
        quote! {
          impl #habitat for #name {
            /// The corpora a declaration owns in THIS mount — one blueprint per election that
            /// points here, each carrying its durable name, its columns and the `stored` posture
            /// the declaration chose.
            type Blueprint = #blueprint;
          }

          impl #initialize for #name {
            /// The shipped slot maker, over this mount — the BLOCKING face, because opening a
            /// tantivy index is two syscalls and no await.
            type Visitor = #maker<Self>;

            #[inline]
            fn initializer(mount: #shared<Self>) -> Self::Visitor {
              #maker::new(mount)
            }
          }
        }
      }
    }
  }

  /// The two halves of the cargo gate this kind's emission rides — the OPEN one and its complement.
  ///
  /// The emission names types a build without the feature does not have, so it cannot be written
  /// unconditionally, and a `#[cfg(feature = …)]` inside an expansion asks the DECLARING crate for a
  /// feature it has never heard of. The gate pair is the crate's own answer to exactly that, and this
  /// is which pair a kind spends.
  #[inline]
  #[must_use]
  pub const fn gate(self) -> (&'static str, &'static str) {
    match self {
      Self::Tantivy => ("if_tantivy", "if_no_tantivy"),
    }
  }

  /// What a build WITHOUT this engine is told, at the declaration that asked for it.
  ///
  /// It names the feature and the manifest, because that is the whole fix. The alternative — letting
  /// the shut gate swallow the emission — leaves a reader an `AsyncResource` they never wrote and were
  /// never going to write.
  #[must_use]
  pub fn absent(self) -> String {
    format!(
      "`#[ingraph::resource({word})]` needs `ingraph`'s `{word}` feature — the kind word emits this \
       engine's own impls, and a build without the engine has no types for them to name. Add \
       `features = [\"{word}\"]` to the `ingraph` dependency, or drop the word and write the \
       resource's impls by hand (the foreign form).",
      word = self.word()
    )
  }

  /// The FIELD a kind word injects into the declaration — the engine the macro mints.
  ///
  /// The whole reason a resource macro is an ATTRIBUTE one: a builtin resource's author writes
  /// `pub struct Ft;` and the engine underneath it is this crate's business, so the declaration the
  /// compiler sees is not the declaration the author wrote. It is named the way every injected field
  /// here is — a spelling nothing outside the emission writes — and it is PRIVATE, because the two
  /// doors onto it are emitted beside it and are what a caller reaches.
  #[must_use]
  pub fn engine_field(self, krate: &syn::Path, prefix: &EmissionPrefix) -> syn::Field {
    use syn::parse::Parser as _;

    let ty: syn::Type = match self {
      Self::Tantivy => syn::parse_quote!(#krate::__private::store::TantivyStore),
    };
    let name = engine_field(prefix);
    syn::Field::parse_named
      .parse2(quote!(#name: #ty))
      .expect("a named field")
  }

  /// Everything this kind emits for the declaration `name`, under the crate `krate`.
  ///
  /// Three impls and one inherent block, and every one of them delegates:
  ///
  /// | item | what it says |
  /// |---|---|
  /// | `impl AsyncResource` | the store's own construction — `Options` and `Error` are the store's, and `build` is its open |
  /// | `impl DeclaredResource` | the citizenship, carrying the mode the KIND knows |
  /// | `impl FulltextEngine` | THE BASE: eight seats and the three address-lifecycle functions, projected off the store's per-slot handle |
  /// | `impl FulltextStore` | THE PER-SLOT FACTORY — the mode's own face, and the door every corpus is opened through |
  /// | `impl FulltextMount` | THE MODE-BLIND FACE over that factory, plus the manager it lends — what a WIRE DOOR names |
  /// | `impl Habitat` | WHAT A HOME LOOKS LIKE here — the corpora a declaration owns in this mount |
  /// | `impl Initialize` | LAYER TWO's machine: the shipped slot maker, on the face this kind's mode names |
  /// | `impl <Type>` | `connection()` — the one fact a caller needs to bundle a `Connected` |
  ///
  /// # A RESOURCE IS A STORE, and it is NOT a corpus
  ///
  /// This is the grain the whole emission turns on. A resource is the MOUNT — a connection-manager
  /// opened once, holding whatever pool or index root the deployment configured — and a SLOT is one
  /// corpus inside it, named by the ELECTION that writes it: `<index>__<field>__<label>`, which is
  /// `node × election` and is what boot slot-shape validation checks. Two elections pointing at ONE
  /// resource are therefore TWO corpora with two universes of BM25 statistics, which is the whole
  /// reason the grain is where it is: `docfreq` over `numdocs` and the average document length are
  /// INDEX-WIDE, so a title and a body sharing a corpus would move each other's scores.
  ///
  /// An earlier draft named ONE corpus per resource, after the declaration's own snake name. That
  /// read the resource as the corpus and left a deployment no way to hold two elections in one mount
  /// without merging their statistics. The two-`TypeId` story — two same-kind resources being two
  /// types and two `Shared<R>` lookups — is untouched and is what it always was: the answer for
  /// genuinely TWO STORES, not the answer for two corpora.
  ///
  /// # The BASE is projections and nothing else, which is what makes delegation honest
  ///
  /// Every seat is written as `<TantivyFulltext as FulltextEngine>::…` rather than as the concrete
  /// type it resolves to. So the day the engine changes one of them, this expansion changes with it
  /// and no declaration has to be re-emitted against a copy that drifted. The three lifecycle
  /// functions are ASSOCIATED ones, which is why the base needs no value at all to delegate.
  ///
  /// The base is also SLOT-BLIND — eight type seats and three address functions, not one of which
  /// names a corpus — which is exactly why it can sit on the mount. It is [`the kind trait`]: a leg
  /// writing `resource = "crate::Ft"` is verified by projecting through it, so a vector election
  /// pointed at a full-text resource is `E0277` at the path its author wrote.
  ///
  /// # NO READ AND NO WRITE FACE, and the slot grain is why
  ///
  /// `FulltextRead::search` and `FulltextWrite::upsert` carry no slot parameter — the per-slot
  /// HANDLE is what carries it, minted at the corpus name. A face on the mount would therefore have
  /// to bake ONE corpus name into itself, which is the reading this emission just refused. So the
  /// mount wears the FACTORY and the handle it mints wears the faces, and the two are never confused
  /// because they are two types.
  ///
  /// # The mode's FIRST TRUE SPEND is which factory face is written
  ///
  /// [`mode`](Self::mode) picks `FulltextStore` for a blocking store and `AsyncFulltextStore` for an
  /// awaited one. The pair differs in exactly one verb — `open` — because the per-slot factory is
  /// synchronous and infallible on both faces, so `open` is the whole of what a mode can change
  /// here. Tantivy's open is two syscalls and no await, so a `tantivy` resource is written on the
  /// BLOCKING face; the transitional posture that bound the awaited face regardless ends at this
  /// line.
  ///
  /// # …and the MOUNT is where that spend stops leaking outward
  ///
  /// Face selection happens AT THIS EMISSION and nowhere downstream, which is the whole reason
  /// `FulltextMount` exists: a wire door is expanded at an ELECTION, in a crate that can see the
  /// resource's path and not its mode, so a door written over either store face would serve half
  /// the resources there are. The two templates here — `FulltextStore` at `Block`,
  /// `AsyncFulltextStore` at `Async` — both close into one mode-blind seam, and the selection is
  /// therefore paid once by the party that knows the answer.
  ///
  /// # The one inherent door, and why it is not the accessor family the module refuses
  ///
  /// `connection()` hands out the manager THIS MACRO opened. That is a fact about the field the
  /// macro injected, not about anything the author wrote — so naming it here is this crate naming
  /// its own mint, which is the opposite of putting a convention on somebody else's surface. A
  /// caller needs it to bundle a [`Connected`](../../ingraph/struct.Connected.html), the connection
  /// being the borrow every verb takes back.
  #[must_use]
  pub fn emit(
    self,
    krate: &syn::Path,
    name: &syn::Ident,
    prefix: &EmissionPrefix,
  ) -> proc_macro2::TokenStream {
    let engine = match self {
      Self::Tantivy => tantivy(krate, name, self.mode(), prefix),
    };
    // LAYER TWO rides beside the engine and is written per KIND for the same reason the engine is:
    // the word knows what a home looks like here and which machine makes one, so the two lines a
    // foreign author writes by hand are written for a builtin.
    let maker = self.maker(krate, name);
    quote! {
      #engine
      #maker
    }
  }
}

/// A validated resource declaration, ready to emit.
///
/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a
/// manifest front end later reach the same emitter.
#[derive(Debug, Clone)]
pub struct ResourceModel {
  /// The EMISSION NAMESPACE this declaration's minted names wear.
  ///
  /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
  /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
  /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
  pub prefix: EmissionPrefix,
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  pub krate: syn::Path,
  /// The declared type — what the citizenship is emitted for.
  pub name: syn::Ident,
  /// The BUILTIN ENGINE this declaration named in one word — `None` for the FOREIGN form, which is
  /// the open seam and emits no engine impl at all.
  pub kind: Option<ResourceKind>,
  /// WHICH FACE this resource's engine impls wear.
  ///
  /// The `async` word where the declaration is foreign, and the KIND's own answer where it is not —
  /// which is why the two are refused together: a builtin's mode is knowledge the word carries, and
  /// a second opinion beside it could only disagree.
  pub mode: ResourceMode,
}

impl ResourceModel {
  /// The field a BUILTIN kind word injects into the host — `None` for the foreign form, whose
  /// declaration is echoed exactly as written.
  #[must_use]
  pub fn carried_engine(&self) -> Option<syn::Field> {
    self
      .kind
      .map(|kind| kind.engine_field(&self.krate, &self.prefix))
  }

  /// The IMPLS — the citizenship, and whatever a kind word adds beside it.
  ///
  /// The host is not here: an attribute macro replaces the item it sits on, and assembling the two is
  /// [`expand`](Self::expand)'s job because only the caller holds the declaration. This is what a
  /// reader asserts against.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let sync = self.mode.sync();
    // WHAT THE DECLARATION HOLDS. A builtin kind word answers it; the foreign form answers NOTHING
    // and takes the trait's empty default, which is the conservative half of the sole-default law —
    // a resource that has not said what it holds must not become the sole candidate for a leg it
    // cannot serve.
    let kinds = self.kind.map(|kind| {
      let held = kind.kinds();
      quote! {
        const KINDS: #krate::__private::resource::ResourceKinds =
          #krate::__private::resource::ResourceKinds::#held;
      }
    });
    let citizenship = quote! {
      impl #krate::__private::resource::DeclaredResource for #name {
        const SYNC: bool = #sync;
        #kinds
      }
    };
    match self.kind {
      None => citizenship,
      Some(kind) => {
        let engine = kind.emit(krate, name, &self.prefix);
        quote! {
          #citizenship
          #engine
        }
      }
    }
  }

  /// THE WHOLE EXPANSION — the declaration and the impls, assembled under whichever gate the
  /// declaration's kind rides.
  ///
  /// `plain` is the author's own host, re-emitted; `carrying` is that host with
  /// [`carried_engine`](Self::carried_engine) appended. THE HOST IS EMITTED WHETHER OR NOT the
  /// declaration was accepted and whichever half of a gate survives, for the reason every attribute
  /// macro in this family states: the macro replaces the item it sits on, so an expansion that
  /// dropped the host would delete the type and bury its own message under every mention of it.
  ///
  /// The FOREIGN form has no gate and no injection, so it is the two token streams' concatenation and
  /// nothing more — the semantics it has always had.
  #[must_use]
  pub fn expand(
    &self,
    plain: &proc_macro2::TokenStream,
    carrying: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let emitted = self.emit();
    let Some(kind) = self.kind else {
      return quote! {
        #plain
        #emitted
      };
    };
    let krate = &self.krate;
    let (open, shut) = kind.gate();
    let (open, shut) = (format_ident!("{open}"), format_ident!("{shut}"));
    let absent = kind.absent();
    quote! {
      #krate::__private::gate::#open! {
        #carrying
        #emitted
      }
      #krate::__private::gate::#shut! {
        #plain
        ::core::compile_error!(#absent);
      }
    }
  }
}

/// The name the injected engine is written under — a spelling nothing outside this module writes.
///
/// One function, so the field the injection APPENDS and the field the emitted bodies READ cannot be
/// given two spellings. It is private for the reason the doors beside it are public: what a caller
/// reaches is `connection()` and `SLOT`, and the field itself is the expansion's own business.
fn engine_field(prefix: &EmissionPrefix) -> syn::Ident {
  prefix.framed_ident("engine")
}

/// The `tantivy` kind word's whole emission — see [`ResourceKind::emit`] for what each item says.
///
/// Written as one function rather than as four, because the four share every path they name and the
/// alternative is threading a dozen `syn::Path`s between them.
///
/// `mode` is READ rather than assumed: it names the construction face, and a kind whose store opens
/// through a future would spell the awaited one at this same line. Passing it in is what makes the
/// choice a spend of [`ResourceKind::mode`] instead of a constant this function happens to agree
/// with.
fn tantivy(
  krate: &syn::Path,
  name: &syn::Ident,
  mode: ResourceMode,
  prefix: &EmissionPrefix,
) -> proc_macro2::TokenStream {
  let engine = engine_field(prefix);

  let store = quote!(#krate::__private::store::TantivyStore);
  let handle = quote!(#krate::__private::store::TantivyFulltext);
  let construction = match mode {
    ResourceMode::Block => quote!(#krate::__private::store::FulltextStore),
    ResourceMode::Async => quote!(#krate::__private::store::AsyncFulltextStore),
  };
  let base = quote!(#krate::__private::store::FulltextEngine);
  let mount = quote!(#krate::__private::store::FulltextMount);
  let bytes = quote!(#krate::__private::store::Utf8Bytes);
  // THE RESOURCE CONTRACT's `build`, which asks for a future whichever face the store opens on —
  // so it DELEGATES to the factory below rather than opening the store a second time, and the two
  // modes differ only in what stands between them.
  //
  // A BLOCKING open answers a `Result`, so the awaited construction is that `Result` with `ready`
  // around it: a wrapper over a value already computed, which is the one shape the dual-mode law
  // admits. The reverse — a `block_on` around an awaited open — is the fiction it refuses, and no
  // arm here writes one; the awaited face already answers a future and is forwarded untouched.
  let opened = match mode {
    ResourceMode::Block => quote! {
      ::core::future::ready(<Self as #construction>::open(options))
    },
    ResourceMode::Async => quote!(<Self as #construction>::open(options)),
  };
  // THE FACTORY'S OWN `open`, whose SHAPE is the one thing the two store faces differ in: the
  // blocking face answers a `Result` and the awaited one answers a future. Written out per mode
  // rather than shared, because a shared body would have to pick one shape and wrap the other.
  let open = match mode {
    ResourceMode::Block => quote! {
      /// Open the manager ONCE, on this thread — the store's own blocking open, with the mount
      /// wrapped around what it returns.
      #[inline]
      fn open(options: Self::Options) -> ::core::result::Result<Self, Self::Error> {
        <#store as #construction>::open(options).map(|#engine| Self { #engine })
      }
    },
    ResourceMode::Async => quote! {
      /// Open the manager ONCE — the store's own awaited open, with the mount wrapped around what
      /// it resolves to.
      #[inline]
      fn open(
        options: Self::Options,
      ) -> impl ::core::future::Future<Output = ::core::result::Result<Self, Self::Error>>
             + ::core::marker::Send {
        async move {
          <#store as #construction>::open(options)
            .await
            .map(|#engine| Self { #engine })
        }
      }
    },
  };

  quote! {
    impl #name {
      /// The connection-manager this resource opened, borrowed — what a call's
      /// `Connected` carries.
      ///
      /// One manager, opened once by `build` and held for the resource's life. It is handed out
      /// rather than kept private because every verb reached through this mount takes it back: a
      /// read reaches its slot's reader through it, and a write is queued into a writer taken on it.
      #[inline]
      #[must_use]
      pub fn connection(&self) -> &#store {
        &self.#engine
      }
    }

    impl #krate::__private::resource::AsyncResource for #name {
      /// The STORE's own construction input, projected rather than restated: whatever the store
      /// takes to open is what this resource's `[resources.…]` section carries.
      type Options = <#store as #construction>::Options;
      /// The store's own refusal, for the same reason.
      type Error = <#store as #construction>::Error;

      /// One construction, reached through the FACTORY beside it: `build` is the resource tier's
      /// name for the same act, so it delegates rather than opening the store a second time.
      ///
      /// The `ctx` seat is UNSPENT here and that is the honest state: what a store mount opens with
      /// is its own options, and a resource that wants a resource built before it reads it through
      /// this seat by hand rather than through an emission that cannot know which.
      #[inline]
      fn build(
        _ctx: &#krate::__private::drive::Resources,
        options: Self::Options,
      ) -> impl ::core::future::Future<Output = ::core::result::Result<Self, Self::Error>>
             + ::core::marker::Send {
        #opened
      }
    }

    impl #construction for #name {
      /// The three seats are the STORE's, projected — a mount that restated any of them would be a
      /// second copy to keep true.
      type Options = <#store as #construction>::Options;
      type Error = <#store as #construction>::Error;
      /// THE PER-SLOT HANDLE — stateless, minted per corpus, and the type that wears the read and
      /// write faces this mount deliberately does not.
      type Handle = <#store as #construction>::Handle;

      #open

      /// ONE CORPUS of this mount, by name.
      ///
      /// The name is the ELECTION's — `<index>__<field>__<label>`, minted by the declaration that
      /// writes the slot — and it arrives as a parameter for exactly that reason: a mount holds as
      /// many corpora as elections point at it, and baking one name in here is the reading this
      /// emission refuses. Sync and infallible, per the seam's own contract: a stateless handle
      /// needs no I/O to mint.
      #[inline]
      fn fulltext(&self, slot: impl ::core::convert::Into<#bytes>) -> Self::Handle {
        <#store as #construction>::fulltext(&self.#engine, slot)
      }
    }

    impl #mount for #name {
      /// The factory's own handle, projected — the mount seam adds no third opinion about what a
      /// corpus of this store is.
      type Handle = <Self as #construction>::Handle;

      /// ONE CORPUS, by the election's durable name — the factory above, under the name a WIRE
      /// DOOR can spell.
      ///
      /// The seam exists because a door cannot name the factory: which of the two store faces this
      /// resource wears is decided by its MODE, and an election that points here is expanded
      /// without that knowledge. So the mode is spent HERE, where the declaration knows it, and
      /// every door downstream names one trait.
      #[inline]
      fn corpus(&self, slot: impl ::core::convert::Into<#bytes>) -> Self::Handle {
        <Self as #construction>::fulltext(self, slot)
      }

      /// The manager, borrowed — what a `Connected` against any corpus of this mount carries.
      #[inline]
      fn connection(&self) -> &<Self::Handle as #base>::Connection {
        &self.#engine
      }
    }

    impl #base for #name {
      type Options = <#handle as #base>::Options;
      type SearchOptions = <#handle as #base>::SearchOptions;
      type Error = <#handle as #base>::Error;
      type Score = <#handle as #base>::Score;
      type Address = <#handle as #base>::Address;
      type Connection = <#handle as #base>::Connection;
      type WriteBuffer = <#handle as #base>::WriteBuffer;
      type ReadBuffer = <#handle as #base>::ReadBuffer;

      #[inline]
      fn buffer() -> Self::WriteBuffer {
        <#handle as #base>::buffer()
      }

      #[inline]
      fn finalize(buf: Self::WriteBuffer) -> Self::Address {
        <#handle as #base>::finalize(buf)
      }

      #[inline]
      fn open(address: Self::Address) -> Self::ReadBuffer {
        <#handle as #base>::open(address)
      }
    }

  }
}