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
//! The STANDALONE family's model: a hand-written struct's Filter, Comparison and OrderBy faces,
//! composed from the same [`unit`](crate::unit) walks `#[ingraph::record(…)]` composes.
//!
//! # What the bare doors add to the units: NOTHING
//!
//! That is the ruling and it is also the code. Each `emit_*` below assembles rows and calls a unit;
//! there is no second emitter and no standalone-only shape. What the GRAMMAR WORD adds — the storage
//! lowerings, the wire faces, the per-database order terms, the row equations — is exactly what a
//! hand-written struct has no table to render against, so a bare door adds none of it.
//!
//! # A field with NO interpretation word takes its type's own reading
//!
//! The record MANDATES the word on a stored or exposed field, and the reason is storage: a column's
//! physical layout is decided by the kind, so a record that let the kind be inferred would let a
//! table shape be inferred. A bare face has no table. So a field writing no word here resolves
//! through `DefaultMarker` — the same inference the marker layer already answers for every field
//! whose type has one sensible reading — and a field writing one spends it exactly as the record
//! does.
//!
//! That is a WIDENING and not a reduced dialect: every word the record takes is taken here, and one
//! declaration the record refuses is accepted. Stated because it is the one place the two doors'
//! grammars differ, and the difference is the storage the word was mandated for.
//!
//! # The DATABASE set is the container's, and it decides how many comparisons there are
//!
//! A record's comparison is per database because its fields are STORAGE-typed and the storage type
//! is per database. A standalone struct that names no database has one type to be compared in, so it
//! gets ONE comparison, generic in its dialect — the same shape a record's is, at a parameter.
//! Naming databases (`persist(sqlite, postgres)`) gets one per database, each named by the same two
//! functions a record's is: `default_comparison_name(default_row_name(subject, kind))`.
//!
//! # A crossing that NAMES the projection is unwritable at a generic `DB`, and that is measured
//! # rather than chosen
//!
//! `TryFromFilter<F> for <S>Comparison<DB>` written with `<F as ToDatabaseComparison<V,
//! Db>>::Comparison` as its `where` clause's self type is unwritable at a generic `DB`: the
//! projection there makes rustc resolve it through the impl that DEFINES it, so the clause demands
//! whatever that impl demands of `Db` — including `Db::Builder<'q> == SqlConjunction<'q, Db>`, which
//! no `Db` bound can supply. The interface's own crossing records the same wall and answers it the
//! same way: name a backend.
//!
//! **The self type in that sentence is the WHERE CLAUSE's, not the impl's.** The impl head names the
//! minted comparison already, at both doors — writing the concrete name instead of the projection is
//! the spelling in use rather than one left untried, and the wall survives it because the rows the
//! BODY owes have the projection as their self type. Measured at the seventh spelling on 2026-08-22;
//! [`FieldsModel`](crate::fields::FieldsModel)'s `pair` carries the compiler output and the control
//! that isolates the seam to the comparison's MEMBER type.
//!
//! # The wall has a door, and now NEITHER arm stops at it
//!
//! *Unwritable* above is true of a crossing that NAMES the projection, and that is a fact about a
//! spelling rather than about the dialect. `ToCrossedComparison` reaches the same two rows through
//! METHODS, which return the projection instead of naming it in a bound, and the fragment tier writes
//! its crossing at a parameter over that — one impl for every backend, its `where` clause one row per
//! member with the FILTER as each self type. [`StandaloneModel::generic_pair`] is that same shape,
//! read onto a declaration's own columns — BARE or NAMED, the same method either way: where the
//! container names a filter seat with `#[ingraph(filter = "…")]`, the comparison gets
//! `TryFromFilter<F> for <S>Comparison<DB>` and the empty-predicate `Default` beside it, one impl for
//! every backend, discharged wherever a caller names a concrete one.
//!
//! **Gated on the SEAT rather than on the wall, and rather than on bareness.** This door's
//! value-level crossing is a refinement of the map row [`StandaloneModel::crossing`] emits, a
//! refinement needs something to refine, and a declaration naming no hook has written a refinement of
//! nothing — the reason the FIELD-level refusal already gives, unmoved and unworded-differently by
//! this. So the pair rides the same gate the map row always has: a hook, or neither half — asked once
//! and answered the same way whether or not the declaration also named a database, because the wall
//! this door answers was never about the store words either.
//!
//! **The NAMED loop's own absence WAS scope rather than the wall, and this is the knife that closes
//! it.** A named database only ever changed which STORED type a column crosses through here — the
//! comparison itself stays a parameter whether or not a database was named, so nothing about
//! *unwritable at a generic `DB`* ever distinguished the two arms; #358 measured the bare one and left
//! the named one flagged rather than measuring both at once, because measuring one shape at a time is
//! how a wall gets a door instead of a hole. [`StandaloneModel::emit_comparison`] now calls
//! [`StandaloneModel::generic_pair`] beside BOTH arms' own calls — the bare branch's `at = None` and
//! each named iteration's own `at = Some(…)` — never once touching
//! [`one_comparison`](StandaloneModel::one_comparison)'s own body, which is what keeps everything the
//! pair does not add byte for byte what it was, in both arms, by construction rather than by audit.
//!
//! **The per-database STORED-type override composes without a new reader.**
//! [`crossing_of`](StandaloneModel::crossing_of) already had to answer *what does this column store*,
//! because [`held`](StandaloneModel::held) and [`assumptions`](StandaloneModel::assumptions) ask it
//! for every comparison this door emits, named or not —
//! [`stored`](StandaloneModel::stored) is that answer, and it already reads the per-database override
//! where a named declaration wrote one. Threading the same `at` this door's other readers already
//! carry into `crossing_of` is the whole of what the named loop needed: the crossing's `V` becomes
//! the STORED type at that database exactly where the struct's own fields already are one, and
//! `ToCrossedComparison<V, Db>` asks nothing of `V` that ties it to the DOMAIN type. Measured at two
//! declarations that store the SAME column shape under two DIFFERENT types, crossing live at SQLite
//! — see `ingraph/tests/standalone_named_crossing.rs`. A `flatten` column asks
//! [`one_comparison`](StandaloneModel::one_comparison)'s own `Self::new` for one bound the plain
//! crossing does not supply; [`crossings`](StandaloneModel::crossings) states it beside the crossing
//! rather than instead of it, the same branch [`assumptions`](StandaloneModel::assumptions) already
//! carries, read here for the reason that one already established.
//!
//! **A finding the measurement surfaced, pre-existing and untouched by this knife.** The fixture
//! above is TWO declarations rather than one naming both databases, because one naming both does not
//! compile: [`crossing`](StandaloneModel::crossing) emits, for EVERY named database, `impl<DB>
//! ToDatabaseComparison<Subject, DB> for Hook { … }` — ONE HEAD, since neither the trait's own
//! arguments nor the self type mention the database NAME. Two named databases is two impls sharing
//! that head, and rustc's overlap check does not weigh `where` clauses when deciding two impls
//! conflict — `E0119`, on a struct that names two databases and a hook, regardless of whether either
//! comparison ever gains a value-level pair. [`crossing`] is byte-identical to `origin/main` here, so
//! this is not a fact about what this knife adds; it is a fact about the map row that already existed,
//! unmeasured until a compiled fixture finally named two databases and a hook at once. Reconciling it
//! — keying the map row on something the database name reaches, or refusing the combination by name
//! at the front end — is open, and is a knife of its own.

use quote::quote;

use crate::{
  model::{DatabaseKind, Marker},
  name::RustSafeName,
  unit,
};

#[cfg(test)]
mod tests;

/// A hand-written struct, as the three bare doors read it.
///
/// PLAIN, for [`RecordModel`](crate::model::RecordModel)'s reason — public fields, no constructor,
/// no validation. What is checked is checked at the FRONT END, where the tokens an author wrote are
/// still in hand and a refusal can point at one.
pub struct StandaloneModel {
  /// The declaration's own visibility, which every emitted item takes.
  pub vis: syn::Visibility,
  /// The struct the faces are OF — the doc sentences' noun, and the type a crossing compares.
  pub subject: syn::Ident,
  /// The `ingraph` root the expansion spells its shelf through.
  pub krate: syn::Path,
  /// What the FILTER face is called.
  pub filter: RustSafeName,
  /// What the ORDER-BY face is called.
  pub order_by: RustSafeName,
  /// What ONE comparison is called before the per-database suffix is applied — the base a record
  /// spells as its row's name.
  pub comparison: RustSafeName,
  /// The databases the comparison is emitted for. EMPTY is one comparison generic in its dialect.
  pub databases: Vec<DatabaseKind>,
  /// The columns, in declared order.
  pub columns: Vec<StandaloneColumn>,
  /// `#[ingraph(filter = "path")]` — the filter seat a crossing is emitted FROM.
  pub hook: Option<syn::Path>,
}

/// One field of the struct, as the three doors read it.
pub struct StandaloneColumn {
  /// The Rust member — layer 1, the field's own name, which no word moves.
  pub member: syn::Ident,
  /// What a doc sentence calls this column: the common `rename = "…"` where one is
  /// written, the member otherwise.
  pub name: RustSafeName,
  /// The field's declared type — what a comparison stores where no database overrides it, and what
  /// a filter is projected from where no wire type is written.
  pub domain: syn::Type,
  /// `graphql(type = "…")` — the ONE wire form, which is what the FILTER is projected from.
  ///
  /// The filter faces the client, so it is built from the type a client writes. The comparison
  /// faces the database, so it is built from the domain type and stored at the database's own.
  pub wire: Option<syn::Type>,
  /// The interpretation word this field's type is read under, if the declaration wrote one.
  pub marker: Option<Marker>,
  /// One entry per database this struct names, in the model's own database order.
  pub stored: Vec<StandaloneStored>,
}

/// How ONE database stores one column.
pub struct StandaloneStored {
  /// `type = "…"` — what this database stores, when it is not the domain type.
  pub ty: Option<syn::Type>,
  /// `flatten` — the comparison occupies more than one column, so the crossing is the REFINED one.
  pub flatten: bool,
}

impl StandaloneModel {
  /// The shelf path one framework item is spelled through.
  fn framework(&self, module: &[&str], item: &str) -> proc_macro2::TokenStream {
    crate::emit::framework(&self.krate, module, item)
  }

  /// The doc-sentence noun. A LINK, because the struct the derive is written on is in scope
  /// wherever the expansion lands — which is the one thing a bare door knows that a shared unit
  /// cannot.
  fn subject(&self) -> String {
    format!("[`{}`]", self.subject)
  }

  /// The FILTER face: the where-struct and its builders, over the WIRE form of every column.
  pub fn emit_filter(&self) -> proc_macro2::TokenStream {
    let rows: Vec<unit::FilterColumn> = self
      .columns
      .iter()
      .map(|column| unit::FilterColumn {
        // A STANDALONE declaration's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        member: column.member.clone(),
        name: format!("`{}` column", column.name),
        filter: crate::emit::filter_of(
          &self.krate,
          column.wire.as_ref().unwrap_or(&column.domain),
          column.marker.as_ref(),
          crate::emit::FilterFace::Column,
        ),
      })
      .collect();
    let header = unit::UnitHeader {
      vis: &self.vis,
      name: self.filter.safe().clone(),
      subject: self.subject(),
      note: None,
    };
    let (declaration, builders) = unit::filter(&header, &rows);
    quote! { #declaration #builders }
  }

  /// The ORDER-BY face: the term enum, its direction, its identity and its subject path.
  ///
  /// All four, where a record gates two of them. A record's `identity` rides the PAGE's own law —
  /// it needs a stored id and a SQL clause machine — and neither is a fact a hand-written struct
  /// has: what is being ordered here is the struct's own fields, and every term of it names one.
  pub fn emit_order_by(&self) -> proc_macro2::TokenStream {
    let rows = self.order_rows();
    let direction_ty = self.framework(&["graphql"], "OrderDirection");
    let term_name = self.framework(&["cursor"], "TermName");
    let to_subject_path = self.framework(&["graphql"], "ToSubjectPath");
    let subject_path = self.framework(&["graphql"], "SubjectPath");
    let name = self.order_by.safe();
    let header = unit::UnitHeader {
      vis: &self.vis,
      name: name.clone(),
      subject: self.subject(),
      note: None,
    };
    let (declaration, direction) = unit::order_by(&header, &direction_ty, &rows);
    let identity = unit::order_identity(&self.vis, &term_name, &rows);
    let subject =
      unit::order_subject_path(name, &to_subject_path, &subject_path, &term_name, &rows);
    quote! {
      #declaration

      impl #name {
        #direction
        #identity
      }

      #subject
    }
  }

  /// The ORDER-BY rows — one per column, in declared order.
  fn order_rows(&self) -> Vec<unit::OrderColumn> {
    self
      .columns
      .iter()
      .map(|column| unit::OrderColumn::of(&column.member, format!("`{}` column", column.name)))
      .collect()
  }

  /// The COMPARISON face: one per named database, or ONE generic in its dialect where none is
  /// named.
  ///
  /// # BOTH branches gain the value-level pair, through the SAME call
  ///
  /// [`generic_pair`](Self::generic_pair) is called from HERE, beside [`one_comparison`]'s own call
  /// in both branches and never inside it — so [`one_comparison`] itself runs the exact code it
  /// always has, unreached by the new method's own body regardless of which branch a declaration
  /// takes. That is what makes byte-identity a fact about which LINES a declaration reaches rather
  /// than something asserted about a shared body: nothing this knife added is inside
  /// [`one_comparison`], so everything IT emits — the struct, the accessors, the lowering, the map
  /// row — stays what it was, in both branches, and the only new tokens either branch can gain are
  /// [`generic_pair`]'s own, called with that branch's own `at`.
  ///
  /// [`one_comparison`]: Self::one_comparison
  /// [`generic_pair`]: Self::generic_pair
  pub fn emit_comparison(&self) -> proc_macro2::TokenStream {
    if self.databases.is_empty() {
      let name = RustSafeName::from_ident(&crate::model::default_comparison_name(
        self.comparison.safe(),
      ));
      let comparison = self.one_comparison(&name, None);
      let pair = self.generic_pair(&name, None);
      return quote! { #comparison #pair };
    }
    let each = self.databases.iter().enumerate().map(|(at, kind)| {
      let row = crate::model::default_row_name(self.comparison.safe(), *kind);
      let name = RustSafeName::from_ident(&crate::model::default_comparison_name(&row));
      let comparison = self.one_comparison(&name, Some(at));
      let pair = self.generic_pair(&name, Some(at));
      quote! { #comparison #pair }
    });
    quote! { #(#each)* }
  }

  /// ONE comparison type, at a database index or at none.
  fn one_comparison(&self, name: &RustSafeName, at: Option<usize>) -> proc_macro2::TokenStream {
    let db = crate::emit::parameter("DB");
    let crossings = self.assumptions(&db, at);
    let rows: Vec<unit::ComparisonColumn> = self
      .columns
      .iter()
      .map(|column| unit::ComparisonColumn {
        // A STANDALONE declaration's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        member: column.member.clone(),
        name: format!("`{}` column", column.name),
        held: self.held(column, &db, at),
      })
      .collect();
    let header = unit::UnitHeader {
      vis: &self.vis,
      name: name.safe().clone(),
      subject: self.subject(),
      note: None,
    };
    let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
    // The LOWERING rides with the struct, exactly as a record's does: the type IS a comparison
    // whether or not anything has crossed into it yet, and the map row below cannot keep its item
    // bound — `type Comparison: ComplexComparison<Db>` — without it.
    let seats = unit::LoweringSeats {
      backend: self.framework(&["comparison"], "Backend"),
      complex: self.framework(&["comparison"], "ComplexComparison"),
      frame: self.framework(&["comparison"], "Frame"),
      at: self.framework(&["comparison"], "At"),
      field_name: self.framework(&["field"], "FieldName"),
    };
    let lowered: Vec<unit::LoweringColumn> = self
      .columns
      .iter()
      .map(|column| unit::LoweringColumn {
        // A STANDALONE declaration's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        member: column.member.clone(),
        rendered: column.name.to_string(),
        flatten: at
          .and_then(|at| column.stored.get(at))
          .is_some_and(|stored| stored.flatten),
        through: None,
      })
      .collect();
    let lowering = unit::comparison_lowering(name.safe(), &db, &crossings, &seats, &lowered);
    let crossing = self.crossing(name, &db, at);
    quote! { #declaration #methods #lowering #crossing }
  }

  /// What one column's field is held at, in one database.
  fn held(
    &self,
    column: &StandaloneColumn,
    db: &syn::Ident,
    at: Option<usize>,
  ) -> proc_macro2::TokenStream {
    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
    let filter = crate::emit::filter_of(
      &self.krate,
      &column.domain,
      column.marker.as_ref(),
      crate::emit::FilterFace::Column,
    );
    let stored = self.stored(column, at);
    quote!(<#filter as #to_comparison<#stored, #db>>::Comparison)
  }

  /// What one database stores one column as — its own `type = "…"`, or the domain type.
  fn stored(&self, column: &StandaloneColumn, at: Option<usize>) -> proc_macro2::TokenStream {
    let domain = &column.domain;
    at.and_then(|at| column.stored.get(at))
      .and_then(|stored| stored.ty.as_ref())
      .map_or_else(|| quote!(#domain), |ty| quote!(#ty))
  }

  /// What a comparison over these columns ASSUMES — the record's own list, at one database.
  ///
  /// `Db: Backend` leads because it is not elaborated from the rest: a `where F:
  /// ToDatabaseComparison<V, Db>` names a trait whose own parameter is bounded that way, so the
  /// predicate is owed at every caller that writes the crossing, and it is a claim about the
  /// DATABASE rather than about any column.
  ///
  /// A `flatten` column states the REFINED crossing and only it: `ToFlattenedComparison<V, Db>` carries
  /// the plain crossing as its SUPERTRAIT, so a marked column states ONE bound and the other arrives
  /// by elaboration.
  fn assumptions(&self, db: &syn::Ident, at: Option<usize>) -> proc_macro2::TokenStream {
    let backend = self.framework(&["comparison"], "Backend");
    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
    let to_flattened = self.framework(&["comparison"], "ToFlattenedComparison");
    let crossings = self.columns.iter().map(|column| {
      let filter = crate::emit::filter_of(
        &self.krate,
        &column.domain,
        column.marker.as_ref(),
        crate::emit::FilterFace::Column,
      );
      let stored = self.stored(column, at);
      let flatten = at
        .and_then(|at| column.stored.get(at))
        .is_some_and(|stored| stored.flatten);
      let crossing = if flatten {
        &to_flattened
      } else {
        &to_comparison
      };
      quote!(#filter: #crossing<#stored, #db>,)
    });
    quote! {
      #db: #backend,
      #(#crossings)*
    }
  }

  /// The CROSSING the conversion hook names: the map row saying which comparison this filter seat
  /// crosses into.
  ///
  /// The TYPE-LEVEL half. Its value-level twin — `TryFromFilter`, which builds the comparison operand
  /// by operand — used to be unwritable at a generic dialect for the reason [`generic_pair`]'s doc
  /// records, and a standalone comparison's dialect is a parameter even where a database is named:
  /// the database decides the STORED types, not the driver the query is built for.
  /// `ToCrossedComparison` opened a door past that wall, and [`generic_pair`] walks BOTH arms through
  /// it now — the bare one at `at = None`, a named one at this same method's own `at`. So the hook
  /// delivers the map always, and the operand-level crossing arrives through the kinds' own rows,
  /// through [`generic_pair`] either way — called beside this method's own emission rather than
  /// written here, left to a caller that names a concrete backend the way an interface's own crossing
  /// is.
  ///
  /// [`generic_pair`]: Self::generic_pair
  fn crossing(
    &self,
    name: &RustSafeName,
    db: &syn::Ident,
    at: Option<usize>,
  ) -> proc_macro2::TokenStream {
    let Some(hook) = self.hook.as_ref() else {
      return proc_macro2::TokenStream::new();
    };
    let subject = &self.subject;
    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
    let crossings = self.assumptions(db, at);
    let name = name.safe();
    quote! {
      #[automatically_derived]
      impl<#db> #to_comparison<#subject, #db> for #hook
      where
        #crossings
      {
        type Comparison = #name<#db>;
      }
    }
  }

  /// One column's (storage type, filter slot) pair, spelled the way [`held`](Self::held) and
  /// [`assumptions`](Self::assumptions) spell it inline — [`FieldsModel::crossing_of`]'s reader,
  /// again, for the reason that one is: a slot resolved twice is a slot two answers can disagree
  /// about. The STORED half is [`stored`](Self::stored)'s own answer, exactly as [`held`] and
  /// [`assumptions`] already read it: a bare declaration's storage type is always its DOMAIN, `at`
  /// having no per-database entry to read without a named database, and a named declaration's is
  /// whichever override — or lack of one — that database wrote. Two readers of one fact would be two
  /// answers that could disagree; this is the one reader, called wherever the fact is needed.
  ///
  /// [`FieldsModel::crossing_of`]: crate::fields::FieldsModel::crossing_of
  /// [`held`]: Self::held
  /// [`assumptions`]: Self::assumptions
  fn crossing_of(
    &self,
    column: &StandaloneColumn,
    at: Option<usize>,
  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    (
      self.stored(column, at),
      crate::emit::filter_of(
        &self.krate,
        &column.domain,
        column.marker.as_ref(),
        crate::emit::FilterFace::Column,
      ),
    )
  }

  /// What a crossing over these columns ASSUMES, at no named database or at one —
  /// [`FieldsModel::crossings`]'s clause, read off this door's own column list at whichever `at`
  /// [`generic_pair`](Self::generic_pair) is itself called with.
  ///
  /// The union of the columns' rows, deduplicated by spelling — two columns of one type and one
  /// `flatten`-ness ask one question, and a `where` clause repeating it says nothing more. `DB:
  /// Backend` leads for [`assumptions`](Self::assumptions)'s reason; the map row that method states
  /// arrives here by ELABORATION off `ToCrossedComparison`'s supertrait, so a non-`flatten` column's
  /// row here is not [`assumptions`]'s plus something — it is that one, refined, and `Self::new`'s
  /// own weaker clause for that column is discharged by the same elaboration.
  ///
  /// # A `flatten` column states one row more
  ///
  /// [`assumptions`] states `ToFlattenedComparison<V, Db>` rather than `ToDatabaseComparison<V, Db>`
  /// for a `flatten` column, and that trait is a SIBLING refinement of the plain map — not a
  /// supertrait of `ToCrossedComparison` and not implied by it — so the elaboration the paragraph
  /// above leans on does not reach a `flatten` column's own row of [`assumptions`]'s clause. This
  /// method states that row explicitly, beside the crossing rather than instead of it: the crossing is
  /// what `cross`/`empty` need, the flattened row is what the `Self::new` call
  /// [`generic_pair`](Self::generic_pair) makes still needs, and a column that is not `flatten` at
  /// this `at` asks for neither the second row nor the first's supertrait restated — same as before
  /// this knife, for every column a named database has not marked.
  ///
  /// [`FieldsModel::crossings`]: crate::fields::FieldsModel::crossings
  /// [`assumptions`]: Self::assumptions
  fn crossings(&self, db: &syn::Ident, at: Option<usize>) -> proc_macro2::TokenStream {
    let backend = self.framework(&["comparison"], "Backend");
    let to_crossed = self.framework(&["comparison"], "ToCrossedComparison");
    let to_flattened = self.framework(&["comparison"], "ToFlattenedComparison");
    let mut seen: Vec<String> = Vec::new();
    let mut rows = proc_macro2::TokenStream::new();
    for column in &self.columns {
      let (stored, slot) = self.crossing_of(column, at);
      let flatten = at
        .and_then(|at| column.stored.get(at))
        .is_some_and(|stored| stored.flatten);
      let mut row = quote!(#slot: #to_crossed<#stored, #db>,);
      if flatten {
        row.extend(quote!(#slot: #to_flattened<#stored, #db>,));
      }
      let spelling = row.to_string();
      if seen.iter().any(|kept| kept == &spelling) {
        continue;
      }
      seen.push(spelling);
      rows.extend(row);
    }
    quote! {
      #db: #backend,
      #rows
    }
  }

  /// **THE VALUE-LEVEL CROSSING AND THE EMPTY PREDICATE, AT A PARAMETER** — this door's own
  /// `TryFromFilter<F> for <S>Comparison<DB>` and the `Default` beside it, both through
  /// `ToCrossedComparison`, one impl for every backend — at no named database, or at the ONE this
  /// call's own `at` selects.
  ///
  /// [`FieldsModel::generic_pair`]'s arrangement, read onto ONE struct's columns rather than a
  /// fragment's fields — no `#[cfg]` walk, because a standalone declaration's fields carry no
  /// condition seat at all, and the fields tier's gate is empty tokens wherever a member wrote none.
  ///
  /// # Gated on the HOOK, not on bareness
  ///
  /// The map row [`crossing`](Self::crossing) names is `F` = the hook — the filter seat the container
  /// declared, not this door's own minted [`emit_filter`](Self::emit_filter) output, which a
  /// declaration may point the hook AT but which this method never assumes. Without a hook there is
  /// no `F` for `TryFromFilter<F>` to be OVER, and `Default` stays with it rather than shipping alone:
  /// the two are one PAIR, and a pair with one half orphaned is not what either door emits. A
  /// declaration naming no hook gets neither half, exactly as it gets no map row — the existing
  /// refusal at the FIELD tier (a conversion word with no container hook) already covers the only
  /// place this absence is reachable by name, and its wording does not change: nothing here mints a
  /// NEW way to reach a comparison's fields, only a new thing a hook, once written, buys — whether or
  /// not the declaration also names a database.
  ///
  /// # Called beside [`one_comparison`], never inside it
  ///
  /// See [`emit_comparison`](Self::emit_comparison)'s own doc for why: [`one_comparison`] must run the
  /// exact code it always has, and the surest way to keep it byte-identical is for this method to be
  /// unreachable from it rather than reachable-and-declining — true of the bare branch as it always
  /// was, and now equally true beside each named iteration: a named declaration's comparison stays a
  /// parameter too, see [`crossing`](Self::crossing)'s doc, so nothing about the WALL ever argued for
  /// the boundary sitting where #358 left it; only scope did, and this method's own second parameter
  /// is what closes that scope.
  ///
  /// # The STORED-type override, at a parameter
  ///
  /// `at` reaches [`crossings`](Self::crossings) and [`crossing_of`](Self::crossing_of) exactly as it
  /// already reaches [`assumptions`](Self::assumptions) and [`held`](Self::held): the crossing's `V`
  /// is [`stored`](Self::stored)'s own answer, so a named database's own override is what this pair
  /// crosses THROUGH, not the domain type underneath it, and `DB` stays a parameter regardless of
  /// which database named the override — naming a database here still only ever pinned the STORED
  /// type, never the driver the query renders for.
  ///
  /// [`one_comparison`]: Self::one_comparison
  /// [`FieldsModel::generic_pair`]: crate::fields::FieldsModel::generic_pair
  fn generic_pair(&self, name: &RustSafeName, at: Option<usize>) -> proc_macro2::TokenStream {
    let Some(hook) = self.hook.as_ref() else {
      return proc_macro2::TokenStream::new();
    };
    let db = crate::emit::parameter("DB");
    let comparison = name.safe();
    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
    let to_crossed = self.framework(&["comparison"], "ToCrossedComparison");
    let boxed = crate::model::boxed_error();
    let clause = self.crossings(&db, at);
    let doc = crate::emit::leading(&format!(
      "Cross a wire filter into the predicate this {subject}'s comparison compares by — every \
       column through its own crossing, and the empty comparison wherever the client asked \
       nothing.\n\nONE impl for every backend: this {subject}'s comparison is generic in its dialect \
       even where the declaration names a database, so its crossing carries each column's row rather \
       than discharging it.\n\n# Errors\nWhatever a column's crossing into its stored form refused \
       with.",
      subject = self.subject(),
    ));
    let members: Vec<proc_macro2::TokenStream> = self
      .columns
      .iter()
      .map(|column| {
        let member = &column.member;
        quote!(#member,)
      })
      .collect();
    let empty: Vec<proc_macro2::TokenStream> = self
      .columns
      .iter()
      .map(|column| {
        let (stored, slot) = self.crossing_of(column, at);
        quote!(<#slot as #to_crossed<#stored, #db>>::empty(),)
      })
      .collect();
    let legs = self.columns.iter().map(|column| {
      let member = &column.member;
      let (stored, slot) = self.crossing_of(column, at);
      quote! {
        let #member = match __ingraph_filter.#member {
          ::core::option::Option::Some(__ingraph_held) => {
            match <#slot as #to_crossed<#stored, #db>>::cross(__ingraph_held) {
              ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
              ::core::result::Result::Err(__ingraph_why) => {
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            }
          }
          // The client asked nothing about this column, which is not the same as asking for
          // nothing to match: the empty comparison renders no conjunct.
          ::core::option::Option::None => <#slot as #to_crossed<#stored, #db>>::empty(),
        };
      }
    });
    quote! {
      // `Self::new` and never a struct literal: the constructor is the comparison's only
      // construction path, and a second one here would be a second place the column list lives.
      #[automatically_derived]
      impl<#db> ::core::default::Default for #comparison<#db>
      where
        #clause
      {
        #[inline]
        fn default() -> Self {
          Self::new(#(#empty)*)
        }
      }

      #[automatically_derived]
      impl<#db> #try_from_filter<#hook> for #comparison<#db>
      where
        #clause
      {
        type Error = #boxed;

        #[doc = #doc]
        fn try_from_filter(
          __ingraph_filter: #hook,
        ) -> ::core::result::Result<Self, Self::Error> {
          #(#legs)*
          ::core::result::Result::Ok(Self::new(#(#members)*))
        }
      }
    }
  }
}