Skip to main content

ingraph_codegen/
standalone.rs

1//! The STANDALONE family's model: a hand-written struct's Filter, Comparison and OrderBy faces,
2//! composed from the same [`unit`](crate::unit) walks `#[ingraph::record(…)]` composes.
3//!
4//! # What the bare doors add to the units: NOTHING
5//!
6//! That is the ruling and it is also the code. Each `emit_*` below assembles rows and calls a unit;
7//! there is no second emitter and no standalone-only shape. What the GRAMMAR WORD adds — the storage
8//! lowerings, the wire faces, the per-database order terms, the row equations — is exactly what a
9//! hand-written struct has no table to render against, so a bare door adds none of it.
10//!
11//! # A field with NO interpretation word takes its type's own reading
12//!
13//! The record MANDATES the word on a stored or exposed field, and the reason is storage: a column's
14//! physical layout is decided by the kind, so a record that let the kind be inferred would let a
15//! table shape be inferred. A bare face has no table. So a field writing no word here resolves
16//! through `DefaultMarker` — the same inference the marker layer already answers for every field
17//! whose type has one sensible reading — and a field writing one spends it exactly as the record
18//! does.
19//!
20//! That is a WIDENING and not a reduced dialect: every word the record takes is taken here, and one
21//! declaration the record refuses is accepted. Stated because it is the one place the two doors'
22//! grammars differ, and the difference is the storage the word was mandated for.
23//!
24//! # The DATABASE set is the container's, and it decides how many comparisons there are
25//!
26//! A record's comparison is per database because its fields are STORAGE-typed and the storage type
27//! is per database. A standalone struct that names no database has one type to be compared in, so it
28//! gets ONE comparison, generic in its dialect — the same shape a record's is, at a parameter.
29//! Naming databases (`persist(sqlite, postgres)`) gets one per database, each named by the same two
30//! functions a record's is: `default_comparison_name(default_row_name(subject, kind))`.
31//!
32//! # A crossing that NAMES the projection is unwritable at a generic `DB`, and that is measured
33//! # rather than chosen
34//!
35//! `TryFromFilter<F> for <S>Comparison<DB>` written with `<F as ToDatabaseComparison<V,
36//! Db>>::Comparison` as its `where` clause's self type is unwritable at a generic `DB`: the
37//! projection there makes rustc resolve it through the impl that DEFINES it, so the clause demands
38//! whatever that impl demands of `Db` — including `Db::Builder<'q> == SqlConjunction<'q, Db>`, which
39//! no `Db` bound can supply. The interface's own crossing records the same wall and answers it the
40//! same way: name a backend.
41//!
42//! **The self type in that sentence is the WHERE CLAUSE's, not the impl's.** The impl head names the
43//! minted comparison already, at both doors — writing the concrete name instead of the projection is
44//! the spelling in use rather than one left untried, and the wall survives it because the rows the
45//! BODY owes have the projection as their self type. Measured at the seventh spelling on 2026-08-22;
46//! [`FieldsModel`](crate::fields::FieldsModel)'s `pair` carries the compiler output and the control
47//! that isolates the seam to the comparison's MEMBER type.
48//!
49//! # The wall has a door, and now NEITHER arm stops at it
50//!
51//! *Unwritable* above is true of a crossing that NAMES the projection, and that is a fact about a
52//! spelling rather than about the dialect. `ToCrossedComparison` reaches the same two rows through
53//! METHODS, which return the projection instead of naming it in a bound, and the fragment tier writes
54//! its crossing at a parameter over that — one impl for every backend, its `where` clause one row per
55//! member with the FILTER as each self type. [`StandaloneModel::generic_pair`] is that same shape,
56//! read onto a declaration's own columns — BARE or NAMED, the same method either way: where the
57//! container names a filter seat with `#[ingraph(filter = "…")]`, the comparison gets
58//! `TryFromFilter<F> for <S>Comparison<DB>` and the empty-predicate `Default` beside it, one impl for
59//! every backend, discharged wherever a caller names a concrete one.
60//!
61//! **Gated on the SEAT rather than on the wall, and rather than on bareness.** This door's
62//! value-level crossing is a refinement of the map row [`StandaloneModel::crossing`] emits, a
63//! refinement needs something to refine, and a declaration naming no hook has written a refinement of
64//! nothing — the reason the FIELD-level refusal already gives, unmoved and unworded-differently by
65//! this. So the pair rides the same gate the map row always has: a hook, or neither half — asked once
66//! and answered the same way whether or not the declaration also named a database, because the wall
67//! this door answers was never about the store words either.
68//!
69//! **The NAMED loop's own absence WAS scope rather than the wall, and this is the knife that closes
70//! it.** A named database only ever changed which STORED type a column crosses through here — the
71//! comparison itself stays a parameter whether or not a database was named, so nothing about
72//! *unwritable at a generic `DB`* ever distinguished the two arms; #358 measured the bare one and left
73//! the named one flagged rather than measuring both at once, because measuring one shape at a time is
74//! how a wall gets a door instead of a hole. [`StandaloneModel::emit_comparison`] now calls
75//! [`StandaloneModel::generic_pair`] beside BOTH arms' own calls — the bare branch's `at = None` and
76//! each named iteration's own `at = Some(…)` — never once touching
77//! [`one_comparison`](StandaloneModel::one_comparison)'s own body, which is what keeps everything the
78//! pair does not add byte for byte what it was, in both arms, by construction rather than by audit.
79//!
80//! **The per-database STORED-type override composes without a new reader.**
81//! [`crossing_of`](StandaloneModel::crossing_of) already had to answer *what does this column store*,
82//! because [`held`](StandaloneModel::held) and [`assumptions`](StandaloneModel::assumptions) ask it
83//! for every comparison this door emits, named or not —
84//! [`stored`](StandaloneModel::stored) is that answer, and it already reads the per-database override
85//! where a named declaration wrote one. Threading the same `at` this door's other readers already
86//! carry into `crossing_of` is the whole of what the named loop needed: the crossing's `V` becomes
87//! the STORED type at that database exactly where the struct's own fields already are one, and
88//! `ToCrossedComparison<V, Db>` asks nothing of `V` that ties it to the DOMAIN type. Measured at two
89//! declarations that store the SAME column shape under two DIFFERENT types, crossing live at SQLite
90//! — see `ingraph/tests/standalone_named_crossing.rs`. A `flatten` column asks
91//! [`one_comparison`](StandaloneModel::one_comparison)'s own `Self::new` for one bound the plain
92//! crossing does not supply; [`crossings`](StandaloneModel::crossings) states it beside the crossing
93//! rather than instead of it, the same branch [`assumptions`](StandaloneModel::assumptions) already
94//! carries, read here for the reason that one already established.
95//!
96//! **A finding the measurement surfaced, pre-existing and untouched by this knife.** The fixture
97//! above is TWO declarations rather than one naming both databases, because one naming both does not
98//! compile: [`crossing`](StandaloneModel::crossing) emits, for EVERY named database, `impl<DB>
99//! ToDatabaseComparison<Subject, DB> for Hook { … }` — ONE HEAD, since neither the trait's own
100//! arguments nor the self type mention the database NAME. Two named databases is two impls sharing
101//! that head, and rustc's overlap check does not weigh `where` clauses when deciding two impls
102//! conflict — `E0119`, on a struct that names two databases and a hook, regardless of whether either
103//! comparison ever gains a value-level pair. [`crossing`] is byte-identical to `origin/main` here, so
104//! this is not a fact about what this knife adds; it is a fact about the map row that already existed,
105//! unmeasured until a compiled fixture finally named two databases and a hook at once. Reconciling it
106//! — keying the map row on something the database name reaches, or refusing the combination by name
107//! at the front end — is open, and is a knife of its own.
108
109use quote::quote;
110
111use crate::{
112  model::{DatabaseKind, Marker},
113  name::RustSafeName,
114  unit,
115};
116
117#[cfg(test)]
118mod tests;
119
120/// A hand-written struct, as the three bare doors read it.
121///
122/// PLAIN, for [`RecordModel`](crate::model::RecordModel)'s reason — public fields, no constructor,
123/// no validation. What is checked is checked at the FRONT END, where the tokens an author wrote are
124/// still in hand and a refusal can point at one.
125pub struct StandaloneModel {
126  /// The declaration's own visibility, which every emitted item takes.
127  pub vis: syn::Visibility,
128  /// The struct the faces are OF — the doc sentences' noun, and the type a crossing compares.
129  pub subject: syn::Ident,
130  /// The `ingraph` root the expansion spells its shelf through.
131  pub krate: syn::Path,
132  /// What the FILTER face is called.
133  pub filter: RustSafeName,
134  /// What the ORDER-BY face is called.
135  pub order_by: RustSafeName,
136  /// What ONE comparison is called before the per-database suffix is applied — the base a record
137  /// spells as its row's name.
138  pub comparison: RustSafeName,
139  /// The databases the comparison is emitted for. EMPTY is one comparison generic in its dialect.
140  pub databases: Vec<DatabaseKind>,
141  /// The columns, in declared order.
142  pub columns: Vec<StandaloneColumn>,
143  /// `#[ingraph(filter = "path")]` — the filter seat a crossing is emitted FROM.
144  pub hook: Option<syn::Path>,
145}
146
147/// One field of the struct, as the three doors read it.
148pub struct StandaloneColumn {
149  /// The Rust member — layer 1, the field's own name, which no word moves.
150  pub member: syn::Ident,
151  /// What a doc sentence calls this column: the common `rename = "…"` where one is
152  /// written, the member otherwise.
153  pub name: RustSafeName,
154  /// The field's declared type — what a comparison stores where no database overrides it, and what
155  /// a filter is projected from where no wire type is written.
156  pub domain: syn::Type,
157  /// `graphql(type = "…")` — the ONE wire form, which is what the FILTER is projected from.
158  ///
159  /// The filter faces the client, so it is built from the type a client writes. The comparison
160  /// faces the database, so it is built from the domain type and stored at the database's own.
161  pub wire: Option<syn::Type>,
162  /// The interpretation word this field's type is read under, if the declaration wrote one.
163  pub marker: Option<Marker>,
164  /// One entry per database this struct names, in the model's own database order.
165  pub stored: Vec<StandaloneStored>,
166}
167
168/// How ONE database stores one column.
169pub struct StandaloneStored {
170  /// `type = "…"` — what this database stores, when it is not the domain type.
171  pub ty: Option<syn::Type>,
172  /// `flatten` — the comparison occupies more than one column, so the crossing is the REFINED one.
173  pub flatten: bool,
174}
175
176impl StandaloneModel {
177  /// The shelf path one framework item is spelled through.
178  fn framework(&self, module: &[&str], item: &str) -> proc_macro2::TokenStream {
179    crate::emit::framework(&self.krate, module, item)
180  }
181
182  /// The doc-sentence noun. A LINK, because the struct the derive is written on is in scope
183  /// wherever the expansion lands — which is the one thing a bare door knows that a shared unit
184  /// cannot.
185  fn subject(&self) -> String {
186    format!("[`{}`]", self.subject)
187  }
188
189  /// The FILTER face: the where-struct and its builders, over the WIRE form of every column.
190  pub fn emit_filter(&self) -> proc_macro2::TokenStream {
191    let rows: Vec<unit::FilterColumn> = self
192      .columns
193      .iter()
194      .map(|column| unit::FilterColumn {
195        // A STANDALONE declaration's fields carry no condition seat — the `#[cfg]` word is the
196        // record family's, and this model has no field to hold one.
197        gate: proc_macro2::TokenStream::new(),
198        member: column.member.clone(),
199        name: format!("`{}` column", column.name),
200        filter: crate::emit::filter_of(
201          &self.krate,
202          column.wire.as_ref().unwrap_or(&column.domain),
203          column.marker.as_ref(),
204          crate::emit::FilterFace::Column,
205        ),
206      })
207      .collect();
208    let header = unit::UnitHeader {
209      vis: &self.vis,
210      name: self.filter.safe().clone(),
211      subject: self.subject(),
212      note: None,
213    };
214    let (declaration, builders) = unit::filter(&header, &rows);
215    quote! { #declaration #builders }
216  }
217
218  /// The ORDER-BY face: the term enum, its direction, its identity and its subject path.
219  ///
220  /// All four, where a record gates two of them. A record's `identity` rides the PAGE's own law —
221  /// it needs a stored id and a SQL clause machine — and neither is a fact a hand-written struct
222  /// has: what is being ordered here is the struct's own fields, and every term of it names one.
223  pub fn emit_order_by(&self) -> proc_macro2::TokenStream {
224    let rows = self.order_rows();
225    let direction_ty = self.framework(&["graphql"], "OrderDirection");
226    let term_name = self.framework(&["cursor"], "TermName");
227    let to_subject_path = self.framework(&["graphql"], "ToSubjectPath");
228    let subject_path = self.framework(&["graphql"], "SubjectPath");
229    let name = self.order_by.safe();
230    let header = unit::UnitHeader {
231      vis: &self.vis,
232      name: name.clone(),
233      subject: self.subject(),
234      note: None,
235    };
236    let (declaration, direction) = unit::order_by(&header, &direction_ty, &rows);
237    let identity = unit::order_identity(&self.vis, &term_name, &rows);
238    let subject =
239      unit::order_subject_path(name, &to_subject_path, &subject_path, &term_name, &rows);
240    quote! {
241      #declaration
242
243      impl #name {
244        #direction
245        #identity
246      }
247
248      #subject
249    }
250  }
251
252  /// The ORDER-BY rows — one per column, in declared order.
253  fn order_rows(&self) -> Vec<unit::OrderColumn> {
254    self
255      .columns
256      .iter()
257      .map(|column| unit::OrderColumn::of(&column.member, format!("`{}` column", column.name)))
258      .collect()
259  }
260
261  /// The COMPARISON face: one per named database, or ONE generic in its dialect where none is
262  /// named.
263  ///
264  /// # BOTH branches gain the value-level pair, through the SAME call
265  ///
266  /// [`generic_pair`](Self::generic_pair) is called from HERE, beside [`one_comparison`]'s own call
267  /// in both branches and never inside it — so [`one_comparison`] itself runs the exact code it
268  /// always has, unreached by the new method's own body regardless of which branch a declaration
269  /// takes. That is what makes byte-identity a fact about which LINES a declaration reaches rather
270  /// than something asserted about a shared body: nothing this knife added is inside
271  /// [`one_comparison`], so everything IT emits — the struct, the accessors, the lowering, the map
272  /// row — stays what it was, in both branches, and the only new tokens either branch can gain are
273  /// [`generic_pair`]'s own, called with that branch's own `at`.
274  ///
275  /// [`one_comparison`]: Self::one_comparison
276  /// [`generic_pair`]: Self::generic_pair
277  pub fn emit_comparison(&self) -> proc_macro2::TokenStream {
278    if self.databases.is_empty() {
279      let name = RustSafeName::from_ident(&crate::model::default_comparison_name(
280        self.comparison.safe(),
281      ));
282      let comparison = self.one_comparison(&name, None);
283      let pair = self.generic_pair(&name, None);
284      return quote! { #comparison #pair };
285    }
286    let each = self.databases.iter().enumerate().map(|(at, kind)| {
287      let row = crate::model::default_row_name(self.comparison.safe(), *kind);
288      let name = RustSafeName::from_ident(&crate::model::default_comparison_name(&row));
289      let comparison = self.one_comparison(&name, Some(at));
290      let pair = self.generic_pair(&name, Some(at));
291      quote! { #comparison #pair }
292    });
293    quote! { #(#each)* }
294  }
295
296  /// ONE comparison type, at a database index or at none.
297  fn one_comparison(&self, name: &RustSafeName, at: Option<usize>) -> proc_macro2::TokenStream {
298    let db = crate::emit::parameter("DB");
299    let crossings = self.assumptions(&db, at);
300    let rows: Vec<unit::ComparisonColumn> = self
301      .columns
302      .iter()
303      .map(|column| unit::ComparisonColumn {
304        // A STANDALONE declaration's fields carry no condition seat — the `#[cfg]` word is the
305        // record family's, and this model has no field to hold one.
306        gate: proc_macro2::TokenStream::new(),
307        member: column.member.clone(),
308        name: format!("`{}` column", column.name),
309        held: self.held(column, &db, at),
310      })
311      .collect();
312    let header = unit::UnitHeader {
313      vis: &self.vis,
314      name: name.safe().clone(),
315      subject: self.subject(),
316      note: None,
317    };
318    let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
319    // The LOWERING rides with the struct, exactly as a record's does: the type IS a comparison
320    // whether or not anything has crossed into it yet, and the map row below cannot keep its item
321    // bound — `type Comparison: ComplexComparison<Db>` — without it.
322    let seats = unit::LoweringSeats {
323      backend: self.framework(&["comparison"], "Backend"),
324      complex: self.framework(&["comparison"], "ComplexComparison"),
325      frame: self.framework(&["comparison"], "Frame"),
326      at: self.framework(&["comparison"], "At"),
327      field_name: self.framework(&["field"], "FieldName"),
328    };
329    let lowered: Vec<unit::LoweringColumn> = self
330      .columns
331      .iter()
332      .map(|column| unit::LoweringColumn {
333        // A STANDALONE declaration's fields carry no condition seat — the `#[cfg]` word is the
334        // record family's, and this model has no field to hold one.
335        gate: proc_macro2::TokenStream::new(),
336        member: column.member.clone(),
337        rendered: column.name.to_string(),
338        flatten: at
339          .and_then(|at| column.stored.get(at))
340          .is_some_and(|stored| stored.flatten),
341        through: None,
342      })
343      .collect();
344    let lowering = unit::comparison_lowering(name.safe(), &db, &crossings, &seats, &lowered);
345    let crossing = self.crossing(name, &db, at);
346    quote! { #declaration #methods #lowering #crossing }
347  }
348
349  /// What one column's field is held at, in one database.
350  fn held(
351    &self,
352    column: &StandaloneColumn,
353    db: &syn::Ident,
354    at: Option<usize>,
355  ) -> proc_macro2::TokenStream {
356    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
357    let filter = crate::emit::filter_of(
358      &self.krate,
359      &column.domain,
360      column.marker.as_ref(),
361      crate::emit::FilterFace::Column,
362    );
363    let stored = self.stored(column, at);
364    quote!(<#filter as #to_comparison<#stored, #db>>::Comparison)
365  }
366
367  /// What one database stores one column as — its own `type = "…"`, or the domain type.
368  fn stored(&self, column: &StandaloneColumn, at: Option<usize>) -> proc_macro2::TokenStream {
369    let domain = &column.domain;
370    at.and_then(|at| column.stored.get(at))
371      .and_then(|stored| stored.ty.as_ref())
372      .map_or_else(|| quote!(#domain), |ty| quote!(#ty))
373  }
374
375  /// What a comparison over these columns ASSUMES — the record's own list, at one database.
376  ///
377  /// `Db: Backend` leads because it is not elaborated from the rest: a `where F:
378  /// ToDatabaseComparison<V, Db>` names a trait whose own parameter is bounded that way, so the
379  /// predicate is owed at every caller that writes the crossing, and it is a claim about the
380  /// DATABASE rather than about any column.
381  ///
382  /// A `flatten` column states the REFINED crossing and only it: `ToFlattenedComparison<V, Db>` carries
383  /// the plain crossing as its SUPERTRAIT, so a marked column states ONE bound and the other arrives
384  /// by elaboration.
385  fn assumptions(&self, db: &syn::Ident, at: Option<usize>) -> proc_macro2::TokenStream {
386    let backend = self.framework(&["comparison"], "Backend");
387    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
388    let to_flattened = self.framework(&["comparison"], "ToFlattenedComparison");
389    let crossings = self.columns.iter().map(|column| {
390      let filter = crate::emit::filter_of(
391        &self.krate,
392        &column.domain,
393        column.marker.as_ref(),
394        crate::emit::FilterFace::Column,
395      );
396      let stored = self.stored(column, at);
397      let flatten = at
398        .and_then(|at| column.stored.get(at))
399        .is_some_and(|stored| stored.flatten);
400      let crossing = if flatten {
401        &to_flattened
402      } else {
403        &to_comparison
404      };
405      quote!(#filter: #crossing<#stored, #db>,)
406    });
407    quote! {
408      #db: #backend,
409      #(#crossings)*
410    }
411  }
412
413  /// The CROSSING the conversion hook names: the map row saying which comparison this filter seat
414  /// crosses into.
415  ///
416  /// The TYPE-LEVEL half. Its value-level twin — `TryFromFilter`, which builds the comparison operand
417  /// by operand — used to be unwritable at a generic dialect for the reason [`generic_pair`]'s doc
418  /// records, and a standalone comparison's dialect is a parameter even where a database is named:
419  /// the database decides the STORED types, not the driver the query is built for.
420  /// `ToCrossedComparison` opened a door past that wall, and [`generic_pair`] walks BOTH arms through
421  /// it now — the bare one at `at = None`, a named one at this same method's own `at`. So the hook
422  /// delivers the map always, and the operand-level crossing arrives through the kinds' own rows,
423  /// through [`generic_pair`] either way — called beside this method's own emission rather than
424  /// written here, left to a caller that names a concrete backend the way an interface's own crossing
425  /// is.
426  ///
427  /// [`generic_pair`]: Self::generic_pair
428  fn crossing(
429    &self,
430    name: &RustSafeName,
431    db: &syn::Ident,
432    at: Option<usize>,
433  ) -> proc_macro2::TokenStream {
434    let Some(hook) = self.hook.as_ref() else {
435      return proc_macro2::TokenStream::new();
436    };
437    let subject = &self.subject;
438    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
439    let crossings = self.assumptions(db, at);
440    let name = name.safe();
441    quote! {
442      #[automatically_derived]
443      impl<#db> #to_comparison<#subject, #db> for #hook
444      where
445        #crossings
446      {
447        type Comparison = #name<#db>;
448      }
449    }
450  }
451
452  /// One column's (storage type, filter slot) pair, spelled the way [`held`](Self::held) and
453  /// [`assumptions`](Self::assumptions) spell it inline — [`FieldsModel::crossing_of`]'s reader,
454  /// again, for the reason that one is: a slot resolved twice is a slot two answers can disagree
455  /// about. The STORED half is [`stored`](Self::stored)'s own answer, exactly as [`held`] and
456  /// [`assumptions`] already read it: a bare declaration's storage type is always its DOMAIN, `at`
457  /// having no per-database entry to read without a named database, and a named declaration's is
458  /// whichever override — or lack of one — that database wrote. Two readers of one fact would be two
459  /// answers that could disagree; this is the one reader, called wherever the fact is needed.
460  ///
461  /// [`FieldsModel::crossing_of`]: crate::fields::FieldsModel::crossing_of
462  /// [`held`]: Self::held
463  /// [`assumptions`]: Self::assumptions
464  fn crossing_of(
465    &self,
466    column: &StandaloneColumn,
467    at: Option<usize>,
468  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
469    (
470      self.stored(column, at),
471      crate::emit::filter_of(
472        &self.krate,
473        &column.domain,
474        column.marker.as_ref(),
475        crate::emit::FilterFace::Column,
476      ),
477    )
478  }
479
480  /// What a crossing over these columns ASSUMES, at no named database or at one —
481  /// [`FieldsModel::crossings`]'s clause, read off this door's own column list at whichever `at`
482  /// [`generic_pair`](Self::generic_pair) is itself called with.
483  ///
484  /// The union of the columns' rows, deduplicated by spelling — two columns of one type and one
485  /// `flatten`-ness ask one question, and a `where` clause repeating it says nothing more. `DB:
486  /// Backend` leads for [`assumptions`](Self::assumptions)'s reason; the map row that method states
487  /// arrives here by ELABORATION off `ToCrossedComparison`'s supertrait, so a non-`flatten` column's
488  /// row here is not [`assumptions`]'s plus something — it is that one, refined, and `Self::new`'s
489  /// own weaker clause for that column is discharged by the same elaboration.
490  ///
491  /// # A `flatten` column states one row more
492  ///
493  /// [`assumptions`] states `ToFlattenedComparison<V, Db>` rather than `ToDatabaseComparison<V, Db>`
494  /// for a `flatten` column, and that trait is a SIBLING refinement of the plain map — not a
495  /// supertrait of `ToCrossedComparison` and not implied by it — so the elaboration the paragraph
496  /// above leans on does not reach a `flatten` column's own row of [`assumptions`]'s clause. This
497  /// method states that row explicitly, beside the crossing rather than instead of it: the crossing is
498  /// what `cross`/`empty` need, the flattened row is what the `Self::new` call
499  /// [`generic_pair`](Self::generic_pair) makes still needs, and a column that is not `flatten` at
500  /// this `at` asks for neither the second row nor the first's supertrait restated — same as before
501  /// this knife, for every column a named database has not marked.
502  ///
503  /// [`FieldsModel::crossings`]: crate::fields::FieldsModel::crossings
504  /// [`assumptions`]: Self::assumptions
505  fn crossings(&self, db: &syn::Ident, at: Option<usize>) -> proc_macro2::TokenStream {
506    let backend = self.framework(&["comparison"], "Backend");
507    let to_crossed = self.framework(&["comparison"], "ToCrossedComparison");
508    let to_flattened = self.framework(&["comparison"], "ToFlattenedComparison");
509    let mut seen: Vec<String> = Vec::new();
510    let mut rows = proc_macro2::TokenStream::new();
511    for column in &self.columns {
512      let (stored, slot) = self.crossing_of(column, at);
513      let flatten = at
514        .and_then(|at| column.stored.get(at))
515        .is_some_and(|stored| stored.flatten);
516      let mut row = quote!(#slot: #to_crossed<#stored, #db>,);
517      if flatten {
518        row.extend(quote!(#slot: #to_flattened<#stored, #db>,));
519      }
520      let spelling = row.to_string();
521      if seen.iter().any(|kept| kept == &spelling) {
522        continue;
523      }
524      seen.push(spelling);
525      rows.extend(row);
526    }
527    quote! {
528      #db: #backend,
529      #rows
530    }
531  }
532
533  /// **THE VALUE-LEVEL CROSSING AND THE EMPTY PREDICATE, AT A PARAMETER** — this door's own
534  /// `TryFromFilter<F> for <S>Comparison<DB>` and the `Default` beside it, both through
535  /// `ToCrossedComparison`, one impl for every backend — at no named database, or at the ONE this
536  /// call's own `at` selects.
537  ///
538  /// [`FieldsModel::generic_pair`]'s arrangement, read onto ONE struct's columns rather than a
539  /// fragment's fields — no `#[cfg]` walk, because a standalone declaration's fields carry no
540  /// condition seat at all, and the fields tier's gate is empty tokens wherever a member wrote none.
541  ///
542  /// # Gated on the HOOK, not on bareness
543  ///
544  /// The map row [`crossing`](Self::crossing) names is `F` = the hook — the filter seat the container
545  /// declared, not this door's own minted [`emit_filter`](Self::emit_filter) output, which a
546  /// declaration may point the hook AT but which this method never assumes. Without a hook there is
547  /// no `F` for `TryFromFilter<F>` to be OVER, and `Default` stays with it rather than shipping alone:
548  /// the two are one PAIR, and a pair with one half orphaned is not what either door emits. A
549  /// declaration naming no hook gets neither half, exactly as it gets no map row — the existing
550  /// refusal at the FIELD tier (a conversion word with no container hook) already covers the only
551  /// place this absence is reachable by name, and its wording does not change: nothing here mints a
552  /// NEW way to reach a comparison's fields, only a new thing a hook, once written, buys — whether or
553  /// not the declaration also names a database.
554  ///
555  /// # Called beside [`one_comparison`], never inside it
556  ///
557  /// See [`emit_comparison`](Self::emit_comparison)'s own doc for why: [`one_comparison`] must run the
558  /// exact code it always has, and the surest way to keep it byte-identical is for this method to be
559  /// unreachable from it rather than reachable-and-declining — true of the bare branch as it always
560  /// was, and now equally true beside each named iteration: a named declaration's comparison stays a
561  /// parameter too, see [`crossing`](Self::crossing)'s doc, so nothing about the WALL ever argued for
562  /// the boundary sitting where #358 left it; only scope did, and this method's own second parameter
563  /// is what closes that scope.
564  ///
565  /// # The STORED-type override, at a parameter
566  ///
567  /// `at` reaches [`crossings`](Self::crossings) and [`crossing_of`](Self::crossing_of) exactly as it
568  /// already reaches [`assumptions`](Self::assumptions) and [`held`](Self::held): the crossing's `V`
569  /// is [`stored`](Self::stored)'s own answer, so a named database's own override is what this pair
570  /// crosses THROUGH, not the domain type underneath it, and `DB` stays a parameter regardless of
571  /// which database named the override — naming a database here still only ever pinned the STORED
572  /// type, never the driver the query renders for.
573  ///
574  /// [`one_comparison`]: Self::one_comparison
575  /// [`FieldsModel::generic_pair`]: crate::fields::FieldsModel::generic_pair
576  fn generic_pair(&self, name: &RustSafeName, at: Option<usize>) -> proc_macro2::TokenStream {
577    let Some(hook) = self.hook.as_ref() else {
578      return proc_macro2::TokenStream::new();
579    };
580    let db = crate::emit::parameter("DB");
581    let comparison = name.safe();
582    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
583    let to_crossed = self.framework(&["comparison"], "ToCrossedComparison");
584    let boxed = crate::model::boxed_error();
585    let clause = self.crossings(&db, at);
586    let doc = crate::emit::leading(&format!(
587      "Cross a wire filter into the predicate this {subject}'s comparison compares by — every \
588       column through its own crossing, and the empty comparison wherever the client asked \
589       nothing.\n\nONE impl for every backend: this {subject}'s comparison is generic in its dialect \
590       even where the declaration names a database, so its crossing carries each column's row rather \
591       than discharging it.\n\n# Errors\nWhatever a column's crossing into its stored form refused \
592       with.",
593      subject = self.subject(),
594    ));
595    let members: Vec<proc_macro2::TokenStream> = self
596      .columns
597      .iter()
598      .map(|column| {
599        let member = &column.member;
600        quote!(#member,)
601      })
602      .collect();
603    let empty: Vec<proc_macro2::TokenStream> = self
604      .columns
605      .iter()
606      .map(|column| {
607        let (stored, slot) = self.crossing_of(column, at);
608        quote!(<#slot as #to_crossed<#stored, #db>>::empty(),)
609      })
610      .collect();
611    let legs = self.columns.iter().map(|column| {
612      let member = &column.member;
613      let (stored, slot) = self.crossing_of(column, at);
614      quote! {
615        let #member = match __ingraph_filter.#member {
616          ::core::option::Option::Some(__ingraph_held) => {
617            match <#slot as #to_crossed<#stored, #db>>::cross(__ingraph_held) {
618              ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
619              ::core::result::Result::Err(__ingraph_why) => {
620                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
621              }
622            }
623          }
624          // The client asked nothing about this column, which is not the same as asking for
625          // nothing to match: the empty comparison renders no conjunct.
626          ::core::option::Option::None => <#slot as #to_crossed<#stored, #db>>::empty(),
627        };
628      }
629    });
630    quote! {
631      // `Self::new` and never a struct literal: the constructor is the comparison's only
632      // construction path, and a second one here would be a second place the column list lives.
633      #[automatically_derived]
634      impl<#db> ::core::default::Default for #comparison<#db>
635      where
636        #clause
637      {
638        #[inline]
639        fn default() -> Self {
640          Self::new(#(#empty)*)
641        }
642      }
643
644      #[automatically_derived]
645      impl<#db> #try_from_filter<#hook> for #comparison<#db>
646      where
647        #clause
648      {
649        type Error = #boxed;
650
651        #[doc = #doc]
652        fn try_from_filter(
653          __ingraph_filter: #hook,
654        ) -> ::core::result::Result<Self, Self::Error> {
655          #(#legs)*
656          ::core::result::Result::Ok(Self::new(#(#members)*))
657        }
658      }
659    }
660  }
661}