Skip to main content

ingraph_codegen/
fields.rs

1//! The FIELD-FRAGMENT TIER's emission — the faces a value has, and none of the faces a NODE has.
2//!
3//! A fragment is 公用字段抽取: a group of fields several declarations hold, written once. It is the
4//! BOTTOM RUNG of the record family's ladder — held rather than declared — and every absence below
5//! follows from that single fact rather than from an era rule or a missing layer:
6//!
7//! * no `Identifiable`, because it bears no id — that is what the tier MEANS, and a fragment's
8//!   identity, when a question about one arises at all, is its holder's;
9//! * no `Transformer`, whose whole content is a key and the two address types beside it;
10//! * no `Graphql`, because a fragment is not a queryable ROOT and a root is what that face is;
11//! * no storage of any kind, because a fragment's columns are the HOLDER's row.
12//!
13//! The rung above is `entity`, which bears an identity and no rows; above that is `record`, which
14//! bears both. The three are one ladder and each word names what its rung HAS.
15//!
16//! # The three FACES, and why none of them is a family word
17//!
18//! What a fragment HAS is a width and the questions that follow from it. A holder's emission never
19//! learns what a fragment is — nothing in `emit::graphql` names this tier, before these faces or
20//! after them — because every seam a holder reaches a column's type through is a PROJECTION the
21//! type answers:
22//!
23//! | the holder writes | the fragment answers with |
24//! |---|---|
25//! | `shape::<Ty>(…)` in its column list | [`ColumnKind`](Self::columns) — the WIDTH |
26//! | `<<Ty as DefaultMarker>::Marker as ToGraphqlFilter>::{Filter, ColumnFilter}` in its filter | [`filter`](Self::filter) — the two marker rows, and the up-to-two predicates they name (the author's, where `filter = "…"` mounted one) |
27//! | `<That as ToDatabaseComparison<Ty, Db>>::Comparison` in its predicate | [`comparison`](Self::comparison) — one conjunct per field, each one segment down |
28//!
29//! So the faces are ANSWERS to questions the holder was already asking, and the tier's absences are
30//! untouched: what is stated here is a column layout, a predicate over it, and the reading that
31//! resolves the two — never a node's identity, its rows, or its place as a query's root.
32//!
33//! Beside them is the fragment's own API — one accessor family per field — which is what [`Column`]
34//! already emits for a record. The reuse is the point: a fragment's fields are read exactly as a
35//! record's are, and a second shape for the same thing is what this file exists not to be. The
36//! filter and the comparison keep that discipline one layer up, being [`unit`]'s own walks — the
37//! same two a record and a standalone struct compose.
38//!
39//! # What a holder does with one is not here
40//!
41//! The field grammar a fragment declares — the labels, the storage legs, the wire legs — is
42//! inherited by every holder. Nothing reads that yet, so nothing here carries it: the model holds
43//! what this emission spends and grows when the inheritance arrives to spend the rest.
44//!
45//! The holder-side word that DOES exist is a naming act rather than a divergence:
46//! `persist(<db>(flatten))` decides whether one database drops the prefix a held fragment's columns
47//! are laid out under, and it asks nothing of this tier — the holder's own `PersistColumn` carries
48//! it. What it DOES ask of the fragment is the refined crossing, and
49//! [`comparison`](Self::comparison) is where that is answered.
50//!
51//! # The REWRITE mode, and the seat this tier does not have
52//!
53//! `remote = "…"` makes a declaration a transparent wrapper over a type another crate owns, and
54//! `fields` is the FOURTH declaration to take it — after `entity`, `record` and the vocabulary
55//! kinds. The device is [`crate::remote`]'s and is shared rather than re-implemented: the same
56//! bridge, the same reference family, the same escape.
57//!
58//! What is this tier's own is the ABSENCE. A record's rewrite splits every read on `identity` —
59//! an id column is borrowed, because this framework's identity seats borrow, and a data column
60//! crosses by value — and a fragment bears no id, so the split has one branch. The manifest's
61//! columns are all equal: one by-value reader each, no `_ref`, no `id_ref`, no identity seat to
62//! serve. The `id` word is refused at the front end, so an identity-bearing manifest field never
63//! reaches this emission.
64//!
65//! The four FACES above are untouched by the mode, and that is the point of restating a foreign
66//! type as a manifest at all: a width, a filter slot, a comparison conjunct and a wire member are
67//! read off a declared NAME and a declared TYPE, which a manifest states exactly as a held field
68//! does. The one place the mode is visible in a face is the wire object's resolver — see
69//! [`wire`](FieldsModel::wire), where a measured `E0515` forced the arm to HOLD its value in
70//! `ingraph::Crossed` rather than borrow one it does not own. What a client reads is unmoved by
71//! that: the adapter delegates every name to the same crossing the held arm returns through.
72
73use quote::{format_ident, quote, quote_spanned};
74use syn::spanned::Spanned as _;
75
76use crate::{
77  composed,
78  construct::{Build, Construction},
79  delegate::Delegate,
80  method::{ColumnOrigin, Emitted, Member, Origin, Owner},
81  model::{Column, Condition, DatabaseKind, Fill},
82  name::RustSafeName,
83  remote::Ingredient,
84  unit,
85};
86
87#[cfg(test)]
88mod tests;
89
90/// The `const` the SEGMENT NAMES are minted into, inside the expansion's own anonymous const.
91///
92/// One constant because three emissions spell it — the list itself, the width that names each entry
93/// into a `ColumnShape`, and the read that fetches each column by name — and a name that drifted
94/// between them would be `E0425` inside an expansion nobody can edit.
95const FIELDS: &str = "__INGRAPH_FRAGMENT_FIELDS";
96
97/// ONE field a fragment declares: the COLUMN every face reads, and the documentation the
98/// declaration wrote above it.
99///
100/// A [`Column`] rather than a [`Field`](crate::model::Field): a `Field` carries `identity` and a
101/// `reference`, and a fragment has neither to carry. What is left — the name, the written type and
102/// the projection its accessor hands it back by — is exactly a column.
103///
104/// The DOCS are a seat of their own because the REWRITE deletes the field that held them. An
105/// ordinary fragment keeps its fields, so their doc comments stay where the author put them and
106/// nothing here has to carry one; a fragment that wraps a foreign type has no such field left, and
107/// the reader is the one place that field's meaning is still answerable. Beside the column rather
108/// than in a list of their own, for the reason [`comparison`](FieldsModel::comparison) states about
109/// the two column lists it refuses to keep: two lists that agreed today are two lists that can
110/// drift.
111#[derive(Debug, Clone)]
112pub struct FragmentField {
113  /// The column — the name, the written type and the projection.
114  pub column: Column,
115  /// `record(flatten)` — whether this field lends its name to the columns beneath it.
116  ///
117  /// # It is the INNER mount's word, and it names no database
118  ///
119  /// A record scopes the same decision per database — `<db>(flatten)` rides that row's own column
120  /// list — and a fragment has no such list to scope it in: the layout a fragment publishes is
121  /// [`ColumnKind::SEGMENTS`](FieldsModel::columns), which carries no dialect and is measured not to
122  /// want one. So the word here is written without a database and means what the type means: this
123  /// field's segments are columns of the FRAGMENT's own namespace, wherever that namespace is
124  /// eventually laid out. `record(<db>(flatten))` is refused by name for exactly that measurement.
125  ///
126  /// `false` is the default and is the bare TYPE POSITION's own answer — a field whose type holds
127  /// several values is stored as those values, prefixed with the field's name.
128  pub flatten: bool,
129  /// What this field's `builder(…)` said about its place in the wrapped type's CONSTRUCTION — its
130  /// seat, its crossing, and the two words that stand on their own.
131  ///
132  /// Carried in BOTH modes and spent in ONE, exactly as [`docs`](Self::docs) is: an ordinary
133  /// fragment IS its fields, so a raise writes the struct literal and there is no call sequence for
134  /// a word to describe. The grammar refuses every construction word on such a declaration by name,
135  /// so a spent-nowhere value here is the default and never an author's silently-dropped sentence.
136  pub build: Build,
137  /// The field's own doc comments, `///` and `#[doc = "…"]` alike, in the order they were written.
138  ///
139  /// Empty is the ordinary case and means exactly what it says: nothing was written, or nothing has
140  /// to be carried.
141  pub docs: Vec<syn::Attribute>,
142  /// The `#[cfg]`s this field is declared under, and the `#[cfg_attr]`s that decorate its stand-in.
143  ///
144  /// # The tier used to have no seat for one, and five faces emitted over the hole
145  ///
146  /// [`crate::remote`]'s own note promised a manifest field's `cfg` *the reader, the column in every
147  /// database, the filter seat, the order-by term and the place on the wire face, all together*, and
148  /// this tier had nowhere to keep it: the field was accepted, the reader emitted unconditionally,
149  /// and a negative predicate produced an expansion naming a field the build had removed. The
150  /// measurement, on a two-field fragment with one gated field: **six errors** — three `E0615` at the
151  /// accessor family and one `E0560` at the raise's struct literal, plus the pair rustc adds — with
152  /// `#[cfg_attr(pred, ingraph(…))]` beside it dropped in silence, which is the exact failure that
153  /// refusal exists to prevent.
154  ///
155  /// So the seat is the record family's, read by the same `attribute::condition` and spent by the
156  /// same two spellings: [`Condition::gate`] wherever an attribute may sit, and
157  /// [`Condition::present`] summed by [`crate::emit::positions`] wherever an ORDINAL indexes a list
158  /// the predicates contract.
159  ///
160  /// # Two limits, both the family's own and neither this tier's
161  ///
162  /// A WHERE-PREDICATE takes no attribute, so the obligations a conditional field contributes stay
163  /// in the clause whichever way its predicate goes — the record's element crossings say the same
164  /// thing at their own seat. And a CURSOR KEY member may not be conditional at all: a key that
165  /// contracted would page by a different order than the one that wrote the cursor, so the front end
166  /// refuses it by name.
167  ///
168  /// [`Condition::gate`]: crate::model::Condition::gate
169  /// [`Condition::present`]: crate::model::Condition::present
170  pub condition: Condition,
171  /// `record(rename = "…")` — what this column is CALLED where it is stored, or [`None`] for the
172  /// field's own name.
173  ///
174  /// # One axis moves and the other does not, which is what `ColumnName` is for
175  ///
176  /// A column has two names: what the DECLARATION calls it — the axis a filter, a comparison and an
177  /// order all speak in — and what a STATEMENT renders, which is what an engine resolves. The record
178  /// seat's bare `rename` moves the second and leaves the first, and this is that word one namespace
179  /// in, meaning exactly what it means there.
180  ///
181  /// It is DIALECT-FREE where a record scopes a second one per database, and that is the same
182  /// measurement [`flatten`](Self::flatten) rides: a fragment publishes one `ColumnKind::SEGMENTS`
183  /// carrying no dialect, so there is no second list for a second database's name to be written
184  /// into.
185  ///
186  /// [`None`] means *nothing was written* exactly, and a fragment that renames nothing expands token
187  /// for token as it did before the word existed — the shape entry stays `ColumnName::of`, the
188  /// spelling for a column whose two names are one string.
189  pub stored_name: Option<String>,
190  /// `graphql(rename = "…")` — what a client calls this field, or [`None`] for the fold of its own
191  /// name.
192  ///
193  /// ONE word for the two surfaces a field publishes: the object's member and the filter's slot are
194  /// one field's name on the wire, and a record's own face reads them off one declared name for the
195  /// same reason. The fallback is not stored here — it is `wire_member`'s camelCase fold, computed
196  /// where it is spent — so [`None`] means *nothing was written* exactly.
197  pub wire_name: Option<String>,
198  /// `record(skip)` / `record(skip(default = "…"))` — the DECLARED ABSENCE, and what fills the read.
199  ///
200  /// The record field seat's own `skip`, one namespace in and meaning exactly what it means there:
201  /// no column in ANY database. Under the inversion law a bare field IS a column, so this is the one
202  /// declared exit — and the fill is what makes it an exit rather than a hole, a read having to
203  /// supply the value the row does not carry.
204  ///
205  /// What it subtracts is every STORAGE answer and the predicate with it: no segment, no name, no
206  /// bind, no read and no filter slot, per the ruled law that each face walks its own participation
207  /// set and the filter follows storage. What it does NOT subtract is the tier's own value face —
208  /// the accessor family and the place on the wire object — because those are what the declaration
209  /// IS rather than what a holder asked for.
210  ///
211  /// It is refused beside `cursor`: the key is every declared field, and a member with no column is
212  /// one the SQL keyset cannot compare.
213  pub skip: Option<Fill>,
214  /// `record(derived(column = "…", from = "…", type = "…"))` — the columns this field's declaration
215  /// adds to the layout and the WRITE computes, in the order they were written.
216  ///
217  /// [`skip`](Self::skip)'s mirror image, and the pairing is exact: a skipped field is
218  /// declared-but-not-stored and the raise fills it, a derived column is stored-but-not-declared and
219  /// the write computes it. So the two words are refused beside each other — a field with no column
220  /// in any database has no place in the layout for a column to follow.
221  ///
222  /// EMPTY is the ordinary case and is what every declaration written before the word existed
223  /// carries, so a fragment deriving nothing expands token for token as it did.
224  pub derived: Vec<Derived>,
225  /// `record(write = "…")` — the function this field's value passes through on its way to storage,
226  /// or [`None`] for the value as it stands.
227  ///
228  /// # ONE function, TWO sites, and that is the whole of what the word buys
229  ///
230  /// The type layer preserves the DECLARED spelling — a container that says `2/4` is held as `2/4`
231  /// — so canonicalisation is forbidden at the constructor door and belongs at the STORAGE
232  /// boundary. A hand-written household does it by discipline, calling `Rate::reduced()` at the
233  /// bind AND at the crossing's query operand, and the two-sites-one-function agreement is the
234  /// entire reason an index answers `eq` exactly: store `2/4` unreduced in one row and a client
235  /// asking `eq(1/2)` misses it.
236  ///
237  /// So the word is spent twice — [`carrier`](FieldsModel::carrier) wraps the accessor, and both
238  /// crossing arms map the operand through the SAME path — and a golden pins that the two agree.
239  /// Spending it at one site only manufactures the exact miss the seat exists to kill.
240  ///
241  /// # `fn(&T) -> T`, pinned in a `const` no feature gates away
242  ///
243  /// [`transforms`](FieldsModel::transforms) writes `const _: fn(&T) -> T = path;` per declared
244  /// transform, so a path that resolves to nothing is `E0433` and one whose signature disagrees is
245  /// `E0308`, both at the string the author wrote. The device is the derived seat's, one shape in:
246  /// there the function is a never-called ARGUMENT because a `ColumnShape` had to be built anyway,
247  /// and here there is no artifact to build, so the pin is the const's own type.
248  ///
249  /// [`None`] means *nothing was written* exactly, and a fragment transforming nothing expands
250  /// token for token as it did before the word existed.
251  pub write: Option<syn::Path>,
252  /// `record(read = "…")` — the function a stored value passes through on its way back, or [`None`]
253  /// for the identity.
254  ///
255  /// [`write`](Self::write)'s optional mirror, for the household whose stored form is not a domain
256  /// form. ABSENT MEANS IDENTITY, and that is the canonicalisation case rather than an oversight: a
257  /// reduced rational is a valid `Rate`, so nothing has to be undone on the way out.
258  ///
259  /// It is the READ's word alone — [`assemble`](FieldsModel::assemble) wraps the fetch — and it
260  /// reaches no other face: a filter operand is a client's value travelling INTO storage, which is
261  /// [`write`](Self::write)'s direction.
262  pub read: Option<syn::Path>,
263}
264
265/// ONE column a WRITE computes — `record(derived(column = "…", from = "…", type = "…"))`, attached
266/// to the field it is derived from.
267///
268/// # Why the TYPE is written when the function already carries it
269///
270/// `from` names a `fn(&Self) -> T` and `T` is the column's type, which is all a WIDTH needs: the
271/// shape entry is `ingraph::derived::<Self, T>(from, …)` and the compiler reads `T` off the
272/// function. The other faces cannot. A `where` clause owes `T: Carrier<DB>`, a filter slot is a
273/// projection off `T`, and a comparison member names `T` in a bound — all of them need the type as
274/// TOKENS, and stable Rust has no way to spell a function's return type. So the declaration writes
275/// it, and the shape entry above is what holds the two spellings together: `from` returning
276/// anything else is `E0308` at the path that named it.
277#[derive(Debug, Clone)]
278pub struct Derived {
279  /// The column's own name — its Rust face, and the name every emitted vocabulary speaks in.
280  ///
281  /// One name and not two. A declared field renames its STORED axis with `record(rename = "…")` and
282  /// keeps its declared one; a derived column has no field to have been called anything else, so
283  /// the word that names it names both axes at once and [`RustSafeName`] is the pairing — the
284  /// external half is the string as written, the safe half is the member an expansion may spell.
285  pub column: RustSafeName,
286  /// `from = "…"` — the function that computes this column, `fn(&Self) -> T`.
287  pub from: syn::Path,
288  /// `type = "…"` — `T`, so the faces that cannot read it off the function can name it.
289  pub ty: syn::Type,
290}
291
292/// ONE column of a fragment's published layout — a field the declaration holds, or a column
293/// DERIVED from one.
294///
295/// # Why the two arms travel together
296///
297/// Every storage face walks columns rather than fields: the width names one shape apiece, the bind
298/// pushes one placeholder apiece, the stored predicate offers one slot apiece and the comparison
299/// renders one conjunct apiece. A derived column is a column at all four, so a walk that had to ask
300/// *and are there any derived ones* at each of them would be four places for the answer to differ.
301/// One list, four readers — the arrangement [`FieldsModel::names`] already uses for the names
302/// themselves.
303///
304/// The READ is the face that parts, and it parts by walking a different list rather than by testing
305/// this one: [`FieldsModel::assemble`] walks the declared fields, because a value is rebuilt from
306/// what was declared and a derived column has nothing to be rebuilt into.
307#[derive(Debug, Clone, Copy)]
308enum Laid<'a> {
309  /// A field the declaration holds — its own type, its own name, its own place on every face.
310  Declared(&'a FragmentField),
311  /// A column computed off `source` by `column`'s function.
312  Derived {
313    /// The field the word was attached to — whose condition this column rides, and whose position
314    /// it follows.
315    source: &'a FragmentField,
316    /// The column itself: its name, its function and its type.
317    column: &'a Derived,
318  },
319}
320
321impl<'a> Laid<'a> {
322  /// The `#[cfg]`s this column is emitted under.
323  ///
324  /// A derived column rides its SOURCE's, and it has to: the function reads the field, so a build
325  /// whose predicate removed the field has no function to call. One gate, one pair of columns, in
326  /// every list the predicates contract.
327  fn condition(&self) -> &'a Condition {
328    match self {
329      Self::Declared(field) | Self::Derived { source: field, .. } => &field.condition,
330    }
331  }
332
333  /// The gate an attribute position spells.
334  fn gate(&self) -> proc_macro2::TokenStream {
335    self.condition().gate()
336  }
337
338  /// The column's own type — the field's, or the one the `derived` word wrote.
339  fn ty(&self) -> &'a syn::Type {
340    match self {
341      Self::Declared(field) => &field.column.ty,
342      Self::Derived { column, .. } => &column.ty,
343    }
344  }
345
346  /// The identifier a filter slot and a comparison member are called.
347  fn member(&self) -> &'a syn::Ident {
348    match self {
349      Self::Declared(field) => &field.column.name,
350      Self::Derived { column, .. } => column.column.safe(),
351    }
352  }
353
354  /// What a doc sentence calls this column.
355  fn subject(&self) -> String {
356    match self {
357      Self::Declared(field) => format!("`{}` field", field.column.name),
358      Self::Derived { column, source } => format!(
359        "`{}` column, derived from the `{}` field",
360        column.column.external(),
361        source.column.name
362      ),
363    }
364  }
365
366  /// Whether this column lends its name to the columns beneath it.
367  ///
368  /// A derived column always does. `record(flatten)` is the INNER MOUNT's word — it says a declared
369  /// field's type lays its segments in the fragment's own namespace — and a derived column has no
370  /// field to have dropped the name of: the `column = "…"` word IS its name, so there is nothing to
371  /// flatten away.
372  fn flatten(&self) -> bool {
373    match self {
374      Self::Declared(field) => field.flatten,
375      Self::Derived { .. } => false,
376    }
377  }
378
379  /// The DECLARED field this column belongs to, or [`None`] for a derived one.
380  ///
381  /// What the faces a derived column stays out of ask, so the exclusion is one question rather than
382  /// a `matches!` at each of them.
383  fn declared(self) -> Option<&'a FragmentField> {
384    match self {
385      Self::Declared(field) => Some(field),
386      Self::Derived { .. } => None,
387    }
388  }
389}
390
391/// The RECORD-HOST activation: `record`, and the dialects the declaration named inside it.
392///
393/// # The container declares the capability set, which is the family's inversion law
394///
395/// A record's head names the databases its rows land in and a bare field is a column in every one
396/// of them; a fragment says the same thing one namespace in, and its fields narrow the same way.
397/// The list here is that head's, read at the tier that is HELD rather than stored — so it claims no
398/// table and mints no row: what it names is which dialects this fragment was BUILT for, and
399/// therefore which per-dialect faces have a declaration to be emitted from. There is exactly one
400/// such face — the comparison pair a wire-faced holder asks for — and it is written at each named
401/// dialect's concrete backend; see [`FieldsModel::pair`].
402///
403/// It is the position `crossing(<db>, …)` was heading for and never reached. That word claimed no
404/// storage either and said so in its own note; what the namespace adds is the one thing that made
405/// it ambiguous — a dialect written bare on a fragment used to be a store claim at one seat and a
406/// crossing target at another, and inside `record(…)` there is only one reading.
407#[derive(Debug, Clone)]
408pub struct RecordHost {
409  /// The dialects this fragment is built for, in the order the declaration named them.
410  ///
411  /// EMPTY is the bare `record` word and is not a defect: the storage faces below are dialect-
412  /// GENERIC — one `Carrier<DB>`, one `Assemble`, one `SEGMENTS` — so a fragment that names no
413  /// dialect is held by a record storing rows in any of them, and gets no pair, which is what every
414  /// declaration written before the model existed does.
415  ///
416  /// What a named dialect buys is the COMPARISON PAIR, minted per entry at that entry's concrete
417  /// backend. It buys nothing at the layout: those three faces carry no dialect and cannot be split
418  /// per dialect — the read least of all, two `Assemble` impls constrained to different
419  /// `Row::Database`s being `E0119` — so a per-FIELD claim about a dialect is refused at the front
420  /// end with that measurement, and a layout that varies per database is the HOLDER's to write.
421  ///
422  /// It is also where a MOUNTED LOWERING hangs, which is the second thing a named dialect buys —
423  /// see [`BuiltFor::comparison`].
424  pub databases: Vec<BuiltFor>,
425  /// `record(write = "…")` — the WHOLE VALUE's way across the storage boundary, or [`None`] where
426  /// the declaration wrote none.
427  ///
428  /// # The field seat cannot spell it, and that is the whole reason this one exists
429  ///
430  /// [`FragmentField::write`] is a `fn(&T) -> T` over ONE field's type. A canonical form that reads
431  /// SEVERAL fields at once has no such function: reducing a rational divides both halves by their
432  /// common factor, so the numerator's new value is not a function of the numerator. The seat here
433  /// is `fn(&Self) -> Self` — the whole value in, the whole value out — which is exactly the shape
434  /// the hand households already have, `Rate::reduced()` and `Timebase::reduced()` being methods on
435  /// the value rather than on either half.
436  ///
437  /// # What it is spent at, and why that is TWO sites rather than one
438  ///
439  /// Every place this emission carries the whole value ACROSS the storage boundary, which the census
440  /// of 2026-08-24 enumerated: the BIND ([`carrier`](FieldsModel::carrier)) and the CURSOR's write
441  /// ([`keyset`](FieldsModel::keyset)). Both must spend it or the pair disagrees — a keyset boundary
442  /// written from the declared spelling resumes against columns holding the canonical one, which is
443  /// the paging twin of the `eq` miss the field seat exists to kill.
444  ///
445  /// The CROSSING is not a third site, and the reason is measured rather than deferred: the emitted
446  /// composite predicate is one `Option<component filter>` per COLUMN
447  /// ([`crate::unit::filter`]), so `try_from_filter` never holds a whole `Self` for a
448  /// `fn(&Self) -> Self` to touch — and a whole-value transform has no per-column action to push
449  /// down, `num = 2` having no image under a reduction that divides by a factor of the PAIR. See
450  /// [`FieldsModel::head_write`] for the whole ruling.
451  ///
452  /// A [`syn::Path`] for [`BuiltFor::comparison`]'s reason: the path is EMITTED, so one naming
453  /// nothing is `E0433` at the string the author wrote and one whose signature disagrees is `E0308`
454  /// there.
455  pub write: Option<syn::Path>,
456  /// `record(read = "…")` — the mirror, or [`None`] for the identity.
457  ///
458  /// The raise side is SYMMETRIC, which is what admits the word at all: [`FieldsModel::assemble`]
459  /// builds a whole `Self` out of the fetched columns and [`FieldsModel::keyset`]'s read builds one
460  /// out of the cursor's bytes, so a `fn(&Self) -> Self` has the same two sites in this direction
461  /// that [`write`](Self::write) has in the other.
462  ///
463  /// ABSENT is the IDENTITY, for the field seat's reason: a canonicalisation's stored form IS a
464  /// domain form — a reduced rational is a rational — so the common case writes `write` alone.
465  pub read: Option<syn::Path>,
466}
467
468/// ONE dialect this fragment is BUILT for, and whatever lowering it mounted there.
469///
470/// # The mount is per dialect because a lowering is
471///
472/// A comparison is backend-SPECIFIC by construction — that is `ingraph::comparison`'s own first
473/// paragraph — so the seat that replaces one is per backend too. There is deliberately no
474/// dialect-free spelling: a type generic over the SQL family serves three dialects and not MongoDB,
475/// and a bare seat would leave that scope implicit at the one declaration that could have stated
476/// it. A family-generic type is named at each dialect it serves, and each mention is audited
477/// against the dialect it was written at.
478#[derive(Debug, Clone)]
479pub struct BuiltFor {
480  /// Which database this entry named.
481  pub kind: DatabaseKind,
482  /// `<db>(comparison = "…")` — the type this fragment's predicate LOWERS INTO at this dialect,
483  /// or [`None`] where the framework's per-field product stands.
484  ///
485  /// # What it replaces, and why a field list cannot say it
486  ///
487  /// The emitted comparison is a per-FIELD product: one conjunct per column, each rendered one
488  /// segment below the address the whole value arrived at. A whole-value operator has no field to
489  /// hang on — `overlaps` on a time range is `start < $end AND end > $start`, one predicate over two
490  /// columns at once — so a household needing one bespoke lowering had to decline the storage
491  /// activation entirely, which is what kept the pilot's time household hand-written.
492  ///
493  /// It is the declared mirror of [`FieldsModel::filter`]: that word mounts the author's WIRE
494  /// predicate and this one mounts the author's LOWERING, and the two are independently swappable.
495  /// Where BOTH are written the framework still writes the map row that joins them — the author's
496  /// filter at this dialect lowering into the author's comparison — because that row is the one
497  /// artifact neither word can write for itself.
498  ///
499  /// A [`syn::Path`] for [`FieldsModel::filter`]'s reason: it names a type this declaration did not
500  /// mint and the path is EMITTED, so one naming nothing is `E0412` at the string the author wrote,
501  /// and one naming a type that does not answer the dialect's faces is the audit's own sentence at
502  /// the same span.
503  pub comparison: Option<syn::Path>,
504  /// `<db>(cursor = "…")` — the type that writes this fragment's CURSOR BYTES at THIS dialect, or
505  /// [`None`] where the framed default stands there.
506  ///
507  /// # Per dialect in substance, not only in grammar
508  ///
509  /// The seat sits in a dialect group by the register law — a word that names a TYPE is written where
510  /// the dialect is, as `comparison` is one word over — and here the placement is what the value
511  /// MEANS rather than where it is filed: the bytes belong to that store. A page cursor is
512  /// session-lived pagination state rather than a durable id, so the only engine that has to read a
513  /// token is the one that minted it, and a household is free to keep a dense form per store.
514  ///
515  /// So the entries need not agree, and a declaration mounting three different codecs at three
516  /// dialects is ordinary. [`FieldsModel::per_dialect_keyset`] is what spends them: one row per
517  /// DECLARED dialect, carrying the mounted codec where one was named and the frame where none was.
518  ///
519  /// A [`syn::Path`] for [`Self::comparison`]'s reason, with the same two failure modes at the same
520  /// span.
521  pub cursor: Option<syn::Path>,
522}
523
524/// The WIRE activation: `graphql`, and the two SDL names its block may move.
525///
526/// # A third activation, and saddle-agnostic where the other two are host kinds
527///
528/// `record` and `entity` name the rungs that may HOLD this fragment. This one names nothing of the
529/// sort: it says the declaration has a face on the wire at all. Without it a fragment is a
530/// storage-only value — a width, a bind, a read and a predicate, with no object, no crossing and no
531/// input-object registration — which is a shape the tier could not express before, every declaration
532/// publishing whether anything asked or not.
533///
534/// The old refusal's sentence survives as the SIGNPOST rather than as a rule: a fragment still has no
535/// queryable ROOT, and what it shows on the wire is a fragment of whatever holds it. What the word
536/// activates is the object that holder resolves through.
537///
538/// # Two SDL names, which is the seat #340's survey left open
539///
540/// A fragment publishes four named surfaces — its object, its filter input object, and one member
541/// name on each per field — and had no `graphql(…)` word to hang a rename on. Two seats close all
542/// four: the two TYPE names here, and one FIELD name per field, from which the fourth surface
543/// derives. That is the guide's own classification (*a name derived from a base a word already
544/// moves*), and it is what a record does too — its filter slot reads the field's declared wire name
545/// rather than the member's.
546#[derive(Debug, Clone)]
547pub struct WireFace {
548  /// `graphql(rename = "…")` — what a client calls the fragment's own OUTPUT OBJECT.
549  ///
550  /// [`None`] is the fragment's own name, which is what the `#[Object]` block spelled before this
551  /// seat existed.
552  pub object: Option<RustSafeName>,
553  /// `graphql(filter(rename = "…"))` — the BASE the FILTER family's schema names compose off.
554  ///
555  /// # It moves a base, not a name, and #340's twin law is why
556  ///
557  /// A fragment publishes up to TWO input objects — the full field set at a rowless host and the
558  /// stored subset at a row-holding one — and a derived name is composed off the SCHEMA base rather
559  /// than off the Rust ident, so a renamed face carries its twin. `filter(rename = "Dim")` therefore
560  /// publishes `DimFilter` beside `DimColumnFilter`; composing off the ident would have published a
561  /// renamed face beside a twin still wearing the old stem, which is the half-working rename the
562  /// law calls worse than none.
563  ///
564  /// [`None`] is the fragment's own name, which composes to `<Fragment>Filter` — exactly the name
565  /// the composed door minted before the second face existed.
566  ///
567  /// The stored face takes no independent word. What one would be FOR is a schema publishing both
568  /// faces that wants the second called something else, and no consumer has asked — the admission
569  /// bar, 2026-08-22.
570  pub filter: Option<RustSafeName>,
571}
572
573/// A validated fragment: what it is called, how visible it is, and the fields every holder
574/// inherits.
575///
576/// PLAIN, for [`RecordModel`](crate::model::RecordModel)'s reason — public fields, no constructor,
577/// nothing that parses — so the derive today and a manifest front end later build the same one.
578#[derive(Debug, Clone)]
579pub struct FieldsModel {
580  /// The fragment's own name — the declaration this model came from.
581  pub fragment: syn::Ident,
582  /// How visible the fragment is, and therefore how visible each emitted method is.
583  ///
584  /// Mirrored rather than fixed at `pub`, exactly as a record's: no one can widen a type they did
585  /// not declare.
586  pub vis: syn::Visibility,
587  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
588  /// another.
589  ///
590  /// Spent on the PROJECTION traits and on nothing else, which is the whole of what this expansion
591  /// reaches for: a `Vec<_>` field is handed back as a slice through `project::Repeated` and an
592  /// `Option<_>` through `project::Optional`. A fragment that declares neither shape still carries
593  /// the path, because which shapes it has is not a fact the parser makes the root depend on.
594  pub krate: syn::Path,
595  /// `remote = "path::To::Type"` — the FOREIGN TYPE this fragment is a transparent wrapper over, or
596  /// `None` for the ordinary fragment that IS its fields.
597  ///
598  /// The FOURTH declaration to take the word, and the first with NO IDENTITY SEAT. Its presence
599  /// changes what the fields below MEAN — they stop being the fragment's own storage and become a
600  /// MANIFEST, the shape of the wrapped type as this framework needs to read it — while the item
601  /// the compiler sees is `#[repr(transparent)] struct X(Remote);`. What does NOT change is any
602  /// face: the width, the filter, the comparison and the wire object all read the manifest's
603  /// declared types, and a declared type is a declared type whether the value behind it is held or
604  /// wrapped. What moves is the READ, which becomes the remote's own accessor crossed by `Into` —
605  /// see [`crate::remote`], whose core this tier shares with `entity` and `record`.
606  ///
607  /// A `syn::Path` rather than a `syn::Type`, for
608  /// [`RecordModel::remote`](crate::model::RecordModel::remote)'s reason: a wrapper's inner type is
609  /// a named type and nothing else, and the path is EMITTED, so one naming nothing is `E0412` at
610  /// the string the author wrote.
611  pub remote: Option<syn::Path>,
612  /// EVERY field the fragment declares, in declared order.
613  pub fields: Vec<FragmentField>,
614  /// What the declaration said about the way its wrapped type is BUILT — the entry, the finish, the
615  /// blankets and the injections.
616  ///
617  /// [`Construction::default`] where nothing was written, which is the value that makes the words
618  /// free: a declaration writing no `builder(…)` gets the same call the emission wrote before the
619  /// vocabulary existed.
620  pub construction: Construction,
621  /// `delegate(fn …)` — the METHODS reachable on `Self` this fragment restates, and whichever of
622  /// them it also publishes.
623  ///
624  /// # The one door into the emitted object beyond the columns
625  ///
626  /// A fragment's wire face is an `#[Object]` block this emission writes, one field per declared
627  /// column, and a declaration cannot append to it: a second `#[Object] impl Dimensions` is two
628  /// impls of one trait for one type, which is a coherence impossibility rather than a policy. So a
629  /// value with a question its columns do not answer — an aspect ratio, an orientation — has no way
630  /// onto its own face without a seat inside the declaration, and this is that seat.
631  ///
632  /// # ORIGIN is not the word's question
633  ///
634  /// An entry names a method reachable on `Self` and does not ask where it came from — an inherent
635  /// `impl` the author wrote, one the value is reached through by `Deref`, a trait method in scope.
636  /// Both bodies below are method-resolution syntax, so rustc answers, and a name nothing on `Self`
637  /// answers to is `E0599` at the generated call: this family's honesty pattern rather than a rule a
638  /// macro could have checked.
639  ///
640  /// # The MODE forks the EMISSION, and only the emission
641  ///
642  /// | | what a plain entry emits |
643  /// |---|---|
644  /// | a REWRITE ([`remote`](Self::remote) named) | the FORWARDING method — see [`delegate`](Self::delegate), body `(&self.0).m(…)` — because the wrapped value's method is otherwise reachable only through `Deref`, and an inherent one is what a caller and a doc page see |
645  /// | an ORDINARY fragment | **nothing.** The method is already the author's own on `Self`, and a same-named one emitted beside it would be that method calling itself |
646  ///
647  /// So on an ordinary fragment an entry's whole content is the LIFTED half — see
648  /// [`lifted`](Self::lifted), body `Self::m(self)` — and one that publishes nothing there has no
649  /// reader at all, which the front end refuses by name. What it does NOT refuse is the origin.
650  ///
651  /// The LIFTED half is a field of the object in both modes, so it arrives with
652  /// [`wire`](Self::wire).
653  ///
654  /// Empty is the ordinary declaration and costs nothing.
655  pub delegates: Vec<Delegate>,
656  /// `record` / `record(<db>, …)` — the RECORD-HOST activation, or [`None`] where the declaration
657  /// did not write one.
658  ///
659  /// # Activation is REQUIRED, and it is what decides which faces are emitted at all
660  ///
661  /// A fragment is HELD, so what it has to ANSWER is whatever the holding kind asks — and the two
662  /// kinds ask different things. A record asks for a width, a bind, a read and a comparison; an
663  /// entity holds no rows and asks for none of them. A tier that emitted both sets for every
664  /// declaration was answering questions no holder had asked, and the storage answers are the
665  /// expensive half: they are what put `sqlx` in the obligations of a fragment nobody stores.
666  ///
667  /// So the declaration says which kinds may consume it, and a declaration that says NEITHER is a
668  /// named refusal rather than a silent nothing — see `ingraph_derive::fields`. There is no shorthand
669  /// for both: the words are one each, which is the vocabulary-admission bar rather than terseness.
670  ///
671  /// This one gates the STORAGE faces: [`columns`](Self::columns) and its fence, the segment
672  /// [`names`](Self::names), [`carrier`](Self::carrier), [`assemble`](Self::assemble),
673  /// [`keyset`](Self::keyset) and the whole of [`comparison`](Self::comparison).
674  pub record: Option<RecordHost>,
675  /// `entity` — the ENTITY-HOST activation, written bare.
676  ///
677  /// BARE and nothing else, which is a door rather than a hole: entity-hosting has nothing to
678  /// configure yet, so the word activates the read faces and a configuration is a ruling away. The
679  /// tenants are known by name — an election's projection, a fulltext or vector label on an
680  /// entity-hosted field, the keys-tier exposure — and each enters through the admission bar with
681  /// the consumer that spends it. `entity(…)` with anything inside is a named refusal saying so.
682  ///
683  /// It gates the FULL predicate — `<Fragment>Filter`, one slot per DECLARED field — and the marker
684  /// rows a holder resolves a slot through. A record activates a predicate too, and it is a
685  /// DIFFERENT one: `<Fragment>ColumnFilter`, one slot per stored column. *Each face tells its own
686  /// truth*, the 2026-08-22 ruling — a `record(skip)`ped field's value at a record is a raise's
687  /// fill, and filtering a constant is a lying schema, where a rowless host holds the value itself
688  /// and every field it declares is askable.
689  ///
690  /// A declaration writing ONE of the two words emits one type and seats it at both marker rows,
691  /// which is what makes the common case free. One writing both emits both — two consumer worlds,
692  /// two vocabularies.
693  pub entity: bool,
694  /// `graphql` / `graphql(…)` — the WIRE activation, or [`None`] where the declaration wrote none.
695  ///
696  /// It gates [`wire`](Self::wire) whole — the crossing and the `#[Object]` block — and the FILTER's
697  /// own input-object registration, which is the face that makes a holder able to publish a slot of
698  /// this predicate's type. The Rust filter struct is not gated by it: a storage-only fragment is
699  /// still filtered, and what it lacks is a client that can name the filter.
700  pub wire: Option<WireFace>,
701  /// `cursor` / `cursor(a, b)` — the KEY this fragment is a paging position by, or [`None`] where
702  /// the declaration wrote no such word.
703  ///
704  /// # It is an ASSERTION, which is why it is opt-in and why it is a list
705  ///
706  /// A cursor is a position in a TOTAL ORDER, and a group of fields has no order of its own: nothing
707  /// about `{width, height}` says which of two dimensions comes first, and a framework that picked
708  /// one would be minting an answer the declaration never gave. The word is the author saying *the
709  /// order I declared these in is the one legitimate total order over this value* — and the list
710  /// form is the same assertion over a NAMED SUBSET, in the order it names, for the fragment whose
711  /// declaration order is the readable one and whose key order is not.
712  ///
713  /// Empty means the BARE word: every declared field, in declared order.
714  pub cursor: Option<Vec<syn::Ident>>,
715  /// `filter = "path::To::Type"` — the predicate a holder carries at a field that holds this
716  /// fragment, where the declaration MOUNTS one of its own, or [`None`] for the generated one.
717  ///
718  /// # It is a SWAP and not an override, which is why nothing is emitted beside it
719  ///
720  /// The generated filter is one slot per participating field, each guarded by whatever that field's
721  /// type is guarded by — a total, mechanical reading of the declaration. A composite whose
722  /// vocabulary is its own says something the field list cannot: `Dimensions` takes `aspectRatio` and
723  /// `orientation` beside its two columns, and those are questions about the VALUE rather than about
724  /// a column. So the word does not refine the generated filter, it replaces it: the generated one is
725  /// not emitted at all — neither the struct, nor its builders, nor the input face
726  /// [`filter_face`](Self::filter_face) would have registered — and [`CompositeFilterMarker`] names
727  /// the author's type instead.
728  ///
729  /// # It takes BOTH seats, and that is the swap being a swap
730  ///
731  /// The dual-face ruling gives a fragment up to two predicates, and a mounted one replaces the
732  /// pair. The stored seat it takes by necessity — the author's filter carries the author's
733  /// lowering, and a lowering is what the stored face IS — but it takes the full seat too, because
734  /// the alternative is a schema in which one value has two vocabularies from a declaration that
735  /// named one: the author's predicate reachable from a record and a generated one from an entity,
736  /// with no word anywhere saying which is meant. `Dimensions` taking `aspectRatio` is a question
737  /// about the VALUE, which is the rowless face's own subject — so the generated full face is the
738  /// LAST thing an author who wrote this word wants beside it.
739  ///
740  /// What comes with the author's filter is the author's LOWERING. The generated filter's own
741  /// `ToDatabaseComparison<Fragment, Db>` row is what says *this predicate compares this value*, and
742  /// it is a fact about the predicate rather than about the fragment — so a swapped filter states its
743  /// own, naming whatever comparison it lowers into, and states the value-level crossing beside it.
744  /// This emission's comparison is still there to be named: the two layers coexist, and pointing the
745  /// author's row at `<Fragment>Comparison<Db>` is what buys the hand-written face the mechanical
746  /// lowering for free. The EMPTY predicate is not part of that trade — `Default` is a fact about the
747  /// COMPARISON, which is this emission's in both cases — so [`pair`](Self::pair) still writes it.
748  ///
749  /// # It is orthogonal to the ACTIVATIONS, and rides them
750  ///
751  /// The word says WHICH predicate, and the host-kind activation says whether a predicate is emitted
752  /// at all: a fragment no kind can hold has no filter for this to swap, and one that writes
753  /// `graphql` publishes the author's input object rather than a generated one. So a mounted filter
754  /// is read wherever [`filter`](Self::filter) is read and nowhere else.
755  ///
756  /// `marker = …` is NOT this word and is not overloaded into it. A marker answers *what READING is
757  /// this column under* — scalar, string, composite — and every reading a composite has resolves
758  /// through [`CompositeMarker`] to whatever this row names. The two questions are one step apart
759  /// and a word answering both would be a word answering neither.
760  ///
761  /// A [`syn::Path`] for [`remote`](Self::remote)'s reason: it refers to a type this declaration did
762  /// not mint, and the path is EMITTED, so one naming nothing is `E0412` at the string the author
763  /// wrote.
764  ///
765  /// [`CompositeFilterMarker`]: https://docs.rs/ingraph/latest/ingraph/trait.CompositeFilterMarker.html
766  /// [`CompositeMarker`]: https://docs.rs/ingraph/latest/ingraph/struct.CompositeMarker.html
767  pub filter: Option<syn::Path>,
768}
769
770impl FieldsModel {
771  /// The fragment's own API: one accessor family per field, and no framework face beside it.
772  ///
773  /// EVERY field takes the mutators too, and the difference from a record is a consequence rather
774  /// than a choice: a record withholds them from the fields that bear identity, and a fragment has
775  /// no identity-bearing field to withhold them from.
776  ///
777  /// It sits inside the anonymous `const` every other emission here uses, which changes nothing
778  /// about reaching it: an inherent method is found through its type. Uniform rather than argued
779  /// per emission — a reader who knows where a record's impls live knows where these do.
780  ///
781  /// # A REWRITE moves this family and nothing else
782  ///
783  /// With [`remote`](Self::remote) named, the accessor family above is replaced by
784  /// [`readers`](Self::readers) and the wrapper's own two blocks join the const — the BRIDGE
785  /// prelude and the reference family, both [`crate::remote`]'s and neither this tier's own copy.
786  /// The four FACES are untouched: [`columns`](Self::columns), [`filter`](Self::filter),
787  /// [`comparison`](Self::comparison) and [`wire`](Self::wire) all read the manifest's declared
788  /// types, and a declared type does not move when the value behind it starts being wrapped.
789  #[must_use]
790  pub fn emit(&self) -> proc_macro2::TokenStream {
791    let fragment = &self.fragment;
792    let prelude = self
793      .remote
794      .as_ref()
795      .map(|remote| crate::remote::prelude(fragment, remote));
796    let reference = self
797      .remote
798      .as_ref()
799      .map(|remote| crate::remote::family(fragment, remote));
800    let methods = self.methods();
801    // The ORDINALS, minted ONCE at the top of the block every face below is written into: three of
802    // them index a list the predicates CONTRACT — the segment names, the width and the read — and a
803    // constant apiece is what keeps the three reading the same position. An unconditional fragment
804    // gets literals and no constants at all.
805    let (places, at) = self.positions();
806    // THE ACTIVATION FORK, and the whole of it. A face is emitted where a HOST KIND that asks for
807    // it was declared, and nowhere else: the storage answers where a record may hold this fragment,
808    // the predicate where either kind may. A holder that asks for a face its fragment declined gets
809    // the `E0277` naming the trait, at the field that holds one — which is the same discipline every
810    // obligation at this tier already follows.
811    let stored = self.record.is_some();
812    let (places, names, columns, carrier, assemble, cursor) = if stored {
813      (
814        places,
815        self.names(),
816        self.columns(&at),
817        self.carrier(&at),
818        self.assemble(&at),
819        self.keyset(),
820      )
821    } else {
822      Default::default()
823    };
824    // The DECLARED words ride with the width, on the same fork and for the same reason: both are
825    // facts a HOLDER's table needs and a fragment nobody stores has no table to state them for.
826    let words = if stored {
827      self.words()
828    } else {
829      Default::default()
830    };
831    let (comparison, comparison_body) = if stored {
832      self.comparison()
833    } else {
834      Default::default()
835    };
836    let (filter, filter_body) = if stored || self.entity {
837      self.filter()
838    } else {
839      Default::default()
840    };
841    let wire = self.wire();
842    let filter_face = self.filter_face();
843    // THE TRANSFORM PINS, outside the activation fork on purpose: the faces a `write` reaches are
844    // all behind the SQL family's gate, and a declaration's refusals may not depend on a feature
845    // set — see [`transforms`](Self::transforms).
846    let transforms = self.transforms();
847    let pair = if stored {
848      self.pair()
849    } else {
850      Default::default()
851    };
852    quote! {
853      #filter
854      #comparison
855
856      const _: () = {
857        #prelude
858        #reference
859        #methods
860
861        #transforms
862        #places
863        #names
864        #columns
865        #words
866        #carrier
867        #assemble
868        #cursor
869        #filter_body
870        #filter_face
871        #comparison_body
872        #pair
873        #wire
874      };
875    }
876  }
877
878  /// The VALUE-LEVEL crossing and the EMPTY predicate beside it — one pair per DECLARED ∩
879  /// COMPILED-IN dialect, at a CONCRETE backend inside that backend's own gate.
880  ///
881  /// # The two rows a WIRE-FACED HOLDER asks for, and nothing else asks for
882  ///
883  /// A record with a wire face crosses its filter into a database's predicate one column at a time,
884  /// and it writes ONE spelling for every kind of column (see [`crate::emit`]'s crossing):
885  ///
886  /// ```ignore
887  /// let frame = match filter.frame {
888  ///   Some(held) => <Held as TryFromFilter<Sent>>::try_from_filter(held)?,
889  ///   None => Default::default(),        // the client asked nothing: no conjunct
890  /// };
891  /// ```
892  ///
893  /// So a fragment-typed column asks its comparison for exactly two rows — a crossing and an empty
894  /// value — and a fragment that had neither was `E0277` twice at the HOLDER's attribute, naming
895  /// types the holder's author never wrote. Both are measured, and they are the whole of the gap.
896  ///
897  /// # Why it is a CONCRETE backend, and why that is what the DIALECT LIST is for
898  ///
899  /// Every other face here keeps the dialect a parameter and defers its obligations to a `where`
900  /// clause. This pair cannot: a bound whose self type is
901  /// `<F as ToDatabaseComparison<V, Db>>::Comparison` makes rustc resolve the projection through the
902  /// impl that DEFINES it — measured at SEVEN spellings, including the associated-type-bound form,
903  /// two packaging traits and the concrete-self-type form below — so the clause demands
904  /// `sqlx::Database` for most kinds and `CollectionStorage<V>` for a collection, and no one clause
905  /// states both. The same impl at a concrete backend NORMALISES and compiles.
906  ///
907  /// ## The SEVENTH spelling, and the misreading it closes
908  ///
909  /// The seventh was measured on 2026-08-22, because a downstream corpus read the six as having all
910  /// been taken over one wrong shape. The reading was that the emission writes the CROSSING's OWN
911  /// self type as the projection, where a hand-written comparison names its concrete type and owes
912  /// no clause — mediagraph's `impl<Db> TryFromFilter<RateFilter> for SqlRateComparison<Db>`, which
913  /// carries no `Db` bound at all.
914  ///
915  /// **The emission never wrote the projection there.** [`pair`](Self::pair) writes
916  /// `impl TryFromFilter<#filter> for #comparison<#backend>` — the minted name, which this tier
917  /// holds because it minted it ([`comparison_name`](Self::comparison_name)). What is concrete in
918  /// that head is the BACKEND and not the name, and swapping the backend for a parameter was
919  /// measured directly rather than argued:
920  ///
921  /// ```ignore
922  /// impl<DB> TryFromFilter<ProbeColumnFilter> for ProbeComparison<DB>
923  /// where
924  ///   DB: Backend,
925  ///   <<u32 as DefaultMarker>::Marker as ToGraphqlFilter>::ColumnFilter:
926  ///     ToDatabaseComparison<u32, DB>,        // the STRUCT's clause, verbatim
927  /// ```
928  ///
929  /// The struct's clause verbatim is not enough — the body owes two rows the struct does not:
930  /// *this member crosses* and *this member has an empty value*. Both have the projection as their
931  /// SELF TYPE, so stating either is the wall, whatever the impl head says. At `DB: Backend` the
932  /// pair reports the defining impl's whole demand, four errors per member:
933  ///
934  /// ```text
935  /// error[E0271]: type mismatch resolving `<DB as Backend>::Builder<'q> == SqlConjunction<'q, DB>`
936  /// error[E0277]: the trait bound `DB: sqlx::Database` is not satisfied
937  /// error[E0277]: `<DB as Backend>::Buffer` doesn't implement `std::fmt::Display`
938  /// error[E0277]: `u32` has no carrier in `DB`: no column of that dialect can hold one
939  /// ```
940  ///
941  /// which is `comparison::sql::ScalarFilter`'s lowering row restated at the caller. The
942  /// associated-type-bound form of the same two rows reports the identical four.
943  ///
944  /// ## What the corpus's counter-evidence is really about: the MEMBER, not the head
945  ///
946  /// The control compiles, and it is the whole difference. A comparison whose MEMBERS are the
947  /// concrete kind crosses at a bare `Db` exactly as the hand household does, because
948  /// `TryFromFilter<ScalarFilter<D, I>> for SqlScalarComparison<V, Db>` demands `V: TryFrom<D>` and
949  /// nothing of `Db`:
950  ///
951  /// ```ignore
952  /// struct HandComparison<Db> { width: SqlScalarComparison<u32, Db> }   // no `where` clause
953  /// impl<Db> TryFromFilter<HandFilter> for HandComparison<Db> { … }     // compiles, no bound
954  /// ```
955  ///
956  /// This emission cannot hold that member. `comparison::sql` is `#[cfg(feature = "sqlx")]` and the
957  /// comparison is emitted UNGATED into a crate whose feature set this expansion does not know — so
958  /// the member is a projection for the reason [`ToRelatedComparison`]'s note states for its own,
959  /// and reaching a projection-typed member's crossing is what pulls the defining impl's clause in.
960  /// The hand household names concrete kinds because it is written inside its own gate. That is the
961  /// structural difference, and it is not a spelling.
962  ///
963  /// ## The door that IS open, and where it actually leads
964  ///
965  /// Measured beside the refutation: the pair at a generic `Db` compiles once the SQL family's own
966  /// clause is RESTATED at the crossing — `Db: sqlx::Database + for<'q> Backend<Builder<'q> =
967  /// SqlConjunction<'q, Db>, Buffer: Display>, u32: Carrier<Db> + ColumnKind`. So *dialect-generic*
968  /// is reachable, and its price is exactly what this tier's projection exists to avoid paying: the
969  /// clause is the COLUMN KIND's. The same fragment with one collection column, under that same
970  /// clause, reports
971  ///
972  /// ```text
973  /// error[E0277]: the trait bound `DB: CollectionStorage<Vec<u32>, ScalarFilter<u32>>` is not satisfied
974  ///    = note: required for `ListFilter<u32, ScalarFilter<u32>>` to implement `ToDatabaseComparison<Vec<u32>, DB>`
975  /// ```
976  ///
977  /// — *no one clause states both*, measured at this spelling too rather than inherited from the six.
978  ///
979  /// The per-kind clause table that reading called for is **unbuildable, and the reason is one step
980  /// further in**: a projection standing in a `where` clause is not normalised against an obligation
981  /// spelled with the type it resolves to, so such a clause has to name `ScalarFilter<u32>` and
982  /// `ListFilter<u32, ScalarFilter<u32>>` itself — the kind, the element and the element's own filter
983  /// type, read from tokens, at the tier that admits no interpretation word to read a kind off. Where
984  /// the door really leads is [`generic_pair`](Self::generic_pair): with the crossing reached through
985  /// a METHOD there is nothing per-kind left to state, and a concrete backend becomes what a
986  /// declaration BUYS by naming a dialect rather than what it must pay to have a pair at all.
987  ///
988  /// [`ToRelatedComparison`]: https://docs.rs/ingraph/latest/ingraph/trait.ToRelatedComparison.html
989  ///
990  /// A concrete backend also AUDITS: `DimensionsComparison<Sqlite>` is well formed only where every
991  /// component crosses at SQLite, and the corpus has a fragment (`Dimensions { crops: Vec<u32> }`)
992  /// that does not. So the pair cannot be unconditional, and what decides it is the DECLARATION —
993  /// `record(sqlite, postgres)`, the dialects this fragment is BUILT for. That is the whole of what
994  /// `crossing(<db>, …)` was proposed for, arrived at from the activation instead: a word that
995  /// claimed no storage and named a dialect already exists, and this is what it buys.
996  ///
997  /// A fragment that writes the bare `record` names no dialect and takes the OTHER arm — see
998  /// [`generic_pair`](Self::generic_pair), which carries each member's row instead of discharging it,
999  /// and is what every declaration in a downstream corpus of value types reaches.
1000  ///
1001  /// # It walks the PARTICIPATING subset, which at this tier is `stored()`
1002  ///
1003  /// A `record(skip)`ped field is a column of nowhere, so it is not a slot of the filter and not a
1004  /// member of the comparison — the two lists this walk zips — and the crossing must not name it. The
1005  /// per-DIALECT narrowing is refused at the front end for the layout wall, so a dialect's
1006  /// participating subset and the universal list are one list here; the walk is written against the
1007  /// participation rather than against the declaration so that it stays the right walk when they
1008  /// part.
1009  ///
1010  /// The OTHER absence is the `#[cfg]` one, and it cannot be contracted here because a macro cannot
1011  /// evaluate a predicate: the member stays in the list and carries its gate onto BOTH artifacts it
1012  /// reaches — the `let` that crosses it, and the argument that hands it to `Self::new`. Both are
1013  /// attribute positions, which is what makes the pair track a constructor that really loses a
1014  /// parameter. Written without the gate it is `E0061` at the constructor and `E0609` at the
1015  /// filter's member, in a build the declaration's author may never run.
1016  ///
1017  /// # The refusal is BOXED, for the reason a record's undeclared crossing is
1018  ///
1019  /// A fragment names no operand converter — the tier admits no per-dialect rendering word — so every
1020  /// component crosses at the IDENTITY and most of them are provably infallible. Most is not all: a
1021  /// blob's crossing on MongoDB and a duration's on MySQL each refuse on their own terms, and no one
1022  /// type names both. `Box<dyn Error + Send + Sync>` is the type this framework already answers that
1023  /// with, at a record's undeclared cell and at an interface's computed field, and a third family
1024  /// joins rather than minting a fourth spelling.
1025  fn pair(&self) -> proc_macro2::TokenStream {
1026    let dialects: &[BuiltFor] = match self.record.as_ref() {
1027      Some(host) if !host.databases.is_empty() => &host.databases,
1028      // The BARE `record` word: an activation that names no dialect, which is what every
1029      // declaration in a downstream corpus of value types writes. It gets the pair too now, at a
1030      // parameter — see [`generic_pair`](Self::generic_pair) for the seam that makes one impl serve
1031      // every backend at once, and for why the two arms cannot both be emitted.
1032      Some(_) => return self.generic_pair(),
1033      None => return proc_macro2::TokenStream::new(),
1034    };
1035    let comparison = self.comparison_name();
1036    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
1037    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
1038    let boxed = crate::model::boxed_error();
1039    let doc = crate::emit::leading(&format!(
1040      "Cross a wire filter into the predicate a holder compares this {subject}'s columns by — every \
1041       component through its own crossing, and the empty comparison wherever the client asked \
1042       nothing.\n\n# Errors\nWhatever a component's crossing into its stored form refused with. A \
1043       fragment names no operand converter, so most components cross at the identity and cannot \
1044       refuse at all.",
1045      subject = self.subject(),
1046    ));
1047    // NAME AND GATE together, because a `#[cfg]` field really disappears from BOTH walks this pair
1048    // spends it in: a function argument is an attribute position, so `Self::new` loses the argument
1049    // where its column is gone and this call has to lose the same one. `unit::comparison` already
1050    // reads its list that way; a pair that read it any other way was `E0061` at the constructor and
1051    // `E0609` at the filter's member, inside an expansion its author cannot edit.
1052    let members: Vec<(proc_macro2::TokenStream, &syn::Ident)> =
1053      self.laid().map(|one| (one.gate(), one.member())).collect();
1054    // The PRODUCT is minted at every named dialect, mounted or not: `<Fragment>Comparison<Db>` is
1055    // this emission's in both cases, and a mounted lowering that wants the component walk under its
1056    // own vocabulary reaches it by name — which is the same trade a mounted FILTER already takes.
1057    let dialects = dialects.iter().map(|built| {
1058      let kind = built.kind;
1059      let gate = self.framework(&["gate"], &kind.gate().to_string());
1060      let (module, name) = kind.backend();
1061      let backend = self.framework(module, name);
1062      let empty = members
1063        .iter()
1064        .map(|(gate, _)| quote!(#gate ::core::default::Default::default(),));
1065      let legs = self.laid().map(|one| {
1066        let (member, ty) = (one.member(), one.ty());
1067        let gate = one.gate();
1068        let slot = crate::emit::filter_of(&self.krate, ty, None, crate::emit::FilterFace::Column);
1069        // Named through the projection the STRUCT holds rather than through inference, so a
1070        // component whose comparison cannot be built from its filter is `E0277` naming that pair.
1071        let held = quote!(<#slot as #to_comparison<#ty, #backend>>::Comparison);
1072        // THE WRITE-PATH TRANSFORM's second site — see [`operand`](Self::operand). Nothing at all
1073        // where the field wrote no word, which is what keeps every declaration written before the
1074        // seat existed expanding token for token.
1075        let written = self.operand(one, &slot);
1076        quote! {
1077          #gate
1078          let #member = match __ingraph_filter.#member {
1079            ::core::option::Option::Some(__ingraph_held) => {
1080              #written
1081              match <#held as #try_from_filter<#slot>>::try_from_filter(__ingraph_held) {
1082                ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
1083                ::core::result::Result::Err(__ingraph_why) => {
1084                  return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
1085                }
1086              }
1087            }
1088            // The client asked nothing about this component, which is not the same as asking for
1089            // nothing to match: the empty comparison renders no conjunct.
1090            ::core::option::Option::None => ::core::default::Default::default(),
1091          };
1092        }
1093      });
1094      // A MOUNTED filter brings its own crossing, for the reason it brings its own lowering: what a
1095      // predicate becomes is part of what it IS. The EMPTY predicate is not — `Default` is a fact
1096      // about the COMPARISON, which is this emission's in both cases, and an author who points a
1097      // `ToDatabaseComparison` row at it wants exactly that row.
1098      let crossed = self.filter.is_none().then(|| {
1099        let filter = self.column_filter_name();
1100        let legs: Vec<proc_macro2::TokenStream> = legs.collect();
1101        let members = members.iter().map(|(gate, member)| quote!(#gate #member,));
1102        quote! {
1103          #[automatically_derived]
1104          impl #try_from_filter<#filter> for #comparison<#backend> {
1105            type Error = #boxed;
1106
1107            #[doc = #doc]
1108            fn try_from_filter(
1109              __ingraph_filter: #filter,
1110            ) -> ::core::result::Result<Self, Self::Error> {
1111              #(#legs)*
1112              ::core::result::Result::Ok(Self::new(#(#members)*))
1113            }
1114          }
1115        }
1116      });
1117      quote! {
1118        #gate! {
1119          // The EMPTY predicate, which is what a column the client said nothing about lowers to.
1120          // `Self::new` and never a struct literal: the constructor is the comparison's only
1121          // construction path, and a second one here would be a second place the field list lives.
1122          #[automatically_derived]
1123          impl ::core::default::Default for #comparison<#backend> {
1124            #[inline]
1125            fn default() -> Self {
1126              Self::new(#(#empty)*)
1127            }
1128          }
1129
1130          #crossed
1131        }
1132      }
1133    });
1134    quote!(#(#dialects)*)
1135  }
1136
1137  /// **THE SAME PAIR AT A PARAMETER** — one `impl<DB>` covering every backend at once, for the
1138  /// declaration that names no dialect.
1139  ///
1140  /// # What buys it is the crossing being a METHOD, not a clause the emitter knows
1141  ///
1142  /// The arm above is written at a CONCRETE backend because a predicate whose self type is
1143  /// `<F as ToDatabaseComparison<V, DB>>::Comparison` makes rustc resolve the projection through the
1144  /// impl that defines it, and so demands whatever THAT impl demands of the database — the four
1145  /// errors [`pair`](Self::pair) records. Restating each kind's own clause at the crossing does
1146  /// compile; it was measured, on a fixture carrying a scalar, a collection and a nullable member at
1147  /// once. What it costs is that **every type argument in such a clause has to be spelled
1148  /// CONCRETELY**: a projection standing in a `where` clause is not normalised against an obligation
1149  /// spelled with the type it resolves to, so `<<u32 as DefaultMarker>::Marker as
1150  /// ToGraphqlFilter>::ColumnFilter` in the clause leaves `DB: CollectionStorage<Vec<u32>,
1151  /// ScalarFilter<u32>>` unsatisfied and the emitter would have to write `ScalarFilter<u32>` itself.
1152  /// That means knowing each column's KIND, its ELEMENT and that element's filter type from tokens —
1153  /// a hard-coded kind table, at the one tier that admits no interpretation word to read a kind off.
1154  ///
1155  /// `ToCrossedComparison` removes the reason for the table rather than the table's content. Its two
1156  /// methods RETURN the projection instead of naming it in a bound, so nothing normalises; the
1157  /// predicate this emission writes has the FILTER as its self type, which is the shape the struct's
1158  /// own `where` clause already uses.
1159  ///
1160  /// # The `where` clause is the UNION of the members' rows, deduplicated
1161  ///
1162  /// One predicate per member — the member's own kind's row, named rather than inlined — and two
1163  /// members of one type contribute one predicate, because a `where` clause is a set. `DB: Backend`
1164  /// leads it for the reason [`assumptions`](Self::assumptions)'s does; the map row each member
1165  /// needs arrives by ELABORATION off the crossing's supertrait, so it is not written twice.
1166  ///
1167  /// # A fragment holding a fragment closes the same way
1168  ///
1169  /// A nested member's slot is the inner declaration's own minted filter, so this clause names
1170  /// `InnerColumnFilter: ToCrossedComparison<Inner, DB>` — and what discharges it at a real dialect
1171  /// is the inner declaration's own pair, emitted right here by this same arm. The recursion needs
1172  /// nothing of this emission: each level states its members' rows, and the level below proves them.
1173  ///
1174  /// # The two arms are EXCLUSIVE, and that is coherence rather than taste
1175  ///
1176  /// `impl<DB> TryFromFilter<F> for XComparison<DB>` and `impl TryFromFilter<F> for
1177  /// XComparison<Sqlite>` overlap, so a declaration gets one arm or the other and never both. Which
1178  /// one is the DECLARATION's own word: naming a dialect asks for that dialect's concrete pair,
1179  /// which is what audits the fragment against it — `DimensionsComparison<Sqlite>` is well formed
1180  /// only where every component crosses at SQLite — and the bare word asks for the parameter, whose
1181  /// obligations are carried rather than discharged. A declaration that named a dialect therefore
1182  /// expands byte for byte as it did before this arm existed.
1183  ///
1184  /// # What a member no dialect can hold still costs, and where it is reported
1185  ///
1186  /// Nothing here. The clause is an ASSUMPTION at the declaration, exactly as the comparison
1187  /// struct's own is — a fragment holding a collection column compiles, and the record that stores
1188  /// one at a real dialect is where `ToCrossedComparison`'s own refusal is reported, naming the
1189  /// filter kind and the database. One deferral, not two, and it is the discipline
1190  /// [`comparison`](Self::comparison) already documents for the struct.
1191  fn generic_pair(&self) -> proc_macro2::TokenStream {
1192    let comparison = self.comparison_name();
1193    let db = crate::emit::parameter("DB");
1194    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
1195    let to_crossed = self.framework(&["comparison"], "ToCrossedComparison");
1196    let boxed = crate::model::boxed_error();
1197    let clause = self.crossings(&db);
1198    let doc = crate::emit::leading(&format!(
1199      "Cross a wire filter into the predicate a holder compares this {subject}'s columns by — every \
1200       component through its own crossing, and the empty comparison wherever the client asked \
1201       nothing.\n\nONE impl for every backend: this {subject} names no dialect, so its crossing \
1202       carries each component's row rather than discharging it.\n\n# Errors\nWhatever a component's \
1203       crossing into its stored form refused with. A fragment names no operand converter, so most \
1204       components cross at the identity and cannot refuse at all.",
1205      subject = self.subject(),
1206    ));
1207    // The GATE rides both walks, for the reason the concrete arm's does: a `#[cfg]` field is gone
1208    // from the constructor's parameter list and from the filter's members alike, so a leg or an
1209    // argument written for one would name what that build has not got.
1210    let members = self
1211      .laid()
1212      .map(|one| {
1213        let (gate, member) = (one.gate(), one.member());
1214        quote!(#gate #member,)
1215      })
1216      .collect::<Vec<_>>();
1217    let empty: Vec<proc_macro2::TokenStream> = self
1218      .laid()
1219      .map(|one| {
1220        let gate = one.gate();
1221        let (ty, slot) = self.crossing_of(one);
1222        quote!(#gate <#slot as #to_crossed<#ty, #db>>::empty(),)
1223      })
1224      .collect();
1225    let legs = self.laid().map(|one| {
1226      let (gate, member) = (one.gate(), one.member());
1227      let (ty, slot) = self.crossing_of(one);
1228      // THE SAME SECOND SITE at the dialect-generic arm, through the same reader — one function
1229      // spelled once, so the two arms cannot come to spend different ones.
1230      let written = self.operand(one, &slot);
1231      quote! {
1232        #gate
1233        let #member = match __ingraph_filter.#member {
1234          ::core::option::Option::Some(__ingraph_held) => {
1235            #written
1236            match <#slot as #to_crossed<#ty, #db>>::cross(__ingraph_held) {
1237              ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
1238              ::core::result::Result::Err(__ingraph_why) => {
1239                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
1240              }
1241            }
1242          }
1243          // The client asked nothing about this component, which is not the same as asking for
1244          // nothing to match: the empty comparison renders no conjunct.
1245          ::core::option::Option::None => <#slot as #to_crossed<#ty, #db>>::empty(),
1246        };
1247      }
1248    });
1249    // A MOUNTED filter brings its own crossing, for the reason the concrete arm states — and leaves
1250    // the EMPTY predicate here, which is a fact about the comparison rather than about the filter.
1251    let crossed = self.filter.is_none().then(|| {
1252      let filter = self.column_filter_name();
1253      let legs: Vec<proc_macro2::TokenStream> = legs.collect();
1254      let members = members.iter();
1255      quote! {
1256        #[automatically_derived]
1257        impl<#db> #try_from_filter<#filter> for #comparison<#db>
1258        where
1259          #clause
1260        {
1261          type Error = #boxed;
1262
1263          #[doc = #doc]
1264          fn try_from_filter(
1265            __ingraph_filter: #filter,
1266          ) -> ::core::result::Result<Self, Self::Error> {
1267            #(#legs)*
1268            ::core::result::Result::Ok(Self::new(#(#members)*))
1269          }
1270        }
1271      }
1272    });
1273    quote! {
1274      #[automatically_derived]
1275      impl<#db> ::core::default::Default for #comparison<#db>
1276      where
1277        #clause
1278      {
1279        #[inline]
1280        fn default() -> Self {
1281          Self::new(#(#empty)*)
1282        }
1283      }
1284
1285      #crossed
1286    }
1287  }
1288
1289  /// **THE WRITE-PATH TRANSFORM AT ITS SECOND SITE** — the client's operand through the same
1290  /// function the bind spends, or nothing at all where no word was written.
1291  ///
1292  /// # It is the operand MAP, which is the seam the framework already crosses declared converters
1293  /// through
1294  ///
1295  /// [`TryMapFilter`] is *this kind carrying `V` where `Self` carries `D`, with every operand
1296  /// converted and the operator set untouched*, and it is how a record's own
1297  /// `graphql(input(comparison(<db>(into = "…"))))` reaches a filter it knows only as a type
1298  /// parameter. A write transform is that seam at `D = V = T`: the operands are the field's own type
1299  /// going in and coming out, so [`Mapped`] normalises back to the slot the crossing then reads. One
1300  /// call, no per-kind table, and nothing about it is this tier's own invention.
1301  ///
1302  /// # The obligation is CONCRETE, so it audits at the declaration
1303  ///
1304  /// The slot is a projection over the field's own written type and the row names no database, so
1305  /// the bound resolves eagerly in both arms and needs no `where` clause in either — which is also
1306  /// what makes a field whose kind has no map refuse where a reader can act on it. The kinds
1307  /// without one are the framework's documented absences: a boolean and a duration carry no operand
1308  /// parameter, a collection's elements are stored as something a collection is not, and a
1309  /// COMPOSITE column's predicate is per-column and holds no whole-value operand for a
1310  /// `fn(&T) -> T` to touch. Each is `E0277` naming [`TryMapFilter`] and the kind, at the
1311  /// declaration that wrote the word.
1312  ///
1313  /// # The refusal road is the crossing's own
1314  ///
1315  /// The map is fallible in the trait and infallible here — a `fn(&T) -> T` has nowhere to refuse —
1316  /// so the error type is fixed to the crossing's own boxed one and the arm it produces is
1317  /// unreachable rather than absent. One error type through the whole body is what keeps the two
1318  /// arms' bodies the shape they already had.
1319  ///
1320  /// [`TryMapFilter`]: https://docs.rs/ingraph/latest/ingraph/trait.TryMapFilter.html
1321  /// [`Mapped`]: https://docs.rs/ingraph/latest/ingraph/trait.TryMapFilter.html#associatedtype.Mapped
1322  fn operand(&self, one: Laid<'_>, slot: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1323    let Some(write) = self.write_of(one) else {
1324      return proc_macro2::TokenStream::new();
1325    };
1326    let ty = one.ty();
1327    let try_map = self.framework(&["graphql"], "TryMapFilter");
1328    let boxed = crate::model::boxed_error();
1329    quote! {
1330      let __ingraph_held = match <#slot as #try_map<#ty, #ty>>::try_map_filter(
1331        __ingraph_held,
1332        |__ingraph_operand| ::core::result::Result::<#ty, #boxed>::Ok(#write(&__ingraph_operand)),
1333      ) {
1334        ::core::result::Result::Ok(__ingraph_written) => __ingraph_written,
1335        ::core::result::Result::Err(__ingraph_why) => {
1336          return ::core::result::Result::Err(__ingraph_why);
1337        }
1338      };
1339    }
1340  }
1341
1342  /// **THE TRANSFORM PINS** — one NAMED `const` per declared transform, typed `fn(&T) -> T` and
1343  /// never called here.
1344  ///
1345  /// # The derived seat's device, one shape in
1346  ///
1347  /// `ingraph::derived` takes the function as an ARGUMENT it never calls, because a `ColumnShape`
1348  /// had to be built anyway and a parameter typed `fn(&S) -> T` is what holds `from` and
1349  /// `type = "…"` together. A transform builds no artifact, so there is nothing for a function to be
1350  /// an argument OF — and the pin is then a `const`'s own TYPE, measured against the alternatives:
1351  ///
1352  /// | spelling | what it reports | why not |
1353  /// |---|---|---|
1354  /// | a NAMED `const: fn(&T) -> T` the two sites SPELL | `E0308` on a wrong signature, `E0433` on a path naming nothing, ONCE, at the author's own string | — |
1355  /// | an anonymous `const _: fn(&T) -> T = path;` beside two sites naming the path | the same two, and then the bind's and the operand map's own — **four errors for one mistake**, measured | one mistake told once is this family's own rule |
1356  /// | a framework `const fn written<T>(_: fn(&T) -> T)` | the same as the first | a public function whose whole body is `{}`, added to the shelf for one call site |
1357  /// | nothing, and let the BIND report | the same `E0308`, but only in a build compiling an SQL family | a declaration is a fixed text, so its refusal may not depend on a feature set |
1358  ///
1359  /// The last row is what makes a pin necessary at all: every face this word reaches is behind
1360  /// `if_sqlx!` — the bind is, and so are both crossing arms — so a build with no SQL family
1361  /// compiled would accept a `write` naming a function that does not exist, and the author would
1362  /// learn about it from somebody else's build.
1363  ///
1364  /// # The name is what makes ONE FUNCTION, TWO SITES a fact rather than a habit
1365  ///
1366  /// The bind and the crossing's query operand both spell this `const` rather than the author's
1367  /// path, so the two sites cannot come to spend different functions: there is one definition and
1368  /// two readers, which is the arrangement [`names`](Self::names) already uses for the segment names
1369  /// and for the same reason. It is also what collapses the diagnostic — the sites are typed by the
1370  /// const, so a wrong signature is reported where the declaration named it and nowhere else.
1371  ///
1372  /// # `fn(&T) -> T` is the SHAPE, and it is the hand household's method read as a path
1373  ///
1374  /// `Rate::reduced(&self) -> Rate` is a `fn(&Rate) -> Rate` when named as a path, so the discipline
1375  /// this seat replaces is spellable without the author changing a line of it. The elided lifetime
1376  /// in a function-pointer type is higher-ranked, so the pin admits a function borrowing for any
1377  /// lifetime and demands nothing about where the value came from.
1378  ///
1379  /// # It is indexed by the DECLARED ordinal, for the reason the segment names are
1380  ///
1381  /// A `const` apiece has to be NAMED and the only name available is the field's own, upper-cased —
1382  /// and `myField` and `my_field` upper-case to ONE identifier, so two legal fields would mint one
1383  /// `const` inside an expansion its author cannot edit. A position cannot collide. The GATE rides
1384  /// each pin and each spend alike, so a build whose predicate removed the field removed the
1385  /// transform with it.
1386  fn transforms(&self) -> proc_macro2::TokenStream {
1387    let mut pins = proc_macro2::TokenStream::new();
1388    // THE HEAD's OWN PAIR FIRST — `fn(&Self) -> Self` rather than `fn(&T) -> T`, and NOT indexed:
1389    // there is one head, so the name is the whole of it. No gate rides them either, a `#[cfg]` being
1390    // a FIELD's word and the head being whatever the build kept.
1391    let fragment = &self.fragment;
1392    for (name, path) in [
1393      (Self::HEAD_WRITE, self.head_write()),
1394      (Self::HEAD_READ, self.head_read()),
1395    ] {
1396      let Some(path) = path else {
1397        continue;
1398      };
1399      let name = format_ident!("{name}");
1400      let spanned = quote_spanned!(path.span() => #path);
1401      pins.extend(quote! {
1402        const #name: fn(&#fragment) -> #fragment = #spanned;
1403      });
1404    }
1405    for (ordinal, field) in self.fields.iter().enumerate() {
1406      let (gate, ty) = (field.condition.gate(), &field.column.ty);
1407      for (word, path) in [
1408        ("WRITE", field.write.as_ref()),
1409        ("READ", field.read.as_ref()),
1410      ] {
1411        let Some(path) = path else {
1412          continue;
1413        };
1414        let name = Self::transform_name(word, ordinal);
1415        let spanned = quote_spanned!(path.span() => #path);
1416        pins.extend(quote! {
1417          #gate
1418          const #name: fn(&#ty) -> #ty = #spanned;
1419        });
1420      }
1421    }
1422    pins
1423  }
1424
1425  /// What the pin for one field's transform is CALLED — the name both of its sites spell.
1426  fn transform_name(word: &str, ordinal: usize) -> syn::Ident {
1427    format_ident!("__INGRAPH_FRAGMENT_{word}_{ordinal}")
1428  }
1429
1430  /// The HEAD's write pin — the name every site that carries this value INTO storage spells.
1431  const HEAD_WRITE: &'static str = "__INGRAPH_FRAGMENT_HEAD_WRITE";
1432
1433  /// The HEAD's read pin — the name every site that carries this value BACK spells.
1434  const HEAD_READ: &'static str = "__INGRAPH_FRAGMENT_HEAD_READ";
1435
1436  /// **THE WHOLE-VALUE WRITE TRANSFORM** — `fields(record(write = "…"))`, or [`None`].
1437  ///
1438  /// # What it is for, and why the field seat could not be widened into it
1439  ///
1440  /// The field seat is `fn(&T) -> T` over ONE column's type, and a canonical form that reads several
1441  /// columns has no such function. Reducing a rational divides BOTH halves by their common factor,
1442  /// so `num`'s stored value depends on `den` — there is no `fn(&u32) -> u32` that reduces a
1443  /// numerator, and a per-field word that pretended otherwise would be silently wrong on the day the
1444  /// other half changed. `fn(&Self) -> Self` is the hand household's own shape read as a path:
1445  /// `Rate::reduced(&self) -> Rate` needs no line rewritten to be named here.
1446  ///
1447  /// # ONE FUNCTION, EVERY SITE THE VALUE CROSSES — and the census that says which those are
1448  ///
1449  /// | emitted face | holds a whole `Self`? | spends the word |
1450  /// |---|---|---|
1451  /// | [`carrier`](Self::carrier) — the bind | yes, `&self` | **yes** |
1452  /// | [`keyset`](Self::keyset) — `write_cursor` | yes, `&self` | **yes**, where `cursor` was written |
1453  /// | [`assemble`](Self::assemble) — the raise | yes, the built value | the READ mirror |
1454  /// | [`keyset`](Self::keyset) — `read_cursor` | yes, the built value | the READ mirror |
1455  /// | [`pair`](Self::pair) / [`generic_pair`](Self::generic_pair) — the crossing | **no** | — |
1456  /// | [`wire`](Self::wire) — the object | `&self`, but publishes | no: a transform publishes nothing |
1457  ///
1458  /// The bind and the cursor's write are a genuine TWO-SITE agreement rather than one site written
1459  /// twice, and forgetting either is silent in the worst direction: a keyset boundary written from
1460  /// the declared spelling resumes against columns holding the canonical one, so a page repeats rows
1461  /// or drops them. That is the paging twin of the `eq` miss the field seat exists to kill, and it is
1462  /// why the hand household spends `Rate::reduced()` at its own `CursorValue` as well as at its own
1463  /// `Carrier`.
1464  ///
1465  /// # THE CROSSING IS NOT A SITE, and the reason is arithmetic rather than deferral
1466  ///
1467  /// Measured 2026-08-24, against the emission rather than argued: a fragment's predicate is one
1468  /// `Option<component filter>` per COLUMN ([`crate::unit::filter`]), and both crossing arms consume
1469  /// it member by member — `__ingraph_filter.#member` and nothing else. There is no whole `Self`
1470  /// anywhere in `try_from_filter` for a `fn(&Self) -> Self` to be applied to, and no per-column
1471  /// action to push the word down into either: under a reduction, `num = 2` is not `num = 1` — it is
1472  /// *`num = 2/g` where `g` divides the pair*, a relation over two columns rather than a function of
1473  /// one. The framework's own `TryMapFilter` says the same thing from the other side, which is why
1474  /// the FIELD word on a holder's composite column is `E0277` today.
1475  ///
1476  /// What that leaves is honest and stated rather than papered over: after a head write the STORED
1477  /// face asks about the stored columns, which is the whole of what `<Fragment>ColumnFilter` claims
1478  /// to be — *a predicate over the STORED COLUMNS of a fragment*. A declaration whose clients must
1479  /// ask in DOMAIN terms mounts a whole-value predicate and its lowering, `filter = "…"` beside
1480  /// `record(<db>(comparison = "…"))`, which is the seat pair built for exactly that and the road the
1481  /// macro-parity pilot already takes.
1482  fn head_write(&self) -> Option<&syn::Path> {
1483    self.record.as_ref()?.write.as_ref()
1484  }
1485
1486  /// **THE WHOLE-VALUE READ MIRROR** — `fields(record(read = "…"))`, or [`None`] for the identity.
1487  ///
1488  /// Admitted because the raise side is SYMMETRIC, which the same census establishes: [`assemble`]
1489  /// and the cursor's read each build a whole `Self` and then hand it back, so one function has the
1490  /// same two sites coming out that [`head_write`](Self::head_write) has going in. It runs LAST in
1491  /// both, on the value the columns rebuilt.
1492  ///
1493  /// # The fallible raise, stated rather than invented
1494  ///
1495  /// A wrapped fragment (`remote = "…"` with a `fallible` protocol) rebuilds through the wrapped
1496  /// type's own constructor, and its `Err` leaves [`assemble`] before there is a value at all — so
1497  /// the mirror never runs on a refused row, and this word adds no error road of its own. The
1498  /// cursor's read cannot reach that question at all: a `fallible` protocol beside `cursor` is
1499  /// refused at the declaration, `read_cursor` answering an [`Option`] with no road for an `Err`.
1500  ///
1501  /// [`assemble`]: Self::assemble
1502  fn head_read(&self) -> Option<&syn::Path> {
1503    self.record.as_ref()?.read.as_ref()
1504  }
1505
1506  /// **THE HEAD WRITE'S SPEND**, as the two things a site needs: the statement that runs the
1507  /// function, and the RECEIVER every column expression then reads its value off.
1508  ///
1509  /// `self` and no statement where the declaration wrote no word, so a fragment without one expands
1510  /// byte for byte as it did before this seat existed.
1511  ///
1512  /// # ONE call, however many columns
1513  ///
1514  /// The alternative — spelling `HEAD_WRITE(self).num` at each column — runs a household's own method
1515  /// once per column, and nothing promises it is cheap: a reduction computes a gcd. So the value is
1516  /// bound once and reborrowed, which also makes the *one function, two sites* claim visible as one
1517  /// line per site rather than as a call buried in each column's expression.
1518  ///
1519  /// The second `let` is what keeps [`held`](Self::held) unmoved: a `&Self` receiver spells a place
1520  /// and a call exactly as `self` does, so the two sites differ from the un-transformed emission in
1521  /// their PROLOGUE alone.
1522  fn written(&self) -> (proc_macro2::TokenStream, syn::Ident) {
1523    let (whole, pin) = (format_ident!("__ingraph_whole"), Self::HEAD_WRITE);
1524    match self.head_write() {
1525      None => (proc_macro2::TokenStream::new(), format_ident!("self")),
1526      Some(_) => {
1527        let pin = format_ident!("{pin}");
1528        (
1529          quote! {
1530            let #whole: Self = #pin(self);
1531            // A build whose PREDICATES removed every column removed every reader with them, and a
1532            // prologue nobody reads is `unused_variables` inside an expansion its author cannot
1533            // edit. The first binding is always read by the second, so one allow covers the pair.
1534            #[allow(unused_variables)]
1535            let #whole: &Self = &#whole;
1536          },
1537          whole,
1538        )
1539      }
1540    }
1541  }
1542
1543  /// **THE HEAD READ'S SPEND** — the value a raise hands back, through the mirror or as it stands.
1544  ///
1545  /// Applied to the BUILT value rather than to the fetched columns, which is the whole difference
1546  /// between this and the field seat: a `fn(&Self) -> Self` needs a `Self`, and the earliest one a
1547  /// read has is the one the struct literal or the construction protocol just produced.
1548  fn raised(&self, built: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1549    match self.head_read() {
1550      None => built,
1551      Some(_) => {
1552        let pin = format_ident!("{}", Self::HEAD_READ);
1553        quote!(#pin(&#built))
1554      }
1555    }
1556  }
1557
1558  /// The WRITE pin this column's value is bound and compared through, or [`None`] where the field
1559  /// wrote no word and for a DERIVED column.
1560  ///
1561  /// # A derived column is not transformed, and the types are what say so
1562  ///
1563  /// `write` is a `fn(&T) -> T` over the FIELD's own type and `from` is a `fn(&Self) -> U` over the
1564  /// whole value, so a derived column's type is `U` and the source field's transform does not take
1565  /// one: applying it would be `E0308` wherever the two differ and an arbitrary choice on the day
1566  /// they coincide. The function ALSO sees the value as DECLARED — `from` reads `&Self`, and there
1567  /// is no `Self` with one field replaced for it to read instead, short of rebuilding the value
1568  /// through a `Clone` this tier never asked for.
1569  ///
1570  /// So the rule is forced rather than chosen: **a derived column's `from` sees the domain value,
1571  /// and what it returns is stored as it stands.** A declaration wanting the canonical form computes
1572  /// it inside `from`, which holds the whole value and can call the same function the word named.
1573  ///
1574  /// # The ordinal is found by NAME
1575  ///
1576  /// A struct's fields are uniquely named, and the two artifacts that spell this pin are written by
1577  /// different walks — the bind and the read walk columns, the pins walk the declaration — so the
1578  /// ordinal is resolved rather than carried, off the one key both walks already have.
1579  fn write_of(&self, one: Laid<'_>) -> Option<syn::Ident> {
1580    let field = one.declared()?;
1581    field.write.as_ref()?;
1582    let ordinal = self
1583      .fields
1584      .iter()
1585      .position(|other| other.column.name == field.column.name)?;
1586    Some(Self::transform_name("WRITE", ordinal))
1587  }
1588
1589  /// One member's (storage type, filter slot) pair, spelled the way every other face here spells it.
1590  ///
1591  /// One reader for the two emissions that write a member's crossing — the struct's assumptions and
1592  /// the dialect-generic pair — because a slot resolved twice is a slot two answers can disagree
1593  /// about, and between those two there is no conversion.
1594  fn crossing_of<'a>(&self, one: Laid<'a>) -> (&'a syn::Type, proc_macro2::TokenStream) {
1595    let ty = one.ty();
1596    (
1597      ty,
1598      crate::emit::filter_of(&self.krate, ty, None, crate::emit::FilterFace::Column),
1599    )
1600  }
1601
1602  /// What a DIALECT-GENERIC crossing over these fields assumes: that the database is a `Backend`,
1603  /// and that each member's filter kind CROSSES at it.
1604  ///
1605  /// The union of the members' rows, deduplicated by spelling — two members of one type ask one
1606  /// question, and a `where` clause repeating it says nothing more. The map row
1607  /// [`assumptions`](Self::assumptions) states arrives here by elaboration off the crossing's
1608  /// supertrait, so this clause is not that one plus something: it is that one, refined.
1609  fn crossings(&self, db: &syn::Ident) -> proc_macro2::TokenStream {
1610    let backend = self.framework(&["comparison"], "Backend");
1611    let to_crossed = self.framework(&["comparison"], "ToCrossedComparison");
1612    let mut seen: Vec<String> = Vec::new();
1613    let mut rows = proc_macro2::TokenStream::new();
1614    for one in self.laid() {
1615      let (ty, slot) = self.crossing_of(one);
1616      let row = quote!(#slot: #to_crossed<#ty, #db>,);
1617      let spelling = row.to_string();
1618      if seen.iter().any(|kept| kept == &spelling) {
1619        continue;
1620      }
1621      seen.push(spelling);
1622      rows.extend(row);
1623    }
1624    quote! {
1625      #db: #backend,
1626      #rows
1627    }
1628  }
1629
1630  /// Every field that is a COLUMN — the ones a `record(skip)` did not take out, in declared order.
1631  ///
1632  /// The participation walk EVERY storage face takes, and the filter with them: the ruled law is
1633  /// that each face walks its own set from one declaration, and the predicate's set is the union of
1634  /// storage participation — a field with no column anywhere has nothing for a slot to compare.
1635  ///
1636  /// The absence is STATIC rather than conditional, so it contracts the list here rather than at the
1637  /// compiler: `record(skip)` is a word, and a word a macro can read is one it may act on. What the
1638  /// predicates contract is a different list — see [`positions`](Self::positions), which runs over
1639  /// this one.
1640  fn stored(&self) -> impl Iterator<Item = &FragmentField> {
1641    self.fields.iter().filter(|field| field.skip.is_none())
1642  }
1643
1644  /// The LAYOUT — every column this fragment publishes, declared and derived alike, in the order it
1645  /// occupies.
1646  ///
1647  /// # THE POSITION RULE, in one sentence
1648  ///
1649  /// **A derived column follows the field it is derived from**, and several on one field follow in
1650  /// the order they were written. So the layout is [`stored`](Self::stored) with each field's own
1651  /// derived columns spliced in immediately behind it, and a reader counts FIELDS rather than doing
1652  /// arithmetic: the source's columns and the columns computed from them read together, wherever the
1653  /// source sits.
1654  ///
1655  /// The alternative was a tail — every derived column after every declared one — and it loses the
1656  /// one thing this rule buys. A fragment deriving a canonical unit off each of two timestamps would
1657  /// lay out `start · end · start_nanos · end_nanos` under a tail rule and
1658  /// `start · start_nanos · end · end_nanos` under this one, and only the second reads as *this
1659  /// column, and what is computed from it* in a `CREATE TABLE` a human has to check against a
1660  /// hand-written household's.
1661  ///
1662  /// A SKIPPED field contributes nothing and neither does anything derived off one — the two words
1663  /// are refused together at the front end, so the case never reaches here.
1664  fn laid(&self) -> impl Iterator<Item = Laid<'_>> {
1665    self.stored().flat_map(|field| {
1666      core::iter::once(Laid::Declared(field)).chain(field.derived.iter().map(move |column| {
1667        Laid::Derived {
1668          source: field,
1669          column,
1670        }
1671      }))
1672    })
1673  }
1674
1675  /// The POSITIONS this fragment's field list occupies once the compiler has answered its fields'
1676  /// predicates — the running sum, and the names to index with.
1677  ///
1678  /// [`crate::emit::positions`]'s arithmetic over this tier's own list, which is the same arithmetic
1679  /// a record's row runs: a `#[cfg]` field's entry is a real array element, so a build that removes
1680  /// the second field makes the third's position `1`, and an expansion that wrote `2` would name a
1681  /// position that build has not got.
1682  fn positions(&self) -> (proc_macro2::TokenStream, Vec<proc_macro2::TokenStream>) {
1683    let declared: Vec<Option<&Condition>> = self.laid().map(|one| Some(one.condition())).collect();
1684    crate::emit::positions(&declared)
1685  }
1686
1687  /// Whether ANY field of this fragment is conditional.
1688  ///
1689  /// The switch between the two shapes the separator below is written in, and the one thing that
1690  /// decides whether this tier's expansion is byte for byte the one it was before the seat existed.
1691  fn conditional(&self) -> bool {
1692    self.stored().any(|field| !field.condition.always_present())
1693  }
1694
1695  /// The fragment's INHERENT impl — the accessor family per field, or a rewrite's readers.
1696  ///
1697  /// One fork, at the one seam a rewrite moves: what a value is READ FROM. Everything the emission
1698  /// does with the result is the same on both sides.
1699  fn methods(&self) -> proc_macro2::TokenStream {
1700    let fragment = &self.fragment;
1701    if self.remote.is_some() {
1702      return self.readers();
1703    }
1704    let families = self.fields.iter().map(|field| {
1705      let column = &field.column;
1706      // The CONDITION, on the reader family of the field that wrote it: the echoed field really
1707      // disappears under the predicate, so an ungated accessor would be `E0615` on a method reading
1708      // a field that is not there. The record family's own line, at this tier.
1709      column.methods(
1710        &self.vis,
1711        &self.krate,
1712        &format!("`{}` field of this [`{fragment}`]", column.name),
1713        true,
1714        &field.condition.gate(),
1715      )
1716    });
1717    quote! {
1718      impl #fragment {
1719        #(#families)*
1720      }
1721    }
1722  }
1723
1724  /// A REWRITE's inherent impl: ONE reader per manifest field, and nothing beside it.
1725  ///
1726  /// # NO IDENTITY SEAT, and that is the whole difference from the rung above
1727  ///
1728  /// A record's rewrite splits its family on `identity` — an id column gets the BORROW, because
1729  /// this framework's identity seats borrow, and a data column gets the crossed value. A fragment
1730  /// bears no id, so every one of its fields is on the data side and the split has one branch: one
1731  /// by-value reader per field, no `_ref`, no `id_ref`, and no borrow anywhere in the tier. That is
1732  /// the tier's own definition doing the work rather than a narrowing chosen here — the `id` word
1733  /// is refused at the fragment's front end, so an identity-bearing manifest field cannot reach
1734  /// this walk at all.
1735  ///
1736  /// # No mutators and no `const`, for the rewrite's own two reasons
1737  ///
1738  /// A remote's fields are its own, so nothing here can assign into one and a `with_…` that rebuilt
1739  /// the whole value would be a constructor wearing a setter's name; and the body calls a FOREIGN
1740  /// accessor, which is not this emission's to declare `const`. Both are
1741  /// [`RecordModel::remote_methods`](crate::model::RecordModel)'s sentences, and they hold here
1742  /// unchanged.
1743  ///
1744  /// # The PROJECTION word decides nothing here
1745  ///
1746  /// `copy`, `repeated` and `optional` each name a way an accessor hands a HELD field back — by
1747  /// value beside its borrow, as a slice, as an `Option<&_>` — and every one of those is a borrow
1748  /// of storage this type does not have. A crossed value is owned, so the reader is the same shape
1749  /// whatever the word says, exactly as a record's rewritten data column ignores it.
1750  ///
1751  /// # The field's own doc comments ride the reader
1752  ///
1753  /// They were written about a field the rewrite DELETES, and the reader is where that field's
1754  /// question is still askable. The generated line follows them, so an author's sentence is read
1755  /// first and this emission's second.
1756  fn readers(&self) -> proc_macro2::TokenStream {
1757    let fragment = &self.fragment;
1758    let vis = &self.vis;
1759    // The SEAT's forwarding half, for every entry that did not waive it. `on = self` is that waiver
1760    // — see [`delegate`](Self::delegate) for what the word is FOR — and an entry carrying it reaches
1761    // this walk exactly as an ordinary fragment's does: nothing minted, the method the author's.
1762    let delegates = self
1763      .delegates
1764      .iter()
1765      .filter(|delegate| delegate.on_self.is_none())
1766      .map(|delegate| self.delegate(delegate));
1767    let cross = crate::remote::cross();
1768    let readers = self.fields.iter().map(|field| {
1769      let column = &field.column;
1770      let (name, source, ty) = (&column.name, &column.source, &column.ty);
1771      let docs = &field.docs;
1772      let at = source.span();
1773      let doc = crate::emit::leading(&format!("The `{name}` field of this [`{fragment}`]."));
1774      // The READER is the manifest field's STAND-IN, so it takes both halves of the condition: the
1775      // `#[cfg]`, because a build without the field has no reader to answer with, and the
1776      // `#[cfg_attr]`s beside the doc comments, for the reason those migrate here — the field they
1777      // decorated is deleted, and this is the one artifact left that stands for it.
1778      let gate = field.condition.gate();
1779      let decorations = field.condition.decorations();
1780      // SPANNED at the manifest field, so a remote with no such accessor — or one whose return type
1781      // does not cross — reports at the line the author would fix rather than at the attribute.
1782      let read = quote_spanned!(at=> #cross(self.0.#source()));
1783      quote! {
1784        #gate
1785        #(#docs)*
1786        #(#decorations)*
1787        #[doc = #doc]
1788        #[inline]
1789        #vis fn #name(&self) -> #ty {
1790          #read
1791        }
1792      }
1793    });
1794    quote! {
1795      impl #fragment {
1796        #(#readers)*
1797        #(#delegates)*
1798      }
1799    }
1800  }
1801
1802  /// ONE `delegate(fn …)` entry, forwarded onto the value this declaration wraps — the REWRITE
1803  /// mode's half of the seat, and reached from [`readers`](Self::readers) alone.
1804  ///
1805  /// An ordinary fragment mints no such method: the one it would call is the author's own on `Self`,
1806  /// and a same-named one emitted beside it would be that method calling itself. What the entry
1807  /// buys THERE is the lifted field and nothing else — see
1808  /// [`Delegate::on_self`](crate::delegate::Delegate::on_self) for the word that asks for the same
1809  /// thing here, and [`lifted`](Self::lifted) for the body that does the reaching.
1810  ///
1811  /// # `on = self` — the entry the mode mints for and the author did not want minted
1812  ///
1813  /// The forwarding body calls the method on the WRAPPED value, which is right for the case the mode
1814  /// exists to serve and wrong for exactly one: a method the author wrote on the WRAPPER. There the
1815  /// mint is `E0599` — the wrapped type has no such method — or, where the author's own inherent one
1816  /// is beside it, `E0592` for the duplicate, and neither report is answerable from the declaration's
1817  /// own tokens. `on = self` is the word that skips this walk for that entry, leaving the author's
1818  /// method where they wrote it. The LIFTED half is untouched: its body is `Self::m(self)`, which
1819  /// resolves to the author's method exactly as it resolves to a minted one.
1820  ///
1821  /// The declaration writes the SIGNATURE and this writes the body, which is the only division Rust
1822  /// admits: a forwarding method needs a written return type, there is no `typeof`, and the wrapped
1823  /// type is one this side cannot look inside. That is the vocabulary mirror's own sentence and it
1824  /// holds here unchanged — the seat is one grammar and this is the second declaration to spend it.
1825  ///
1826  /// The call is METHOD-CALL syntax rather than a qualified path, and that is what makes the seat
1827  /// worth having: an inherent method of the wrapped type, one it reaches through its own `Deref`,
1828  /// and a trait method in scope all resolve, with no word here for a declaration to have to know
1829  /// which. A name the wrapped type has not got is `E0599` at the body, naming that type.
1830  ///
1831  /// The VISIBILITY is the fragment's, and it is not the declaration's to write: a [`syn::Signature`]
1832  /// carries none, which is the restatement being exactly a signature rather than an item.
1833  ///
1834  /// # TWO RECEIVERS, and only one of them costs anything at this tier
1835  ///
1836  /// A mirror stores a WORD, so `&mut self` there means materialise, mutate and convert home — two
1837  /// conversions a call, which its own doc records. A wrapper HOLDS the value: `&mut self` reaches
1838  /// `self.0` directly and mutates it in place, at no conversion at all. The receiver still forks the
1839  /// body, because a shared one may not hand out an exclusive borrow; what it does not fork is the
1840  /// cost. A consuming `self` and a receiverless signature are refused at the DOOR.
1841  fn delegate(&self, delegate: &Delegate) -> proc_macro2::TokenStream {
1842    let vis = &self.vis;
1843    let fragment = &self.fragment;
1844    let signature = &delegate.signature;
1845    let method = &signature.ident;
1846    let arguments = signature.inputs.iter().skip(1).filter_map(|argument| {
1847      let syn::FnArg::Typed(typed) = argument else {
1848        return None;
1849      };
1850      match typed.pat.as_ref() {
1851        syn::Pat::Ident(bound) => Some(bound.ident.clone()),
1852        _ => None,
1853      }
1854    });
1855    // SPANNED at the restated name, so a method the wrapped type has not got reports at the entry
1856    // the author would fix rather than at the attribute that opened the block.
1857    let at = method.span();
1858    let held = if delegate.exclusive {
1859      quote_spanned!(at=> (&mut self.0))
1860    } else {
1861      quote_spanned!(at=> (&self.0))
1862    };
1863    let body = quote_spanned!(at=> #held.#method(#(#arguments),*));
1864    let doc = format!(
1865      "Forwarded to the value this [`{fragment}`] wraps.{extra}",
1866      extra = if delegate.exclusive {
1867        " \n\nThe mutation lands on the wrapped value itself: a wrapper HOLDS what it forwards to, \
1868          so an exclusive receiver costs no conversion — which is the one place this seat differs \
1869          from a vocabulary mirror's, where the upstream is materialized from a stored word."
1870      } else {
1871        ""
1872      },
1873    );
1874    quote! {
1875      #[doc = #doc]
1876      #[inline]
1877      #vis #signature {
1878        #body
1879      }
1880    }
1881  }
1882
1883  /// The WIRE face: the fragment's own output OBJECT, and the crossing that reaches it.
1884  ///
1885  /// # An object, and still not a ROOT
1886  ///
1887  /// The old refusal's sentence is the SIGNPOST now rather than the rule, and it means what it always
1888  /// meant: a fragment has no queryable root, no `Graphql` binding and no place in a schema's
1889  /// `Query`. What the word activates is a SHAPE a holder's own field can be resolved AS — a client
1890  /// asking a record for `frame` gets an object with the fragment's fields on it, reached through the
1891  /// holder's face and never on its own.
1892  ///
1893  /// # Nothing at all where the declaration did not ask
1894  ///
1895  /// A fragment that wrote no `graphql(…)` publishes neither the crossing nor the object, and that is
1896  /// the shape the tier could not express before: a storage-only value, held and stored and filtered,
1897  /// with no face a client can reach. A holder that publishes such a column is `E0277` naming
1898  /// `ToGraphqlOutput` at the field, which is the same discipline every other obligation here
1899  /// follows.
1900  ///
1901  /// # The CROSSING is the identity arm, and it is what makes it free
1902  ///
1903  /// `type Output<'a> = &'a Self` — the holder's resolver hands back a borrow of the field it
1904  /// already holds, so publishing a fragment costs no clone per field of every response. A crossing
1905  /// that owned its value would have cost exactly that.
1906  ///
1907  /// # Two gates, and only one of them is this tier's
1908  ///
1909  /// The crossing is emitted UNGATED, being plain Rust that names one ungated trait. The `#[Object]`
1910  /// block rides `if_async_graphql!` — the BINDING gate, which asks `ingraph`'s own feature rather
1911  /// than the declaring crate's, a `#[cfg(feature = "async-graphql")]` written inside an expansion
1912  /// asking the wrong manifest.
1913  ///
1914  /// # Every field is spelled at LAYER 3, as the record's own face spells it
1915  ///
1916  /// The method wears the `__async_graphql_` prefix, which is what took the camelCase fallback away
1917  /// from the library — so `#[graphql(name = "…")]` is written out for every field rather than only
1918  /// for a renamed one. Where the field declared a `graphql(rename = "…")` that is what it spells,
1919  /// and the FILTER's slot reads the same answer: one field, one name on the wire.
1920  ///
1921  /// # A REWRITE's resolver HOLDS its value, and crosses out of the thing that holds it
1922  ///
1923  /// A held field is a place: `&self.width` is a borrow of storage, so the resolver returns
1924  /// `<Ty as ToGraphqlOutput>::Output<'_>` and every arm of that map works, borrowing ones
1925  /// included. A MANIFEST field is not a place — the value comes back from `self.0.width()` by
1926  /// value, crossed — so the only reference available is one to a temporary, and there is nothing
1927  /// for a borrowing arm to point at. **Measured**, at async-graphql 7.2 against this crate's own
1928  /// map:
1929  ///
1930  /// | written | rustc |
1931  /// |---|---|
1932  /// | `to_graphql_output(&self.label())` returning `Output<'_>` | `E0515: cannot return value referencing temporary value` |
1933  /// | the same, returning `Output<'static>` | `E0716: temporary value dropped while borrowed` |
1934  /// | `async fn … -> String { self.label() }` | compiles |
1935  ///
1936  /// The `String` row is what makes it general rather than incidental: its crossing is the identity
1937  /// arm (`Output<'a> = &'a Self`), and every type in that arm behaves the same way. A `u32`'s row
1938  /// is a CARRIER and would have compiled at either lifetime, so the fork is per-type and there is
1939  /// no one spelling that serves the whole map.
1940  ///
1941  /// Returning `#ty` bare was the first answer and it MOVED THE OBLIGATION: a held fragment's field
1942  /// needed `Ty: ToGraphqlOutput` and a wrapped one's `Ty: async_graphql::OutputType`, which agree
1943  /// for every type async-graphql already faces and disagree exactly where this crate's map exists
1944  /// to bridge. Measured on both sides: `u128: OutputType` is unsatisfied, so the width a held
1945  /// fragment publishes as `u128!` did not compile at all one tier over; and `Vec<u8>` DID compile,
1946  /// into `[Int!]!` — a thumbnail as a list of small integers, where the held arm crosses to the
1947  /// blob's own carrier. One declared type, two schemas.
1948  ///
1949  /// **`ingraph::Crossed<Ty>` is what closes it, and the obligation comes back to one trait.** The
1950  /// adapter takes the owned value by MOVE, so it outlives the resolver's return, and projects at
1951  /// `resolve` time out of a field it owns — the borrow the `&self` contract wanted, at an address
1952  /// that is not a temporary. Every name it publishes is the projection's, so the two arms render
1953  /// alike: `<Ty as ToGraphqlOutput>::Output<'_>` decides the SDL whether the face borrowed the
1954  /// value out of storage or computed it.
1955  ///
1956  /// What the wrapped arm asks that the held one does not is `Ty: Send + Sync + 'static`, which is
1957  /// the adapter's own bound and is spent rather than assumed: `OutputType` demands the first two of
1958  /// whatever carries it, and naming a projected form with no value in hand — which is what
1959  /// `create_type_info` does — needs `Output<'static>`.
1960  fn wire(&self) -> proc_macro2::TokenStream {
1961    let Some(face) = self.wire.as_ref() else {
1962      return proc_macro2::TokenStream::new();
1963    };
1964    let fragment = &self.fragment;
1965    let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
1966    let crossed = self.framework(&["graphql"], "Crossed");
1967    let ag = self.framework(&[], "async_graphql");
1968    let shelf = crate::emit::vendored(&self.krate, "async_graphql");
1969    let gate = self.framework(&["gate"], "if_async_graphql");
1970    let sdl = face
1971      .object
1972      .as_ref()
1973      .map_or_else(|| fragment.to_string(), |name| name.external().to_owned());
1974    let wrapped = self.remote.is_some();
1975    let fields = self.fields.iter().map(|field| {
1976      let column = &field.column;
1977      let (name, ty, gate) = (&column.name, &column.ty, field.condition.gate());
1978      let method = crate::method::wire_method(name);
1979      let wire = self.wire_field(Laid::Declared(field));
1980      let doc = crate::emit::leading(&format!("The `{name}` field of this [`{fragment}`]."));
1981      // `Self::#name(self)` rather than `self.#name()`: a rewrite's wrapper DEREFS to the remote,
1982      // and a fully qualified call cannot be resolved through that seam by accident. It is also the
1983      // ONE seam that decides what reading a manifest column means — the reader is where the
1984      // crossing by `Into` is written and where its span lands — so the wire face spends that
1985      // reader rather than re-spelling `__ingraph_cross(self.0.…())` beside it.
1986      let (returns, body) = if wrapped {
1987        (quote!(#crossed<#ty>), quote!(#crossed(Self::#name(self))))
1988      } else {
1989        (
1990          quote!(<#ty as #crossing>::Output<'_>),
1991          quote!(<#ty as #crossing>::to_graphql_output(&self.#name)),
1992        )
1993      };
1994      quote! {
1995        #gate
1996        #[doc = #doc]
1997        #[graphql(name = #wire)]
1998        async fn #method(&self) -> #returns {
1999          #body
2000        }
2001      }
2002    });
2003    let lifted = self.lifted(&crossed);
2004    quote! {
2005      #[automatically_derived]
2006      impl #crossing for #fragment {
2007        type Output<'__ingraph_output> = &'__ingraph_output Self;
2008
2009        #[inline]
2010        fn to_graphql_output(fragment: &Self) -> Self::Output<'_> {
2011          fragment
2012        }
2013      }
2014
2015      #gate! {
2016        #[#ag::Object(crate = #shelf, name = #sdl)]
2017        impl #fragment {
2018          #(#fields)*
2019          #(#lifted)*
2020        }
2021      }
2022    }
2023  }
2024
2025  /// The LIFTED delegates: one field of this fragment's object per published entry, beside the
2026  /// columns.
2027  ///
2028  /// # A manufactured value rides `Crossed`, and no arm of the map is special-cased
2029  ///
2030  /// A published delegate answers by CALLING a method, so its value is made rather than borrowed out
2031  /// of storage — which is exactly the position [`wire`](Self::wire) already measured for a
2032  /// rewrite's manifest column: `Output<'_>` over a temporary is `E0515`, `Output<'static>` is
2033  /// `E0716`, and returning the domain type bare moves the obligation off this crate's map onto
2034  /// async-graphql's. `ingraph::Crossed<Ty>` closes it by holding the value and projecting out of a
2035  /// field it owns, and the resulting field renders whatever `ToGraphqlOutput` says its type
2036  /// crosses to. The same adapter, the same spelling, the same schema — a lifted `u64` publishes
2037  /// `u64!` exactly as a `u64` column does.
2038  ///
2039  /// # A `&mut self` entry is never here
2040  ///
2041  /// A resolver READS, and the front end refuses `#[graphql(…)]` on an exclusive receiver by name —
2042  /// so an entry that mutates is delegable and never liftable, which is the seat's own rule and not
2043  /// this tier's addition.
2044  ///
2045  /// # `Self::#name(self)` and never `self.#name()`
2046  ///
2047  /// A wrapper DEREFS to the value it wraps, so a plain method call inside this block could resolve
2048  /// through that seam to a method of the wrapped type rather than to the one this expansion wrote.
2049  /// A fully qualified call cannot, which is the rule the column fields above already keep.
2050  ///
2051  /// # It is the ONE body an ordinary fragment's entry has, and where ORIGIN is answered
2052  ///
2053  /// A rewrite reaches this call through the forwarding method [`delegate`](Self::delegate) minted
2054  /// beside it; an ordinary fragment reaches the AUTHOR's own inherent method, or whatever else
2055  /// `Self` answers that name with. The seat asks no question about which, because `Self::#name` is
2056  /// resolution syntax and rustc answers it — and a name nothing on `Self` answers to is `E0599`
2057  /// spanned at the restatement the declaration wrote, which is this family's honesty pattern.
2058  fn lifted<'a>(
2059    &'a self,
2060    crossed: &'a proc_macro2::TokenStream,
2061  ) -> impl Iterator<Item = proc_macro2::TokenStream> + 'a {
2062    self.delegates.iter().filter_map(move |delegate| {
2063      let word = delegate.word(crate::model::GraphqlKind::AsyncGraphql)?;
2064      let fragment = &self.fragment;
2065      let signature = &delegate.signature;
2066      let method = &signature.ident;
2067      let ty: syn::Type = match &signature.output {
2068        syn::ReturnType::Type(_, ty) => (**ty).clone(),
2069        // A signature with no `->` answers with `()`, which has no output face — so a published
2070        // entry returning nothing is the crossing's own refusal, at the return position, rather
2071        // than a silent field of no type.
2072        syn::ReturnType::Default => syn::parse_quote_spanned!(method.span()=> ()),
2073      };
2074      let wire = crate::method::wire_method(method);
2075      let doc = crate::emit::leading(&format!(
2076        "The `{method}` method of this [`{fragment}`], published."
2077      ));
2078      Some(quote! {
2079        #[doc = #doc]
2080        #[graphql(name = #word)]
2081        async fn #wire(&self) -> #crossed<#ty> {
2082          #crossed(Self::#method(self))
2083        }
2084      })
2085    })
2086  }
2087
2088  /// What ONE of the two predicate faces is called in RUST.
2089  ///
2090  /// `<Fragment>Filter` for the FULL face — the record family's own name for the same shape — and
2091  /// `<Fragment>ColumnFilter` for the STORED one. Both compose off the fragment's own ident, which
2092  /// is the base no word at this tier moves: `graphql(filter(rename = "…"))` is an SDL seat, so it
2093  /// re-bases [`filter_sdl`](Self::filter_sdl) and leaves these two where the declaration put them.
2094  fn filter_name_of(&self, face: crate::emit::FilterFace) -> syn::Ident {
2095    match face {
2096      crate::emit::FilterFace::Full => crate::model::default_filter_name(&self.fragment),
2097      crate::emit::FilterFace::Column => crate::model::default_column_filter_name(&self.fragment),
2098    }
2099  }
2100
2101  /// What the STORED face is called — the predicate a RECORD compares this fragment's columns by,
2102  /// and the one every lowering binds to.
2103  fn column_filter_name(&self) -> syn::Ident {
2104    self.filter_name_of(crate::emit::FilterFace::Column)
2105  }
2106
2107  /// What ONE of the two predicate faces is called in the SCHEMA.
2108  ///
2109  /// # The word moves the BASE, and both faces compose off it
2110  ///
2111  /// #340's twin law, at this tier: a derived name is composed off the SCHEMA base rather than off
2112  /// the Rust ident, so a renamed face carries its twin. `graphql(filter(rename = "Dim"))` therefore
2113  /// publishes `DimFilter` beside `DimColumnFilter`, and a declaration that writes no word publishes
2114  /// `<Fragment>Filter` beside `<Fragment>ColumnFilter` — which is, for the full face, exactly the
2115  /// name the tier already minted.
2116  ///
2117  /// There is no independent knob for the second name. What it would be FOR is a schema publishing
2118  /// both faces that wants the stored one called something else, and no consumer has asked — the
2119  /// admission bar, 2026-08-22.
2120  fn filter_sdl(&self, face: crate::emit::FilterFace) -> RustSafeName {
2121    let base = self.wire.as_ref().and_then(|wire| wire.filter.as_ref());
2122    let at = base.map_or_else(|| self.fragment.span(), |name| name.safe().span());
2123    let stem = base.map_or_else(
2124      || self.fragment.to_string(),
2125      |name| name.external().to_owned(),
2126    );
2127    let composed = match face {
2128      crate::emit::FilterFace::Full => format!("{stem}Filter"),
2129      crate::emit::FilterFace::Column => format!("{stem}ColumnFilter"),
2130    };
2131    RustSafeName::new(composed, at)
2132  }
2133
2134  /// The fields ONE face's slots are written from.
2135  ///
2136  /// The whole content of the ruling, in one fork. The STORED face walks the participation — a
2137  /// `record(skip)`ped field is a column of nowhere, and its query-time value at a record is a
2138  /// raise's fill, so a slot for it would be a schema inviting a client to filter a constant. The
2139  /// FULL face walks the declaration, because a rowless host holds the value itself: memory IS the
2140  /// data, and every field it declares is askable.
2141  ///
2142  /// # What the FULL walk newly demands, and where the demand already existed
2143  ///
2144  /// A slot's type is a projection with no `where` clause over it, so the full face asks every
2145  /// DECLARED field's type for a filter at the fragment's own declaration — a `record(skip)`ped one
2146  /// included, where before the ruling it asked only the stored ones. The same field was already
2147  /// asked for a `ToGraphqlOutput` by the wire object, which publishes what the declaration IS
2148  /// rather than what a holder stored, so the shape is the tier's existing line rather than a new
2149  /// one. What it means in practice is that a field skipped BECAUSE its type answers no filter
2150  /// family — an engine-resident value is the live case at the rung above — cannot be
2151  /// `entity`-activated beside the skip. There is no word to withhold one field from the full face,
2152  /// and there is no consumer asking for one; the admission bar decides that, not this walk.
2153  ///
2154  /// # A DERIVED column is on the STORED face and on that face alone
2155  ///
2156  /// The two faces already part on *what is in a row*, and a derived column is the extreme case of
2157  /// the same axis: it is a column and nothing else — there is no field to ask a rowless host about,
2158  /// no value in memory to compare, and no accessor that would hand one back. So the full face,
2159  /// which is *every field the declaration holds*, holds none of them, and the stored face, which is
2160  /// *the columns the value is kept in*, holds all of them. That is the whole point of the word: the
2161  /// canonical-unit column exists so a client can ORDER and RANGE on it, and the face a row-holding
2162  /// host reads is the one those questions arrive at.
2163  fn filtered(&self, face: crate::emit::FilterFace) -> Box<dyn Iterator<Item = Laid<'_>> + '_> {
2164    match face {
2165      crate::emit::FilterFace::Full => Box::new(self.fields.iter().map(Laid::Declared)),
2166      crate::emit::FilterFace::Column => Box::new(self.laid()),
2167    }
2168  }
2169
2170  /// The two faces this declaration actually EMITS, in the order they are written.
2171  ///
2172  /// One activation, one type — the common case, and it costs a declaration nothing but the name it
2173  /// already had. Both activations, both types: two consumer worlds, two vocabularies.
2174  fn faces(&self) -> Vec<crate::emit::FilterFace> {
2175    let mut faces = Vec::new();
2176    if self.entity {
2177      faces.push(crate::emit::FilterFace::Full);
2178    }
2179    if self.record.is_some() {
2180      faces.push(crate::emit::FilterFace::Column);
2181    }
2182    faces
2183  }
2184
2185  /// What [`CompositeFilterMarker`]'s two rows NAME — the full seat first, the stored seat second.
2186  ///
2187  /// A declaration activated for one host kind emits one type and seats it at both, which is what
2188  /// makes the single-activation case free: a holder of either kind resolves to the one predicate
2189  /// there is. Activated for both, the seats part and each holder reaches the truth its own kind
2190  /// tells.
2191  ///
2192  /// [`CompositeFilterMarker`]: https://docs.rs/ingraph/latest/ingraph/trait.CompositeFilterMarker.html
2193  fn seats(&self) -> (syn::Ident, syn::Ident) {
2194    let full = self.filter_name_of(crate::emit::FilterFace::Full);
2195    let column = self.column_filter_name();
2196    match (self.entity, self.record.is_some()) {
2197      (true, true) => (full, column),
2198      (true, false) => (full.clone(), full),
2199      _ => (column.clone(), column),
2200    }
2201  }
2202
2203  /// What the COMPARISON face is called: `<Fragment>Comparison`.
2204  ///
2205  /// ONE, and generic in its dialect — a fragment names no database, so there is no per-backend
2206  /// suffix to hang a second one on. That is the standalone door's rule read at this tier, and it is
2207  /// the same rule for the same reason: what a database decides is the STORED type of a column, and
2208  /// a fragment declares no storage for one to differ in.
2209  fn comparison_name(&self) -> syn::Ident {
2210    crate::model::default_comparison_name(&self.fragment)
2211  }
2212
2213  /// The subject noun the emitted faces' doc sentences use — a LINK, because a fragment's own
2214  /// declaration is in scope wherever its expansion lands.
2215  fn subject(&self) -> String {
2216    format!("[`{}`]", self.fragment)
2217  }
2218
2219  /// The FILTER faces: up to two predicates over the fragment's own fields, and the two marker rows
2220  /// that make a HOLDER reach the right one without naming it.
2221  ///
2222  /// # EACH FACE TELLS ITS OWN TRUTH, which is what makes it two types and not one
2223  ///
2224  /// The 2026-08-22 ruling. A fragment held by a RECORD can be compared only by what it is stored
2225  /// in: `record(skip)` takes a field out of every row, so its query-time value at a record is
2226  /// whatever the raise fills, and a slot inviting a client to filter a constant is a lying schema.
2227  /// A fragment held by an ENTITY has no such subset — memory IS the data — so every field it
2228  /// declares is askable. The two answers are both right and they are not the same answer, so the
2229  /// tier writes both rather than picking one and refusing at runtime.
2230  ///
2231  /// **One activation emits one type**, named at both marker seats, and that is the common case and
2232  /// every declaration written before the ruling: a record-hosted fragment gets
2233  /// `<Fragment>ColumnFilter` — today's predicate, under the name that says which truth it tells —
2234  /// and an entity-hosted one gets `<Fragment>Filter`. **Both activations emit both**, and the seats
2235  /// part. Nothing else changes: the walk is [`unit::filter`]'s in both cases, over the list
2236  /// [`filtered`](Self::filtered) hands it.
2237  ///
2238  /// # The holder needs no new word, and that is the whole design
2239  ///
2240  /// A record's filter slot for a column of type `T` is
2241  /// `<<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter` — a projection, resolved by the
2242  /// compiler. So a fragment joins the filter layer by ANSWERING that projection rather than by the
2243  /// holder's emission learning what a fragment is: nothing in `emit::graphql` mentions this tier
2244  /// before this change or after it. What was missing was only the answer, which every hand-written
2245  /// composite in this ecosystem supplied by minting a marker of its own.
2246  ///
2247  /// # The reading is COMPOSITE, and its `Option` is a NULLABLE
2248  ///
2249  /// [`CompositeMarker`] is the VALUE family's member for a value occupying columns of its own, so
2250  /// `Marker::UnderOption` hands `Option<Fragment>` a `NullableMarker` and the `isNull` question is
2251  /// kept. A collection reading would have dropped it, and a composite's columns really can all be
2252  /// `NULL` together — the two states are observable and a filter that could not tell them apart
2253  /// would be answering a different question.
2254  ///
2255  /// # Every slot is `Option<its own column's filter>`, one level and no flattening
2256  ///
2257  /// The fragment's fields are the slots, in declared order, each guarded by whatever ITS type is
2258  /// guarded by. A nested fragment therefore nests — its slot is the inner fragment's filter, which
2259  /// is a filter like any other — and the depth is the declaration's rather than this walk's, which
2260  /// is exactly how [`columns`](Self::columns) already treats the storage side.
2261  ///
2262  /// # The predicate's OWN wire face is the composed door's, and it has to be
2263  ///
2264  /// A holder's filter face REGISTERS every slot — `Option<DimensionsFilter>` is an input-object
2265  /// member — so a predicate that is only a Rust struct is a slot a holder cannot publish. Measured:
2266  /// without this, `DimensionsFilter: InputType` is unsatisfied. The four items it owes are exactly
2267  /// what `#[ingraph(composed)]` emits from a field list, so this reaches [`crate::composed`] rather
2268  /// than writing a second copy — the same reuse the struct and the comparison above take from
2269  /// [`unit`].
2270  ///
2271  /// **No SHORTHAND.** Rule ① puts a bare value under the first published slot, and a composite's
2272  /// first slot is one COMPONENT's filter — so `frame: 1920` would silently mean *width is 1920*.
2273  /// A fragment takes no bare operand, and declining the rule is how the framework's own sentence
2274  /// says so.
2275  ///
2276  /// [`CompositeMarker`]: https://docs.rs/ingraph/latest/ingraph/struct.CompositeMarker.html
2277  fn filter(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
2278    let fragment = &self.fragment;
2279    if let Some(mounted) = self.filter.as_ref() {
2280      return (proc_macro2::TokenStream::new(), self.mounted(mounted));
2281    }
2282    let mut declarations = proc_macro2::TokenStream::new();
2283    let mut builders = proc_macro2::TokenStream::new();
2284    for face in self.faces() {
2285      let (declaration, family) = self.predicate(face);
2286      declarations.extend(declaration);
2287      builders.extend(family);
2288    }
2289    let (full, column) = self.seats();
2290    let composite_filter = self.framework(&["marker"], "CompositeFilterMarker");
2291    let composite_marker = self.framework(&["marker"], "CompositeMarker");
2292    let default_marker = self.framework(&["marker"], "DefaultMarker");
2293    (
2294      declarations,
2295      quote! {
2296        #builders
2297
2298        // The TYPE says what its filter is, for the reason a byte column's type says which of the
2299        // two byte filters it takes: what a composite's filter looks like is a fact about its parts.
2300        // TWO rows, because a composite's filter also depends on WHO holds it — a rowless host asks
2301        // about the value and a row-holding one may only ask about what it stored. One activation
2302        // names one type at both seats; two activations part them.
2303        #[automatically_derived]
2304        impl #composite_filter for #fragment {
2305          type Filter = #full;
2306          type ColumnFilter = #column;
2307        }
2308
2309        // And the reading a field of this type is under when its holder names no word — which is
2310        // every holder, this tier admitting no interpretation word of its own. Unmoved by the two
2311        // faces: what forks is the FILTER a reading resolves to, never the reading.
2312        #[automatically_derived]
2313        impl #default_marker for #fragment {
2314          type Marker = #composite_marker<#fragment>;
2315        }
2316      },
2317    )
2318  }
2319
2320  /// ONE predicate face: the struct, and the builder family beside it.
2321  ///
2322  /// Both faces are [`unit::filter`]'s own walk over a different list — see
2323  /// [`filtered`](Self::filtered) for which list and why — so there is no second emitter here and
2324  /// nothing about the stored face that the full one does not also get.
2325  fn predicate(
2326    &self,
2327    face: crate::emit::FilterFace,
2328  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
2329    let name = self.filter_name_of(face);
2330    let rows: Vec<unit::FilterColumn> = self
2331      .filtered(face)
2332      .map(|one| unit::FilterColumn {
2333        gate: one.gate(),
2334        member: one.member().clone(),
2335        name: one.subject(),
2336        // The SLOT reads the component at the SAME face: a stored predicate over a fragment holding
2337        // a fragment compares the inner one's columns, and a full predicate asks the inner one's
2338        // whole field set. The recursion is the projection's, not this walk's.
2339        filter: crate::emit::filter_of(&self.krate, one.ty(), None, face),
2340      })
2341      .collect();
2342    // The shape's own sentence above these calls a fragment's fields STORED COLUMNS, which is the
2343    // record family's word and is exactly what the two faces stop agreeing about — so each note
2344    // says which reading of it applies rather than restating the shape.
2345    const HELD: &str = "A fragment is HELD, so this predicate is never a query's own argument: it \
2346                        is what a HOLDER's filter carries at the field that holds one, nested \
2347                        under that field's name.";
2348    let note = match face {
2349      crate::emit::FilterFace::Full => format!(
2350        "{HELD}\n\nThe FULL face, which a ROWLESS host reads — and the one place the sentence \
2351         above is to be read as EVERY FIELD THE DECLARATION HOLDS rather than as the stored \
2352         subset. A `record(skip)`ped field has no column anywhere and is askable here: a rowless \
2353         host holds the value itself, and memory is the data."
2354      ),
2355      crate::emit::FilterFace::Column => format!(
2356        "{HELD}\n\nThe STORED face, which a ROW-HOLDING host reads: the columns the value is \
2357         kept in, and no others. What a record hands back for a `record(skip)`ped field is \
2358         whatever the raise FILLS rather than anything a row carries, so a slot for one would \
2359         invite a client to compare a constant."
2360      ),
2361    };
2362    let header = unit::UnitHeader {
2363      vis: &self.vis,
2364      name,
2365      subject: self.subject(),
2366      note: Some(note),
2367    };
2368    unit::filter(&header, &rows)
2369  }
2370
2371  /// A MOUNTED filter: the two marker rows pointing at the author's type, and the obligations that
2372  /// type owes, cleared at the declaration rather than at whatever holds this fragment.
2373  ///
2374  /// # What is NOT here is the point
2375  ///
2376  /// No struct, no builders, no input face. `filter = "…"` says the predicate over this value is the
2377  /// author's, and a generated one emitted beside it would be a second input object in the schema
2378  /// that nothing reaches — the SDL is the deliverable, and a face no slot names is a face a client
2379  /// reads and cannot use.
2380  ///
2381  /// [`DefaultMarker`] is untouched and still answers [`CompositeMarker`], which is the whole reason
2382  /// the swap needs no new word at a HOLDER: a holder's filter slot is
2383  /// `<<Ty as DefaultMarker>::Marker as ToGraphqlFilter>::Filter`, a projection that resolves
2384  /// through the composite reading to whatever [`CompositeFilterMarker`] names. The `Option` around
2385  /// it keeps the `isNull` question exactly as before.
2386  ///
2387  /// # The obligations are the HOLDER's, reported HERE
2388  ///
2389  /// A mounted filter is a slot of every holder's own filter, and that struct derives `Debug` and
2390  /// `Clone` over its slots and registers each one as an input-object member. A type that answers
2391  /// none of those is `E0277` inside the HOLDER's expansion — at a span the fragment's author does
2392  /// not own, in the library's words, naming a type the holder's author never wrote. The two
2393  /// witnesses below move both reports to the `filter = "…"` that made the claim, which is the
2394  /// union input seat's own construction and the same argument.
2395  ///
2396  /// The wire obligation rides the BINDING gate, so a build compiling no `async-graphql` asks
2397  /// nothing about a face it does not emit.
2398  ///
2399  /// [`DefaultMarker`]: https://docs.rs/ingraph/latest/ingraph/trait.DefaultMarker.html
2400  /// [`CompositeMarker`]: https://docs.rs/ingraph/latest/ingraph/struct.CompositeMarker.html
2401  /// [`CompositeFilterMarker`]: https://docs.rs/ingraph/latest/ingraph/trait.CompositeFilterMarker.html
2402  fn mounted(&self, mounted: &syn::Path) -> proc_macro2::TokenStream {
2403    let fragment = &self.fragment;
2404    let composite_filter = self.framework(&["marker"], "CompositeFilterMarker");
2405    let composite_marker = self.framework(&["marker"], "CompositeMarker");
2406    let default_marker = self.framework(&["marker"], "DefaultMarker");
2407    let held = self.witness(
2408      mounted,
2409      &format_ident!("__IngraphMountedFilter"),
2410      &quote!(::core::fmt::Debug + ::core::clone::Clone),
2411      &format!("`{{Self}}` is what `{fragment}` mounts as its filter, and a holder cannot HOLD it"),
2412      "this type is no predicate a holder can carry",
2413      &format!(
2414        "`filter = \"…\"` names the predicate a HOLDER's own filter carries at the field that holds \
2415         `{fragment}`, and that struct derives `Debug` and `Clone` over every slot — so a mounted \
2416         predicate owes both. `#[derive(Debug, Clone, Default, ingraph::Filter)] \
2417         #[ingraph(composed)]` is the declaration the generated filter this replaces was built \
2418         from, and it writes them"
2419      ),
2420    );
2421    let ag = self.framework(&[], "async_graphql");
2422    let gate = self.framework(&["gate"], "if_async_graphql");
2423    let sent = self.witness(
2424      mounted,
2425      &format_ident!("__IngraphMountedInput"),
2426      &quote!(#ag::InputType),
2427      &format!("`{{Self}}` is what `{fragment}` mounts as its filter, and it has no INPUT face"),
2428      "this type is no input object",
2429      &format!(
2430        "a holder's filter REGISTERS every slot, so the predicate over `{fragment}` is an \
2431         input-object member and needs an `async_graphql::InputType` row. \
2432         `#[derive(ingraph::Filter)] #[ingraph(composed)]` writes one from a field list — which is \
2433         what the generated filter this replaces was built from"
2434      ),
2435    );
2436    // The INPUT obligation rides the fragment's own WIRE activation and not only the binding gate: a
2437    // declaration that publishes nothing has no holder that can name this predicate on the wire, so
2438    // asking its mounted type for an input face would be charging it for a surface it declined.
2439    let sent = self.wire.is_some().then(|| {
2440      quote! {
2441        #gate! {
2442          #sent
2443        }
2444      }
2445    });
2446    quote! {
2447      #held
2448
2449      #sent
2450
2451      // The TYPE says what its filter is, and here it says the author's — at BOTH seats. One word,
2452      // one predicate: an author who mounts a filter has said what asking about this value MEANS,
2453      // and a generated face beside it would put a second vocabulary for one value in one schema,
2454      // reachable from one host kind and not the other. The rows are the same two a generated pair
2455      // takes, which is what keeps a holder's projection unmoved.
2456      #[automatically_derived]
2457      impl #composite_filter for #fragment {
2458        type Filter = #mounted;
2459        type ColumnFilter = #mounted;
2460      }
2461
2462      // And the reading a field of this type is under when its holder names no word — unmoved by
2463      // the swap, a mounted predicate being a different answer to the same question.
2464      #[automatically_derived]
2465      impl #default_marker for #fragment {
2466        type Marker = #composite_marker<#fragment>;
2467      }
2468    }
2469  }
2470
2471  /// ONE obligation a mounted filter owes, as a witness trait spent at the path the declaration
2472  /// wrote.
2473  ///
2474  /// A blanket over the real bound rather than the bound itself, for the reason the vocabulary
2475  /// mirror's return-type marker is one: `#[diagnostic::on_unimplemented]` belongs to a trait, and
2476  /// the traits actually owed are `core`'s and the library's. `do_not_recommend` on the blanket is
2477  /// what keeps the report this framework's sentence rather than a descent into the bound.
2478  ///
2479  /// Spanned WHOLE at the author's path — the turbofish included — so the caret lands on the
2480  /// `filter = "…"` an author edits rather than inside an expansion nobody can.
2481  fn witness(
2482    &self,
2483    mounted: &syn::Path,
2484    marker: &syn::Ident,
2485    owed: &proc_macro2::TokenStream,
2486    message: &str,
2487    label: &str,
2488    note: &str,
2489  ) -> proc_macro2::TokenStream {
2490    let at = mounted.span();
2491    let spent = quote_spanned!(at=> __ingraph_mounted::<#mounted>);
2492    quote! {
2493      #[diagnostic::on_unimplemented(
2494        message = #message,
2495        label = #label,
2496        note = #note,
2497      )]
2498      trait #marker {}
2499
2500      #[diagnostic::do_not_recommend]
2501      impl<__IngraphMounted> #marker for __IngraphMounted where __IngraphMounted: #owed {}
2502
2503      const _: () = {
2504        fn __ingraph_mounted<__IngraphMounted: #marker>() {}
2505        let _ = #spent;
2506      };
2507    }
2508  }
2509
2510  /// The PREDICATE'S OWN WIRE FACE, through the composed door — emitted only where the declaration
2511  /// activated one.
2512  ///
2513  /// # Why a Rust-only filter is a slot no holder can register
2514  ///
2515  /// A holder's filter face REGISTERS every slot: `Option<DimensionsFilter>` is an input-object
2516  /// member, so a predicate that is only a Rust struct is a slot a holder cannot publish. Measured:
2517  /// without this, `DimensionsFilter: InputType` is unsatisfied. The four items it owes are exactly
2518  /// what `#[ingraph(composed)]` emits from a field list, so this reaches [`crate::composed`] rather
2519  /// than writing a second copy — the same reuse the struct and the comparison take from [`unit`].
2520  ///
2521  /// **No SHORTHAND.** Rule ① puts a bare value under the first published slot, and a composite's
2522  /// first slot is one COMPONENT's filter — so `frame: 1920` would silently mean *width is 1920*. A
2523  /// fragment takes no bare operand, and declining the rule is how the framework's own sentence says
2524  /// so.
2525  ///
2526  /// It rides the WIRE activation rather than the filter's own gate, because what it is FOR is a
2527  /// client naming this predicate: a storage-only fragment is filtered exactly as before and has no
2528  /// client to name it.
2529  ///
2530  /// A MOUNTED filter has none of this. `filter = "…"` emits no struct for a face to be ABOUT, and
2531  /// registering one anyway would put a second input object in the schema that no slot reaches —
2532  /// which is the whole content of the swap being a swap. The author's type carries its own face,
2533  /// through whatever door declared it.
2534  fn filter_face(&self) -> proc_macro2::TokenStream {
2535    if self.wire.is_none() || self.filter.is_some() {
2536      return proc_macro2::TokenStream::new();
2537    }
2538    let doors = self.faces().into_iter().map(|face| self.input_face(face));
2539    quote!(#(#doors)*)
2540  }
2541
2542  /// ONE face's input object, through the composed door.
2543  ///
2544  /// Two of them land in one schema where a declaration activated both host kinds, and they are two
2545  /// input objects because they are two vocabularies — the whole content of the ruling. Their names
2546  /// part at [`filter_sdl`](Self::filter_sdl), which composes both off one base so a rename carries
2547  /// its twin.
2548  fn input_face(&self, face: crate::emit::FilterFace) -> proc_macro2::TokenStream {
2549    composed::ComposedModel {
2550      sdl: self.filter_sdl(face),
2551      subject: self.filter_name_of(face),
2552      krate: self.krate.clone(),
2553      shorthand: false,
2554      fields: self
2555        .filtered(face)
2556        .map(|one| composed::ComposedField {
2557          member: one.member().clone(),
2558          // The SLOT's own type, which is what the seam resolves the shape from — the same
2559          // `Option<…>` the struct declares, at the same face, so the two cannot come to disagree.
2560          ty: {
2561            let filter = crate::emit::filter_of(&self.krate, one.ty(), None, face);
2562            syn::parse_quote!(::core::option::Option<#filter>)
2563          },
2564          // A SLOT and never a splice: a fragment's field is one component's predicate, and
2565          // flattening it would put that component's operators on the fragment's own face. Its NAME
2566          // is the field's own declared wire name, which is the same one the object's member takes —
2567          // one field, one name on the wire, exactly as a record's face reads it.
2568          kind: composed::ComposedKind::Slot(self.wire_field(one)),
2569          // The SAME condition the struct's member rides, so the predicate reaches the input
2570          // object's registration, its parse and its render together with the field it removes.
2571          condition: one.condition().clone(),
2572        })
2573        .collect(),
2574    }
2575    .emit()
2576  }
2577
2578  /// What a STATEMENT calls one column — its `record(rename = "…")`, or the field's own name.
2579  ///
2580  /// One reader for the three seats that render a column name — the segment list, the shape entry
2581  /// that pairs the two axes, and the predicate's lowering — which is what keeps a `SELECT` naming
2582  /// one column from a `WHERE` naming another.
2583  fn stored_name(&self, one: Laid<'_>) -> String {
2584    match one {
2585      Laid::Declared(field) => field
2586        .stored_name
2587        .clone()
2588        .unwrap_or_else(|| field.column.name.to_string()),
2589      // ONE AXIS, because there is no second one to move. A declared field's two names are its Rust
2590      // name and whatever `record(rename = "…")` moved the stored one to; a derived column has no
2591      // Rust field, so the `column = "…"` word is what a statement renders AND what a filter slot is
2592      // called, and `RustSafeName` is where the two spellings of that one name are held apart.
2593      Laid::Derived { column, .. } => column.column.external().to_owned(),
2594    }
2595  }
2596
2597  /// What a CLIENT calls one field — its declared wire name, or the fold of its own.
2598  ///
2599  /// One reader for the two surfaces a field publishes, which is what keeps the object's member and
2600  /// the filter's slot from coming to disagree about a rename.
2601  /// A DERIVED column has no `graphql(rename = "…")` to read — the word sits on a field and a
2602  /// derived column is not one — so its wire name is the fold of the name it was given, which is the
2603  /// same rule a field writing no rename gets.
2604  fn wire_field(&self, one: Laid<'_>) -> String {
2605    match one.declared().and_then(|field| field.wire_name.clone()) {
2606      Some(spelled) => spelled,
2607      None => crate::emit::wire::wire_member(one.member()),
2608    }
2609  }
2610
2611  /// The COMPARISON face: one predicate per field, each rendered ONE SEGMENT BELOW the address the
2612  /// whole fragment was applied at.
2613  ///
2614  /// # This is the 每列各门 half, and the address is a PATH rather than a prefix
2615  ///
2616  /// `at.frame(name)` pushes one segment onto whatever address arrived, so the same comparison
2617  /// renders `frame_width`/`frame_height` under a field called `frame` and bare `width`/`height`
2618  /// when a holder flattened it. A lowering taking a NAME could not render the second case at all —
2619  /// and one taking a name per column would take two same-typed parameters that can be passed in the
2620  /// wrong order, both orders rendering valid SQL. The walk is [`unit::comparison_lowering`]'s, and
2621  /// this tier writes no second copy of it.
2622  ///
2623  /// # [`CompositeComparison`] reads the SAME const the storage side does
2624  ///
2625  /// One list, two traits: `ColumnKind::SEGMENTS` says how many columns the value occupies and this
2626  /// says the predicate occupies them too. Two lists that agreed today would be two lists that could
2627  /// drift, and the drift is the silent kind — a filter naming a column no statement selected.
2628  ///
2629  /// It is also what makes a fragment FLATTENABLE: `persist(<db>(flatten))` states the refined crossing
2630  /// `ToFlattenedComparison`, whose whole added content is this trait, and a scalar's refusal of it is
2631  /// the framework's own wording for *there is no prefix to drop*.
2632  ///
2633  /// # The `where` clause is UNSATISFIABLE for some fragments, on purpose
2634  ///
2635  /// A field whose filter has no crossing at a generic dialect — a collection is the live case —
2636  /// makes this struct's clause unprovable, and the struct still compiles: a `where` clause is
2637  /// discharged where the type is USED. So a fragment nobody stores may hold such a field, and the
2638  /// `E0277` lands on the record that stores one, naming the field's type. That is exactly the
2639  /// discipline [`columns`](Self::columns) already follows for the storage obligation.
2640  ///
2641  /// [`CompositeComparison`]: https://docs.rs/ingraph/latest/ingraph/comparison/trait.CompositeComparison.html
2642  fn comparison(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
2643    let fragment = &self.fragment;
2644    let name = self.comparison_name();
2645    let db = crate::emit::parameter("DB");
2646    let crossings = self.assumptions(&db);
2647    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
2648    let rows: Vec<unit::ComparisonColumn> = self
2649      .laid()
2650      .map(|one| {
2651        let ty = one.ty();
2652        let filter = crate::emit::filter_of(&self.krate, ty, None, crate::emit::FilterFace::Column);
2653        unit::ComparisonColumn {
2654          gate: one.gate(),
2655          member: one.member().clone(),
2656          name: one.subject(),
2657          held: quote!(<#filter as #to_comparison<#ty, #db>>::Comparison),
2658        }
2659      })
2660      .collect();
2661    let header = unit::UnitHeader {
2662      vis: &self.vis,
2663      name: name.clone(),
2664      subject: self.subject(),
2665      note: Some(
2666        "ONE comparison, generic in its dialect: a fragment names no database, so there is no \
2667         stored type for a second to differ in."
2668          .to_owned(),
2669      ),
2670    };
2671    let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
2672    let seats = unit::LoweringSeats {
2673      backend: self.framework(&["comparison"], "Backend"),
2674      complex: self.framework(&["comparison"], "ComplexComparison"),
2675      frame: self.framework(&["comparison"], "Frame"),
2676      at: self.framework(&["comparison"], "At"),
2677      field_name: self.framework(&["field"], "FieldName"),
2678    };
2679    let lowered: Vec<unit::LoweringColumn> = self
2680      .laid()
2681      .map(|one| unit::LoweringColumn {
2682        gate: one.gate(),
2683        member: one.member().clone(),
2684        // The STORED name, which is what a statement renders — the same axis the segment list
2685        // carries, read through the one function that resolves it.
2686        rendered: self.stored_name(one),
2687        // The INNER mount's own word, read exactly where the column list reads it. Whether this
2688        // whole fragment loses its prefix is a different question and stays the HOLDER's
2689        // `persist(<db>(flatten))`, which acts on the holder's column list and not on this walk.
2690        flatten: one.flatten(),
2691        through: None,
2692      })
2693      .collect();
2694    let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);
2695    let composite = self.framework(&["comparison"], "CompositeComparison");
2696    let column_kind = self.framework(&["column"], "ColumnKind");
2697    let column_shape = self.framework(&["column"], "ColumnShape");
2698    let map = self.map(&db, &name, &crossings);
2699    (
2700      declaration,
2701      quote! {
2702        #methods
2703        #lowering
2704
2705        #[automatically_derived]
2706        impl<#db> #composite<#db> for #name<#db>
2707        where
2708          #crossings
2709        {
2710          const SEGMENTS: &'static [#column_shape] = <#fragment as #column_kind>::SEGMENTS;
2711        }
2712
2713        #map
2714      },
2715    )
2716  }
2717
2718  /// **WHICH COMPARISON THIS FRAGMENT'S PREDICATE LOWERS INTO** — the map row, at a parameter where
2719  /// nothing was mounted and at each named dialect where something was.
2720  ///
2721  /// It is the type-level half of the crossing; the operand-level twin is written at a CONCRETE
2722  /// backend, by [`pair`](Self::pair).
2723  ///
2724  /// # The mounted arm and the parameter arm are EXCLUSIVE, and it is [`pair`](Self::pair)'s reason
2725  ///
2726  /// `impl<DB> ToDatabaseComparison<Fragment, DB> for F` overlaps
2727  /// `impl ToDatabaseComparison<Fragment, Sqlite> for F`, so a declaration that mounts anywhere
2728  /// takes the ENUMERATED form everywhere: one row per dialect the head named, carrying the mounted
2729  /// type where one was written and the framework's own product where none was. That is the whole
2730  /// of *partial coverage is coherent* — an unmounted dialect is not a gap, it is the product still
2731  /// standing.
2732  ///
2733  /// What the enumerated form does NOT cover is a dialect the head never named, and that is
2734  /// declaration-truth rather than a loss: naming a dialect is how this tier says which backends it
2735  /// was built for, and [`pair`](Self::pair) has drawn the same line since the concrete arm existed.
2736  /// A declaration that mounts nothing keeps the parameter arm and expands token for token as it
2737  /// did.
2738  ///
2739  /// # A MOUNTED FILTER moves the self type and never removes the row
2740  ///
2741  /// `filter = "…"` says the predicate is the author's, and the row that says what that predicate
2742  /// lowers into is a fact about the predicate — so with no mount anywhere the author writes it,
2743  /// exactly as before. A `comparison` mount is the author writing the OTHER half, and the row that
2744  /// joins the two halves is the one artifact neither word can write for itself: the author's filter
2745  /// at this dialect lowering into the author's comparison. So the mounted arm is emitted for
2746  /// whichever filter this declaration ended up with, and the two words compose without either
2747  /// knowing about the other.
2748  ///
2749  /// An author who mounts a comparison at a dialect must not then hand-write a row covering that
2750  /// dialect — the framework owns it there, and a second one is `E0119`. The guide says so at the
2751  /// seat.
2752  fn map(
2753    &self,
2754    db: &syn::Ident,
2755    product: &syn::Ident,
2756    crossings: &proc_macro2::TokenStream,
2757  ) -> proc_macro2::TokenStream {
2758    let fragment = &self.fragment;
2759    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
2760    // A comparison face is emitted only under the record activation — see [`emit`](Self::emit) — so
2761    // an absent host here is a fragment whose emission never reached this function.
2762    let mounted_anywhere = self
2763      .record
2764      .as_ref()
2765      .is_some_and(|host| host.databases.iter().any(|one| one.comparison.is_some()));
2766    let Some(host) = self.record.as_ref().filter(|_| mounted_anywhere) else {
2767      // NOTHING MOUNTED: the row as it has always been — one impl over the parameter, and none at
2768      // all where the filter is the author's and so is the row.
2769      if self.filter.is_some() {
2770        return proc_macro2::TokenStream::new();
2771      }
2772      let filter = self.column_filter_name();
2773      return quote! {
2774        #[automatically_derived]
2775        impl<#db> #to_comparison<#fragment, #db> for #filter
2776        where
2777          #crossings
2778        {
2779          type Comparison = #product<#db>;
2780        }
2781      };
2782    };
2783    let mounted = self.column_filter_name();
2784    let filter: proc_macro2::TokenStream = match self.filter.as_ref() {
2785      Some(author) => quote!(#author),
2786      None => quote!(#mounted),
2787    };
2788    let rows = host.databases.iter().enumerate().map(|(nth, built)| {
2789      let gate = self.framework(&["gate"], &built.kind.gate().to_string());
2790      let (module, name) = built.kind.backend();
2791      let backend = self.framework(module, name);
2792      let Some(lowering) = built.comparison.as_ref() else {
2793        // AN UNMOUNTED DIALECT KEEPS THE PRODUCT, and only where the filter is the framework's: an
2794        // author's predicate crossing into a generated comparison is a crossing only the author can
2795        // write, which is the same line the no-mount arm above draws.
2796        //
2797        // NO `where` CLAUSE, for [`pair`](Self::pair)'s reason at its own concrete arm: at a named
2798        // dialect the members' rows are DISCHARGED at this declaration rather than carried, which
2799        // is what a dialect at the head buys and what audits the fragment against it.
2800        if self.filter.is_some() {
2801          return proc_macro2::TokenStream::new();
2802        }
2803        return quote! {
2804          #gate! {
2805            #[automatically_derived]
2806            impl #to_comparison<#fragment, #backend> for #filter {
2807              type Comparison = #product<#backend>;
2808            }
2809          }
2810        };
2811      };
2812      let audit = self.mount_audit(nth, built, lowering, &filter, &backend);
2813      quote! {
2814        #gate! {
2815          #audit
2816
2817          #[automatically_derived]
2818          impl #to_comparison<#fragment, #backend> for #filter {
2819            type Comparison = #lowering;
2820          }
2821        }
2822      }
2823    });
2824    quote!(#(#rows)*)
2825  }
2826
2827  /// **ONE MOUNTED LOWERING AUDITED AT THE DIALECT IT WAS NAMED AT** — the three faces it takes
2828  /// over, spent at the string the author wrote.
2829  ///
2830  /// # What a mount owes
2831  ///
2832  /// A holder reaches a fragment-typed column through `ToCrossedComparison`, whose blanket asks the
2833  /// comparison for a `TryFromFilter` from this fragment's own predicate and a `Default` for the
2834  /// column a client said nothing about; the map row's own item bound asks it to LOWER. All three
2835  /// are here, in one witness, and the last is here DESPITE the item bound rather than in ignorance
2836  /// of it.
2837  ///
2838  /// That was measured. The item bound reports `ComplexComparison<Db> is not satisfied` at the
2839  /// author's string — the path came out of a string literal and kept the literal's span — so the
2840  /// SPAN was never the problem and a witness adds nothing there. What it adds is the sentence: a
2841  /// mount that fails the crossing seat already earns both reports, so leaving the lowering out
2842  /// bought no reduction in error count and left the one failure mode that a reader meets alone
2843  /// without a sentence naming the seat it belongs to.
2844  ///
2845  /// # The marker is numbered, because a declaration may mount at several dialects
2846  ///
2847  /// Each mount mints its own witness trait, and two traits of one name in one scope is `E0428`.
2848  /// The number is the dialect's INDEX at the head rather than a counter of mounts, so a mount's
2849  /// witness keeps its name when a neighbouring dialect gains or loses one.
2850  fn mount_audit(
2851    &self,
2852    nth: usize,
2853    built: &BuiltFor,
2854    lowering: &syn::Path,
2855    filter: &proc_macro2::TokenStream,
2856    backend: &proc_macro2::TokenStream,
2857  ) -> proc_macro2::TokenStream {
2858    let fragment = &self.fragment;
2859    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
2860    let complex = self.framework(&["comparison"], "ComplexComparison");
2861    let product = self.comparison_name();
2862    let db = built.kind.as_str();
2863    self.witness(
2864      lowering,
2865      &format_ident!("__IngraphMountedComparison{nth}"),
2866      &quote!(#try_from_filter<#filter> + ::core::default::Default + #complex<#backend>),
2867      &format!(
2868        "`{{Self}}` is what `{fragment}` mounts as its `{db}` lowering, and it does not answer that \
2869         seat"
2870      ),
2871      "this type is no lowering this fragment's predicate reaches",
2872      &format!(
2873        "`{db}(comparison = \"…\")` replaces the per-field product at `{db}`, so the type it names \
2874         takes over the whole seat and owes its three faces: `TryFromFilter<{filter}>`, which is \
2875         how the client's predicate becomes a lowering; `Default`, which is what a column the \
2876         client said nothing about lowers to; and `ComplexComparison` at this dialect's backend, \
2877         which is the lowering itself. The product this replaces — `{product}` at this backend — \
2878         is still emitted and still nameable, so a mount that wants the component walk under its \
2879         own vocabulary delegates to it rather than restating it",
2880        filter = filter.to_string().replace(' ', ""),
2881      ),
2882    )
2883  }
2884
2885  /// What a comparison over these fields ASSUMES — that the database is a `Backend` at all, and
2886  /// that each field's filter crosses into something for it.
2887  ///
2888  /// One function, spliced verbatim into the struct and every impl over it: a clause asserting MORE
2889  /// than the struct's would report a missing crossing twice, and one asserting less would not apply
2890  /// to the type it is written for.
2891  fn assumptions(&self, db: &syn::Ident) -> proc_macro2::TokenStream {
2892    let backend = self.framework(&["comparison"], "Backend");
2893    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
2894    let crossings = self.laid().map(|one| {
2895      let ty = one.ty();
2896      let filter = crate::emit::filter_of(&self.krate, ty, None, crate::emit::FilterFace::Column);
2897      quote!(#filter: #to_comparison<#ty, #db>,)
2898    });
2899    quote! {
2900      #db: #backend,
2901      #(#crossings)*
2902    }
2903  }
2904
2905  /// The COLUMNS a fragment-typed field of a holder's row occupies — one `ColumnKind` impl, over
2906  /// every dialect at once.
2907  ///
2908  /// # It is the whole of what a holder needs, and the tier's other absences stand
2909  ///
2910  /// A fragment has no id, no key and no storage of its own; what it acquires the moment a record
2911  /// holds one is a WIDTH. `tb: Timebase` is two columns of the holder's table, and the HOLDER's
2912  /// emission cannot know that — there `tb: Timebase` and `title: String` are the same tokens — so
2913  /// the answer has to come from the type, and this is the type answering. Everything the module
2914  /// note lists as absent stays absent: what this states is a column layout, not a face.
2915  ///
2916  /// # ONE impl, and no dialect anywhere in it
2917  ///
2918  /// A fragment declares no databases, and it needs none: a width is not a dialect's fact.
2919  /// `ColumnKind` carries no parameter, so this emission is one impl rather than one per backend
2920  /// behind one gate each — and a build compiling no SQL family at all still expands it, exactly as
2921  /// it expands the accessors above.
2922  ///
2923  /// # The segments are the FIELDS' own types answering, so nesting is free
2924  ///
2925  /// Each is `shape::<FieldTy>(…)` — the same spelling a record's `COLUMNS` writes — so a fragment
2926  /// holding a fragment describes itself to whatever depth it nests, and this emission judges no
2927  /// more than the holder's does. `bounds: BoundingBox` inside `ObjectDetection` lands as a
2928  /// `Composite` whose own segments are a `Composite`, and the renderer descends twice to
2929  /// `bounds_x`; nothing here counted, joined or concatenated anything to make that happen.
2930  ///
2931  /// # `persist(flatten)` selects the OTHER spelling, and the fence comes with it
2932  ///
2933  /// [`flattened::<FieldTy>()`](Self::columns) is the same entry with its name dropped, so the inner
2934  /// mount's segments join THIS fragment's namespace. Two of them can then render one column — or
2935  /// one can meet a column the fragment already has — and neither is visible to the front end, which
2936  /// holds `classification: Classification` and cannot tell that type from a `String`. So the fence
2937  /// is the `const` one, [`ingraph::distinct`], asked once per field over the list the impl itself
2938  /// publishes.
2939  ///
2940  /// It is emitted ONLY where a field was flattened, and that is the `where`-clause discipline below
2941  /// being kept rather than an optimisation. A `const` assertion is evaluated where it is written, so
2942  /// it demands every field's `ColumnKind` row AT THE DECLARATION — which is exactly what the clause
2943  /// exists not to demand. A fragment that flattens nothing cannot collide (every field lends its own
2944  /// name, and two fields of one name is not a struct), so it pays nothing; a fragment that WROTE
2945  /// `flatten` has asserted that field's type is a composite, and the fence is what that assertion
2946  /// costs.
2947  ///
2948  /// # Each field's own answer is an OBLIGATION, so an unstorable fragment is refused at its HOLDER
2949  ///
2950  /// A field whose type has no column shape at all would otherwise make the FRAGMENT's own
2951  /// declaration fail, and a fragment nobody stores is entitled to hold such a field. Stating the
2952  /// bound in the `where` clause moves the report to where the claim is actually made: the impl
2953  /// compiles unused, and the `E0277` lands on the RECORD that stores such a fragment, naming the
2954  /// field's type. That is the discipline the query binding already follows for its record
2955  /// vocabulary.
2956  fn columns(&self, at: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
2957    let fragment = &self.fragment;
2958    let column_kind = self.framework(&["column"], "ColumnKind");
2959    let column_shape = self.framework(&["column"], "ColumnShape");
2960    let shape = self.framework(&["column"], "shape");
2961    let flattened = self.framework(&["column"], "flattened");
2962    let column_name = self.framework(&["column"], "ColumnName");
2963    let held = format_ident!("{FIELDS}");
2964
2965    // A fragment declares no databases, so it has no per-database `rename` to move a segment's
2966    // name: the two halves of the pairing are one string here, and `ColumnName::of` is what says so
2967    // — reading the name out of [`names`](Self::names) rather than spelling it a second time.
2968    let derived = self.framework(&["column"], "derived");
2969    let fragment_ty = &self.fragment;
2970    let segments = self.laid().zip(at).map(|(one, place)| {
2971      let (ty, gate) = (one.ty(), one.gate());
2972      // A COLUMN THE WRITE COMPUTES, spelled through the function that computes it. `derived` is
2973      // `shape` with the function as a parameter it never calls, and the parameter is the whole
2974      // point: `type = "…"` fixes `T` here, so a `from` returning anything else is `E0308` at the
2975      // path that named it — in a `const` no feature gates away, rather than only in the bind.
2976      if let Laid::Derived { column, .. } = one {
2977        let from = &column.from;
2978        let spanned = quote::quote_spanned!(from.span() => #from);
2979        return quote!(#gate #derived::<#fragment_ty, #ty>(#spanned, #column_name::of(#held[#place])),);
2980      }
2981      if one.flatten() {
2982        return quote!(#gate #flattened::<#ty>(),);
2983      }
2984      // TWO NAMES where a word moved one of them, and ONE where nothing did — so a fragment that
2985      // renames nothing expands token for token as it did before the word existed.
2986      let Some(field) = one.declared() else {
2987        unreachable!("a derived column answered above")
2988      };
2989      let Some(declared) = field.stored_name.as_ref().map(|_| field.column.name.to_string()) else {
2990        return quote!(#gate #shape::<#ty>(#column_name::of(#held[#place])),);
2991      };
2992      quote!(#gate #shape::<#ty>(#column_name::renamed(#declared, #column_name::of(#held[#place]).stored().as_str())),)
2993    });
2994    let obligations = self.per_type(&column_kind);
2995    let column_eq = self.framework(&["column"], "ColumnEq");
2996    let eq_obligations = self.per_type_declared(&column_eq);
2997    let sameness = self.sameness(&column_eq);
2998    let order_leaves = self.framework(&["column"], "DeclaredLeaves");
2999    let fence = self.column_fence(at);
3000    quote! {
3001      #[automatically_derived]
3002      impl #column_kind for #fragment
3003      where
3004        #obligations
3005      {
3006        const SEGMENTS: &'static [#column_shape] = &[#(#segments)*];
3007      }
3008
3009      // **ONE LEAF, AND IT IS THE VALUE** — the word that lets a cursor slot over this type be
3010      // spelled the one way every column is spelled. It states no `ColumnKind::ORDER`, so no term
3011      // over it ever expands and nothing ever asks it for a leaf narrower than itself; what the word
3012      // buys is that `<<T as DefaultMarker>::Marker as ToOrderLeaves>::Leaf` RESOLVES for it, which
3013      // is what keeps the emitted cursor free of a scalar/composite branch a macro cannot make.
3014      //
3015      // NO BOUNDS, deliberately: the `Clone` a boundary costs rides the blanket this word is the key
3016      // to, so it is asked for at the first page that holds one rather than at every declaration.
3017      #[automatically_derived]
3018      impl #order_leaves for #fragment {}
3019
3020      // **THE SAMENESS ROW**, which a holder's emitted row folds where it used to derive
3021      // `PartialEq` over its declared field types — so a fragment is a column that can be compared
3022      // without its author having derived anything, and can hold a field whose own sameness is not
3023      // `==`.
3024      //
3025      // # It walks the DECLARED fields, and the two exclusions are deliberate
3026      //
3027      // A DERIVED column is a function of the fields beside it, so it says nothing about identity
3028      // that they have not already said — and a HEAD WRITE transforms the whole value on the way to
3029      // the store, which is a fact about the columns rather than about the value the holder holds.
3030      // Comparing what the DECLARATION holds is both the narrower claim and the one the derive this
3031      // replaced made: `#[derive(PartialEq)]` on a row compared a fragment through the fragment's
3032      // own `PartialEq`, which is field-wise on exactly these fields.
3033      //
3034      // A `#[cfg]`-conditional field forks through `Condition::either` rather than an attribute,
3035      // for the reason the record's own fold does: `#[cfg]` on a TERM of an expression is
3036      // `stmt_expr_attributes` and unstable, so a removed field contributes `&&`'s identity.
3037      #[automatically_derived]
3038      impl #column_eq for #fragment
3039      where
3040        #eq_obligations
3041      {
3042        #[inline]
3043        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
3044          #sameness
3045        }
3046      }
3047
3048      #fence
3049    }
3050  }
3051
3052  /// The WORDS a holder's `CREATE TABLE` declares this fragment's columns with — one per LEAF, in
3053  /// [`ColumnKind::SEGMENTS`](Self::columns)' own order, and the concatenation of its FIELDS' own
3054  /// lists.
3055  ///
3056  /// # Why the arity is spellable here where `TimeRanged<T>`'s is not
3057  ///
3058  /// `StoredAs` records that a composite whose arity depends on a TYPE PARAMETER can have no row:
3059  /// `TimeRanged<T>` would need `4 + <T as StoredAs<Db>>::WORDS.len()` entries, and stable Rust
3060  /// refuses that length in both positions it could be named. A DECLARED fragment is the other case
3061  /// and the difference is measured rather than assumed: its parts are CONCRETE types, and a width
3062  /// carries no dialect — `ColumnKind::SEGMENTS` has no `Db` in it — so
3063  /// `width(<Self as ColumnKind>::SEGMENTS)` is an ordinary `const` even inside an impl that IS
3064  /// generic in `Db`. The LENGTH is dialect-free and the VALUES are the dialect's, which is exactly
3065  /// the split that makes one impl serve every dialect at once.
3066  ///
3067  /// So this is the assembly T1's note left to *whatever assembles a row's whole column list from
3068  /// its FIELDS — where the lengths are concrete*, at the tier that owns the fields.
3069  ///
3070  /// # It is a WALK rather than an index, and that is what admits a nested composite
3071  ///
3072  /// A part may itself span several columns — `bounds: BoundingBox` inside an `ObjectDetection` — so
3073  /// the parts are FLATTENED in order rather than read at `[0]`, and the running position is what
3074  /// makes a fragment of fragments compose to whatever depth it nests. The final `assert` holds the
3075  /// walk against the width the shape claims, which is the same agreement `spans` holds a single
3076  /// type to and the one `Table::shaped` asks of every field of a row.
3077  ///
3078  /// # ONE impl, and the obligations are the fields' own
3079  ///
3080  /// [`columns`](Self::columns)' discipline at the face beside it: each field's row is a `where`
3081  /// predicate rather than a demand made here, so a fragment holding a type no dialect declares
3082  /// still compiles and the `E0277` lands on the RECORD that stores it, naming that field's type.
3083  fn words(&self) -> proc_macro2::TokenStream {
3084    let fragment = &self.fragment;
3085    let stored_as = self.framework(&["column"], "StoredAs");
3086    let column_kind = self.framework(&["column"], "ColumnKind");
3087    let width = self.framework(&["column"], "width");
3088    let db = crate::emit::parameter("DB");
3089    let obligations = self.per_type(&quote!(#stored_as<#db>));
3090    // The same walk the segments are written from, so the two lists contract under one set of
3091    // predicates: a `#[cfg]` field leaves neither a shape without a word nor a word without a shape.
3092    let parts = self.laid().map(|one| {
3093      let (ty, gate) = (one.ty(), one.gate());
3094      quote!(#gate <#ty as #stored_as<#db>>::WORDS,)
3095    });
3096    let refusal = format!(
3097      "`{fragment}`: the words its fields declare do not fill the columns its shape claims — a \
3098       field's `StoredAs` row and its `ColumnKind` row disagree about that type's width"
3099    );
3100    quote! {
3101      #[automatically_derived]
3102      impl<#db> #stored_as<#db> for #fragment
3103      where
3104        #obligations
3105      {
3106        const WORDS: &'static [&'static ::core::primitive::str] = &{
3107          // DIALECT-FREE, which is the whole reason this row can exist: a shape carries no `Db`, so
3108          // the length is a plain `const` here where the VALUES below are the parameter's.
3109          const __INGRAPH_WIDTH__: ::core::primitive::usize =
3110            #width(<#fragment as #column_kind>::SEGMENTS);
3111          let __ingraph_parts: &[&[&'static ::core::primitive::str]] = &[#(#parts)*];
3112          let mut __ingraph_words = [""; __INGRAPH_WIDTH__];
3113          let mut __ingraph_at = 0usize;
3114          let mut __ingraph_which = 0usize;
3115          while __ingraph_which < __ingraph_parts.len() {
3116            let __ingraph_part = __ingraph_parts[__ingraph_which];
3117            let mut __ingraph_inner = 0usize;
3118            while __ingraph_inner < __ingraph_part.len() {
3119              __ingraph_words[__ingraph_at] = __ingraph_part[__ingraph_inner];
3120              __ingraph_at += 1;
3121              __ingraph_inner += 1;
3122            }
3123            __ingraph_which += 1;
3124          }
3125          ::core::assert!(__ingraph_at == __INGRAPH_WIDTH__, #refusal);
3126          __ingraph_words
3127        };
3128      }
3129    }
3130  }
3131
3132  /// **NO TWO OF THIS FRAGMENT'S RENDERED COLUMNS SHARE A NAME**, asserted where the declaration is
3133  /// written — and nothing at all where no field was flattened.
3134  ///
3135  /// # One assertion per FIELD, because a `const` message is a literal
3136  ///
3137  /// Nothing a const assertion says can be assembled from what collided, so the sentence is written
3138  /// HERE, at expansion, where the field's name is known. Asking the question one field at a time is
3139  /// what makes the assertion that fires the one that can name it — the record's own fence's
3140  /// arrangement, at this tier and for its reason.
3141  ///
3142  /// # It reads the impl's OWN const rather than a second list
3143  ///
3144  /// `<Self as ColumnKind>::SEGMENTS` is the list [`columns`](Self::columns) just published, so the
3145  /// fence and the layout cannot come to disagree. It is also what makes the obligation honest: the
3146  /// projection discharges that impl's `where` clause at this use site, so a fragment whose field
3147  /// has no column shape is `E0277` naming the type rather than `E0080` naming nothing.
3148  fn column_fence(&self, at: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
3149    if !self.laid().any(|one| one.flatten()) {
3150      return proc_macro2::TokenStream::new();
3151    }
3152    let fragment = &self.fragment;
3153    let column_kind = self.framework(&["column"], "ColumnKind");
3154    let distinct = self.framework(&["column"], "distinct");
3155    let checked = self.laid().zip(at).map(|(one, place)| {
3156      let gate = one.gate();
3157      let refusal = format!(
3158        "`{fragment}` would render `{column}` into a column one of its own fields already renders. \
3159         A `record(flatten)`ed field lends NO name, so its type's segments join this fragment's \
3160         own namespace — a segment called `x` renders `x` rather than `{column}_x` — and a value \
3161         flattened beside a column of that name occupies it twice. Drop the `flatten`, or rename \
3162         whichever column it meets.",
3163        column = self.stored_name(one),
3164      );
3165      quote!(#gate ::core::assert!(#distinct(<#fragment as #column_kind>::SEGMENTS, #place), #refusal);)
3166    });
3167    quote! {
3168      const _: () = {
3169        #(#checked)*
3170      };
3171    }
3172  }
3173
3174  /// The WRITE half of the storage face: one `Carrier<Db>` row, and the separators between a
3175  /// field's own columns.
3176  ///
3177  /// # N BINDS OUT, and the comma between them is this row's
3178  ///
3179  /// A caller writing a `VALUES` list counts FIELDS and puts a comma between them, because a field
3180  /// is what it can see. How many columns a field spans is the TYPE's answer —
3181  /// [`ColumnKind::SEGMENTS`](Self::columns), read at compile time — so a fragment pushes one
3182  /// placeholder per declared field with its own comma between them, and the `INSERT` list and the
3183  /// `VALUES` list come out the same width with neither side told the number.
3184  ///
3185  /// The two claims are stated on two traits and have to agree: a row whose shape says four columns
3186  /// and whose bind pushes three renders a statement the engine refuses to parse.
3187  ///
3188  /// # The parts bind through their OWN rows, never through a spelling here
3189  ///
3190  /// `<u32 as Carrier<Db>>::push_bind` rather than `qb.push_bind(value)`, which is what keeps a
3191  /// dialect's decision about an integer the dialect's: Postgres widens four integer widths in its
3192  /// own rows, and a composite that reached past them would be a second binding path for the same
3193  /// value. It is the framework's own instant's arrangement, read one tier out.
3194  ///
3195  /// # GENERIC in the dialect, where a hand-written composite names one
3196  ///
3197  /// The derive corpus's `Timebase` writes its comparison rows per dialect and its note says why: a
3198  /// generic header from outside the framework would overlap the framework's own rows for a backend
3199  /// that is not an `sqlx::Database`, and rustc cannot see from out there that none will arrive.
3200  /// **That is not this trait's shape.** [`Carrier<Db>`] carries `Db: sqlx::Database` in its own
3201  /// declaration and has no blanket over a bare `T`, so a fragment — a LOCAL type wherever it is
3202  /// declared — has exactly one row here and nothing to overlap. Every dialect that carries the
3203  /// parts gets the whole for free.
3204  ///
3205  /// # The FAMILY gate, rather than a dialect's and rather than none
3206  ///
3207  /// The trait is `sqlx`'s vocabulary, so a build compiling no SQL family has no trait for this to
3208  /// implement — while a build compiling two would get this impl twice if it rode the per-dialect
3209  /// gates a row's own items ride. One gate, one impl, every dialect.
3210  ///
3211  /// [`Carrier<Db>`]: https://docs.rs/ingraph/latest/ingraph/comparison/sql/trait.Carrier.html
3212  fn carrier(&self, at: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
3213    let fragment = &self.fragment;
3214    let gate = self.framework(&["gate"], "if_sqlx");
3215    let carrier = self.framework(&["comparison", "sql"], "Carrier");
3216    let database = self.framework(&["sqlx"], "Database");
3217    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
3218    let db = crate::emit::parameter("DB");
3219    let owed = self.per_type(&quote!(#carrier<#db>));
3220    let conditional = self.conditional();
3221    // THE HEAD's WRITE, at the FIRST of its two sites — the whole value transformed ONCE, before any
3222    // column is read off it, which is what makes it a whole-value seat rather than a per-column one.
3223    // The SECOND site is the cursor's write; see [`head_write`](Self::head_write) for the census that
3224    // says those two are the whole list.
3225    let (whole, receiver) = self.written();
3226    let binds = self
3227      .laid()
3228      .zip(at)
3229      .enumerate()
3230      .map(|(ordinal, (one, place))| {
3231        let (ty, gate) = (one.ty(), one.gate());
3232        // WHAT IS BOUND, and the one line the two arms differ on: a declared field binds the value
3233        // the fragment holds, and a derived column binds what its function COMPUTES off the whole
3234        // fragment. Spanned at the `from` path, so a function whose receiver or whose return type is
3235        // not what the declaration said reports at the word that named it.
3236        //
3237        // A DERIVED COLUMN READS `self`, and it reads it even under a head write. `from` is the
3238        // author's own `fn(&Self) -> U` and the head word is a different function of the same
3239        // argument, so the two are independent declarations rather than a pipeline — and the choice
3240        // is forced by which direction is RECOVERABLE: a `from` handed the value AS DECLARED can call
3241        // the head function itself, and one handed the transformed value can never get the declared
3242        // spelling back. That is the field seat's own ruling at [`write_of`](Self::write_of), stated
3243        // one level up and for the same reason.
3244        let held = match one {
3245          Laid::Declared(field) => self.held(&field.column, &receiver),
3246          Laid::Derived { column, .. } => {
3247            let from = &column.from;
3248            quote::quote_spanned!(from.span() => #from(self))
3249          }
3250        };
3251        // THE WRITE-PATH TRANSFORM, at the FIRST of its two sites. What is bound is what the
3252        // function returns, which is what makes the column canonical — and the SECOND site is the
3253        // crossing's query operand, spent through the same path by [`pair`](Self::pair) and
3254        // [`generic_pair`](Self::generic_pair). Spending it here alone stores a canonical column and
3255        // asks it in the declared spelling, which is exactly the `eq` miss the seat kills.
3256        //
3257        // A TEMPORARY is borrowed, which is what `fn(&T) -> T` means at a bind: `&write(&self.x)`
3258        // lives to the end of the statement that pushes it. The PIN is what is spelled rather than
3259        // the author's path, so the two sites read one definition and a wrong signature is reported
3260        // where the declaration named it — see [`transforms`](Self::transforms).
3261        let held = match self.write_of(one) {
3262          Some(write) => quote!(#write(&#held)),
3263          None => held,
3264        };
3265        // The COMMA is written BEFORE every part but the first, rather than after every part but the
3266        // last: the two render the same text and only this one is writable as a `for`-less walk over a
3267        // list whose length the emitter knows and the buffer does not.
3268        //
3269        // WHICH part is first is a question the predicates answer, so a fragment with a conditional
3270        // field asks the PLACE — a `const` the compiler folds — instead of the declaration ordinal a
3271        // macro can see. One with none writes the ordinal it always wrote.
3272        if !conditional {
3273          let separator = (ordinal > 0).then(|| quote!(#query_builder::push(__ingraph_qb, ", ");));
3274          return quote! {
3275            #separator
3276            <#ty as #carrier<#db>>::push_bind(&#held, __ingraph_qb);
3277          };
3278        }
3279        // A BLOCK, because the gate has to reach both statements and an attribute sits on ONE.
3280        quote! {
3281          #gate
3282          {
3283            if #place > 0 {
3284              #query_builder::push(__ingraph_qb, ", ");
3285            }
3286            <#ty as #carrier<#db>>::push_bind(&#held, __ingraph_qb);
3287          }
3288        }
3289      });
3290    quote! {
3291      #gate! {
3292        #[automatically_derived]
3293        impl<#db> #carrier<#db> for #fragment
3294        where
3295          #db: #database,
3296          #owed
3297        {
3298          fn push_bind(&self, __ingraph_qb: &mut #query_builder<#db>) {
3299            #whole
3300            #(#binds)*
3301          }
3302        }
3303      }
3304    }
3305  }
3306
3307  /// The READ half of the storage face: one `Assemble` row, one fetch per field, and the HYDRATION
3308  /// the construction protocol writes.
3309  ///
3310  /// # The parameter is the ROW, where the bind's is the dialect
3311  ///
3312  /// That asymmetry is the two traits' own rather than a choice made here. A bind is a dialect's
3313  /// fact — a cast, a placeholder syntax — and a read is [`sqlx::Row`]'s method, which already names
3314  /// its own `Database`. Naming the dialect instead would have put `R::Database` in every bound and
3315  /// left the one type a read actually needs unspellable.
3316  ///
3317  /// # `under` arrives as a PATH, so one body serves both layouts
3318  ///
3319  /// The segments above this value come in as the same cons list the `SELECT` descended, so a field
3320  /// that lends its name reads `frame_width` and one the holder wrote `persist(<db>(flatten))` on
3321  /// reads bare `width` — and nothing here knows which. That is what makes the read the exact twin
3322  /// of the column list rather than a second rule that agrees today.
3323  ///
3324  /// # The columns are read into LOCALS, and the value is built from them
3325  ///
3326  /// Not a struct literal with the reads inline, and the reason is the REWRITE: a wrapped fragment
3327  /// is built by calling somebody else's constructor, and a constructor takes ARGUMENTS. Reading
3328  /// each column into a local named for its field gives both modes one shape to build from — the
3329  /// literal spells them as members, the protocol spells them as arguments — and it puts the `?` on
3330  /// its own line, where a failure names the column that failed.
3331  ///
3332  /// The locals are the FIELDS' own names, which is what lets the own-mode literal use the field
3333  /// shorthand and the wrapped mode hand the protocol a value keyed by the same name.
3334  fn assemble(&self, at: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
3335    let fragment = &self.fragment;
3336    let gate = self.framework(&["gate"], "if_sqlx");
3337    let assemble = self.framework(&["column"], "Assemble");
3338    let assembled = self.framework(&["column"], "assembled");
3339    let assembled_flattened = self.framework(&["column"], "assembled_flattened");
3340    let path = self.framework(&["comparison"], "Path");
3341    let result = self.framework(&["sqlx"], "Result");
3342    let row_trait = self.framework(&["sqlx"], "Row");
3343    let row = crate::emit::parameter("ROW");
3344    let held = format_ident!("{FIELDS}");
3345    let bound = quote!(#assemble<'__ingraph, #row>);
3346    let owed = self.per_type_declared(&bound);
3347    // THE DERIVED COLUMNS ARE NOT READ, and this is where that is said. The layout's places are one
3348    // per COLUMN; the read walks the declared FIELDS, so the derived entries are dropped here rather
3349    // than tested for below — the value is rebuilt from the fields the declaration holds, and a
3350    // column computed off them has nothing to be rebuilt into.
3351    let declared: Vec<&proc_macro2::TokenStream> = self
3352      .laid()
3353      .zip(at)
3354      .filter_map(|(one, place)| one.declared().map(|_| place))
3355      .collect();
3356    let mut places = declared.into_iter();
3357    let reads = self.fields.iter().enumerate().map(|(ordinal, field)| {
3358      let (source, ty, gate) = (
3359        &field.column.source,
3360        &field.column.ty,
3361        field.condition.gate(),
3362      );
3363      // A SKIPPED column is not in the row, so the read SUPPLIES the value instead of fetching one —
3364      // the record seat's own `skip(default = "…")` law, spanned at the word that skipped it, so a
3365      // type with no `Default` is `E0277` there rather than inside this expansion.
3366      if let Some(fill) = field.skip.as_ref() {
3367        let filled = fill.value(ty);
3368        return quote! {
3369          #gate
3370          let #source: #ty = #filled;
3371        };
3372      }
3373      let place = places.next().expect("a stored field has a place");
3374      // THE READ-PATH MIRROR, and the one face it reaches. `record(read = "…")` is for the
3375      // household whose stored form is not a domain form; ABSENT is the IDENTITY, which is what a
3376      // canonicalisation wants — a reduced rational is a valid `Rate`, so nothing is undone coming
3377      // out. Spelled through the PIN for the bind's reason.
3378      let read = field
3379        .read
3380        .as_ref()
3381        .map(|_| Self::transform_name("READ", ordinal));
3382      let through = |fetched: proc_macro2::TokenStream| match read.as_ref() {
3383        Some(read) => quote!(#read(&#fetched)),
3384        None => fetched,
3385      };
3386      // The ANNOTATION is load-bearing: it is what fixes which `Assemble` row runs, exactly as it is
3387      // in a record's own decode.
3388      //
3389      // A FLATTENED field pushes no segment, which is the read half of `flattened::<Ty>()`: its
3390      // columns are named in this fragment's own namespace, so the path arrives unchanged.
3391      if field.flatten {
3392        let fetched = through(quote!(#assembled_flattened(__ingraph_row, __ingraph_under)?));
3393        return quote! {
3394          #gate
3395          let #source: #ty = #fetched;
3396        };
3397      }
3398      let fetched = through(quote!(#assembled(__ingraph_row, #held[#place], __ingraph_under)?));
3399      quote! {
3400        #gate
3401        let #source: #ty = #fetched;
3402      }
3403    });
3404    // THE HEAD's READ MIRROR, LAST — after every column has come back through its own `read` and the
3405    // value has been rebuilt, because a `fn(&Self) -> Self` needs a `Self` and the raise is where the
3406    // first one exists. That ordering is the exact INVERSE of the write path's, where the head runs
3407    // FIRST and each column's own `write` runs on what it returned; a pair spent in one order going
3408    // in and the other coming out is what makes a round trip a round trip.
3409    let built = self.raised(self.raise());
3410    quote! {
3411      #gate! {
3412        #[automatically_derived]
3413        impl<'__ingraph, #row> #assemble<'__ingraph, #row> for #fragment
3414        where
3415          #row: #row_trait,
3416          #owed
3417        {
3418          fn assemble(
3419            __ingraph_row: &'__ingraph #row,
3420            __ingraph_under: ::core::option::Option<&#path<'_>>,
3421          ) -> #result<Self> {
3422            #(#reads)*
3423            ::core::result::Result::Ok(#built)
3424          }
3425        }
3426      }
3427    }
3428  }
3429
3430  /// The VALUE, built out of one local per field — a struct literal, or somebody else's constructor.
3431  ///
3432  /// # An own fragment is built LITERALLY, and that is the tier's definition doing the work
3433  ///
3434  /// A declared fragment IS its fields: every one of them is in scope, the type is this expansion's
3435  /// own, and there is no call sequence for a word to describe. So the raise is the struct literal
3436  /// and the construction vocabulary is refused on such a declaration BY NAME rather than accepted
3437  /// and ignored — see `ingraph_derive`'s `construct::refuse_without_a_remote`.
3438  ///
3439  /// # A wrapped one goes through the SADDLE, which is the record rung's own
3440  ///
3441  /// [`crate::remote::build`] writes the call: the entry, the finish, the links, the injections, the
3442  /// crossing per column and the seat's default law. Nothing about it is a record's — that is why it
3443  /// was lowered out of `impl RecordModel` when this mount arrived — so a fragment's hydration and a
3444  /// record's are one protocol with two walks that fill it.
3445  ///
3446  /// The CONDITION rides each value, in both shapes: a struct literal's field is a legal attribute
3447  /// position and so is a protocol ingredient's, so a build that removed a field builds the value
3448  /// without it — a member the literal never names, an argument the call never passes. The protocol
3449  /// unrolls for a gate exactly as it does one rung up, and for a `set` link the same way.
3450  fn raise(&self) -> proc_macro2::TokenStream {
3451    let Some(remote) = self.remote.as_ref() else {
3452      let members = self.fields.iter().map(|field| {
3453        let (source, gate) = (&field.column.source, field.condition.gate());
3454        quote!(#gate #source,)
3455      });
3456      return quote!(Self { #(#members)* });
3457    };
3458    let ingredients: Vec<Ingredient<'_>> = self
3459      .fields
3460      .iter()
3461      .map(|field| {
3462        let column = &field.column;
3463        let source = &column.source;
3464        Ingredient {
3465          source,
3466          ty: &column.ty,
3467          optional: matches!(column.project, crate::model::Projection::Optional),
3468          build: &field.build,
3469          gate: field.condition.gate(),
3470          value: quote!(#source),
3471        }
3472      })
3473      .collect();
3474    crate::remote::build(remote, &self.construction, &ingredients)
3475  }
3476
3477  /// The KEYSET position — [`CursorValue`], emitted only where the declaration asked for one.
3478  ///
3479  /// # OPT-IN, because a group of fields has no order of its own
3480  ///
3481  /// Every other face here is a CONSEQUENCE: a width, a predicate, a bind and a read all follow from
3482  /// the fields being declared at all, and a fragment gets them whether it wanted them or not. An
3483  /// ORDER does not follow from anything. Nothing about `{width, height}` says which of two
3484  /// dimensions a page should walk first, and a framework that picked one would be answering a
3485  /// question the declaration never asked — so the word is the author's assertion that the order they
3486  /// wrote is the one legitimate total order over this value, and a fragment that made no such
3487  /// assertion has no row here.
3488  ///
3489  /// What the absence COSTS is stated where it is felt rather than here: a record that stores such a
3490  /// fragment unflattened makes it an order subject, and the missing row is the `E0277`
3491  /// [`CursorValue`]'s own `on_unimplemented` names, pointing at this word and at
3492  /// `persist(<db>(flatten))` as the two answers.
3493  ///
3494  /// # The bytes are the MEMBERS, each behind its own length
3495  ///
3496  /// One `write_member` per key column, in the key's order, and one `read_member` back. The framing
3497  /// is the framework's — the same pair a variable-width collection's row spends — and it is paid
3498  /// per member rather than divided out of a fixed width because an EMISSION cannot know a width:
3499  /// `u32` and `String` are the same tokens here. Four bytes a member buys a read that REFUSES a
3500  /// frame this type did not write, which is the whole standard a cursor codec is held to.
3501  ///
3502  /// A trailing byte is a refusal for the same reason: everything the key claimed has been read, so
3503  /// anything left is bytes no member owns.
3504  ///
3505  /// # The value is rebuilt through the SAME raise the decode uses
3506  ///
3507  /// [`raise`](Self::raise) — the struct literal for an own fragment and the construction protocol
3508  /// for a wrapped one — so a cursor and a row rebuild the value one way. A wrapped fragment whose
3509  /// protocol is fallible is the one shape this cannot serve, and it is refused at the declaration
3510  /// rather than papered over: `read_cursor` answers an `Option` with no error road for the `?` to
3511  /// take.
3512  ///
3513  /// # A MOUNTED CODEC replaces the FRAMING, and it does so PER DIALECT
3514  ///
3515  /// `record(<db>(cursor = "…"))` names a type that writes these bytes at ONE store. A declaration
3516  /// that mounts one anywhere therefore stops having a single byte form, and this seat forks:
3517  ///
3518  /// | the declaration | what it emits |
3519  /// |---|---|
3520  /// | no `cursor = "…"` anywhere | ONE `CursorValue` row, framed — token for token what it always emitted |
3521  /// | a codec at any dialect | one `DialectCursor<Db>` row per DECLARED dialect, and NO `CursorValue` |
3522  ///
3523  /// The fork is total rather than additive because the two are `E0119` on one type: the blanket
3524  /// `impl<Db, T: CursorValue> DialectCursor<Db> for T` covers every value whose bytes are the same
3525  /// everywhere, so a type carrying both rows would answer *which bytes does a page spend* twice.
3526  /// Measured before it was designed around — a local type with no `CursorValue` row takes its own
3527  /// per-dialect rows without conflict, because only the crate that owns a type can give it one.
3528  ///
3529  /// What a fragment loses with `CursorValue` is the DIALECT-FREE face: `Cursor::<Fragment>` and any
3530  /// hand-written caller asking for one. That is the honest reading of what the declaration said —
3531  /// *my bytes are the engine's* — and every caller inside this framework asks at a dialect already.
3532  ///
3533  /// A dialect the declaration NAMED but mounted nothing at rides the framed body, so mixed states
3534  /// are ordinary: dense at SQLite, framed at PostgreSQL, each walking its own pages. A dialect it
3535  /// never named has no row and is `E0277` at the record that stores it there — the tier's own
3536  /// *which dialects this fragment is BUILT for* arriving one seat over.
3537  ///
3538  /// [`CursorValue`]: https://docs.rs/ingraph/latest/ingraph/trait.CursorValue.html
3539  fn keyset(&self) -> proc_macro2::TokenStream {
3540    let Some(key) = self.cursor.as_ref() else {
3541      return proc_macro2::TokenStream::new();
3542    };
3543    // The KEY's own order, which the bare word makes the declaration's. Resolved against the columns
3544    // rather than trusted: the front end has already refused a list that is not this declaration's
3545    // fields in this declaration's order, so the lookup below cannot miss.
3546    let members: Vec<&Column> = if key.is_empty() {
3547      self.declared().collect()
3548    } else {
3549      key
3550        .iter()
3551        .filter_map(|named| self.declared().find(|column| &column.name == named))
3552        .collect()
3553    };
3554    let single = self.plain_positions(&members);
3555    let audit = self.codec_audits();
3556    let rows = match self.mounts_a_codec() {
3557      true => self.per_dialect_keyset(&members),
3558      false => self.uniform_keyset(&members),
3559    };
3560    quote! {
3561      #single
3562
3563      #audit
3564
3565      #rows
3566    }
3567  }
3568
3569  /// Whether ANY dialect group named a codec — the predicate the keyset's fork turns on.
3570  fn mounts_a_codec(&self) -> bool {
3571    self
3572      .record
3573      .as_ref()
3574      .is_some_and(|host| host.databases.iter().any(|built| built.cursor.is_some()))
3575  }
3576
3577  /// **THE DIALECT-FREE ROW** — one `CursorValue`, framed, for the declaration that mounted nothing.
3578  ///
3579  /// Byte for byte what this tier emitted before the codec seat existed, which is the whole of what
3580  /// the seat costs a declaration without it.
3581  fn uniform_keyset(&self, members: &[&Column]) -> proc_macro2::TokenStream {
3582    let fragment = &self.fragment;
3583    let cursor_value = self.framework(&["cursor"], "CursorValue");
3584    let owed = self.per_type(&cursor_value);
3585    let (whole, receiver) = self.written();
3586    let (write, read) = self.framed_bodies(members, &receiver);
3587    quote! {
3588      #[automatically_derived]
3589      impl #cursor_value for #fragment
3590      where
3591        #owed
3592      {
3593        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
3594          #whole
3595          #write
3596        }
3597
3598        fn read_cursor(
3599          __ingraph_bytes: &[::core::primitive::u8],
3600        ) -> ::core::option::Option<Self> {
3601          #read
3602        }
3603      }
3604    }
3605  }
3606
3607  /// **ONE ROW PER DECLARED DIALECT** — the mounted codec where one was named, the frame where none
3608  /// was.
3609  ///
3610  /// # UNGATED, all of it — the seam names a MARKER, never a driver
3611  ///
3612  /// The comparison pair's concrete arm rides its dialect's feature gate because it names a BACKEND,
3613  /// and `sqlx::Postgres` does not exist in a build that compiled that dialect out. This seam names
3614  /// `cursor::dialect::Postgres`, which always does: `ingraph::cursor` is compiled under no backend's
3615  /// feature at all. So a declaration's cursor rows — and the refusals about them — read the same in
3616  /// every build, which is the rule [`transforms`](Self::transforms) states for the pins.
3617  fn per_dialect_keyset(&self, members: &[&Column]) -> proc_macro2::TokenStream {
3618    let Some(host) = self.record.as_ref() else {
3619      return proc_macro2::TokenStream::new();
3620    };
3621    let fragment = &self.fragment;
3622    let cursor_value = self.framework(&["cursor"], "CursorValue");
3623    let dialect_cursor = self.framework(&["cursor"], "DialectCursor");
3624    let (whole, receiver) = self.written();
3625    let rows = host.databases.iter().map(|built| {
3626      let (module, item) = built.kind.dialect();
3627      let dialect = self.framework(module, item);
3628      // THE CLAUSE parts with the body. A framed row calls each member type's own `CursorValue`, so
3629      // it owes one predicate per distinct column type; a mounted one calls none of them and owes
3630      // nothing — which is what lets a household page past a value whose components have no row.
3631      let (owed, write, read) = match built.cursor.as_ref() {
3632        Some(codec) => self.mounted_bodies(codec, &receiver),
3633        None => {
3634          let (write, read) = self.framed_bodies(members, &receiver);
3635          (self.per_type(&cursor_value), write, read)
3636        }
3637      };
3638      let owed = (!owed.is_empty()).then(|| quote!(where #owed));
3639      quote! {
3640        #[automatically_derived]
3641        impl #dialect_cursor<#dialect> for #fragment
3642        #owed
3643        {
3644          fn write_cursor_at(
3645            &self,
3646            __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>,
3647          ) {
3648            #whole
3649            #write
3650          }
3651
3652          fn read_cursor_at(
3653            __ingraph_bytes: &[::core::primitive::u8],
3654          ) -> ::core::option::Option<Self> {
3655            #read
3656          }
3657        }
3658      }
3659    });
3660    quote!(#(#rows)*)
3661  }
3662
3663  /// **THE FRAMED PAIR** — one `write_member` per key column and one `read_member` back.
3664  ///
3665  /// One function for both arms of the fork, so the default a mounted dialect's neighbour rides is
3666  /// the SAME bytes the dialect-free row writes rather than a second copy of the walk.
3667  fn framed_bodies(
3668    &self,
3669    members: &[&Column],
3670    receiver: &syn::Ident,
3671  ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
3672    let write_member = self.framework(&["cursor"], "write_member");
3673    let read_member = self.framework(&["cursor"], "read_member");
3674    let writes = members.iter().map(|column| {
3675      let held = self.held(column, receiver);
3676      quote!(#write_member(&#held, __ingraph_out);)
3677    });
3678    let reads = members.iter().map(|column| {
3679      let (source, ty) = (&column.source, &column.ty);
3680      quote!(let #source: #ty = #read_member(&mut __ingraph_rest)?;)
3681    });
3682    // AND THE MIRROR at the read, on the value the bytes rebuilt — the raise's own arrangement, one
3683    // face over: a cursor's bytes hold what the COLUMNS hold, so what comes back out of them owes the
3684    // same journey back to a domain form that a fetched row does.
3685    let built = self.raised(self.raise());
3686    (
3687      quote!(#(#writes)*),
3688      quote! {
3689        let mut __ingraph_rest = __ingraph_bytes;
3690        #(#reads)*
3691        // Everything the key claimed has been read, so anything left is bytes no member owns —
3692        // which is a frame this type did not write.
3693        if !<[::core::primitive::u8]>::is_empty(__ingraph_rest) {
3694          return ::core::option::Option::None;
3695        }
3696        ::core::option::Option::Some(#built)
3697      },
3698    )
3699  }
3700
3701  /// **THE DELEGATING BODIES** — the codec's two calls, and the three things around them that do not
3702  /// move.
3703  ///
3704  /// # What the mount replaces: the FRAMING, and only the framing
3705  ///
3706  /// The framed default pays four bytes a member because an EMISSION cannot know a width. A codec's
3707  /// author can, so what the word buys is those bytes and the walk that writes them. Everything else
3708  /// about this row is unchanged, and each of the three is load-bearing:
3709  ///
3710  /// | still spent | why a mount does not touch it |
3711  /// |---|---|
3712  /// | the HEAD WRITE prologue | the mount is a spelling in BYTES, and the two-site agreement is about which VALUE gets spelled — a codec handed the declared value would encode a boundary the bind never wrote |
3713  /// | the HEAD READ mirror | the same seam coming back: what a codec decodes is the STORED value, and the domain form is one call further on, exactly as a fetched row's is |
3714  /// | [`plain_positions`](Self::plain_positions) | a width refusal about the SQL keyset's column order, which a byte form has no bearing on |
3715  fn mounted_bodies(
3716    &self,
3717    codec: &syn::Path,
3718    receiver: &syn::Ident,
3719  ) -> (
3720    proc_macro2::TokenStream,
3721    proc_macro2::TokenStream,
3722    proc_macro2::TokenStream,
3723  ) {
3724    let cursor_codec = self.framework(&["cursor"], "CursorCodec");
3725    let built = self.raised(quote!(__ingraph_decoded));
3726    (
3727      // The `where` CLAUSE — empty by ruling rather than by oversight; see the note at the caller.
3728      proc_macro2::TokenStream::new(),
3729      quote!(<#codec as #cursor_codec<Self>>::encode(#receiver, __ingraph_out);),
3730      quote! {
3731        let __ingraph_decoded: Self =
3732          <#codec as #cursor_codec<Self>>::decode(__ingraph_bytes)?;
3733        ::core::option::Option::Some(#built)
3734      },
3735    )
3736  }
3737
3738  /// **EACH MOUNT AUDITED AT THE STRING ITS OWN AUTHOR WROTE** — one witness per dialect that named
3739  /// a codec.
3740  ///
3741  /// # It is per MOUNT, because each mount is its own claim
3742  ///
3743  /// A declaration may mount a different codec at every store, so a report at one of them would say
3744  /// nothing about the others. The number is the dialect's INDEX at the head, for
3745  /// [`mount_audit`](Self::mount_audit)'s reason: two traits of one name in one scope is `E0428`, and
3746  /// an index keeps a witness's name when a neighbouring dialect gains or loses a mount.
3747  ///
3748  /// # UNGATED, like the rows it audits
3749  ///
3750  /// [`mount_audit`](Self::mount_audit) rides its dialect's feature gate because what it demands
3751  /// names a BACKEND — `ComplexComparison<Sqlite>` does not exist in a build without `sqlite`. This
3752  /// obligation names none: `CursorCodec<Self>` is a fact about the VALUE's bytes and carries no
3753  /// database at all. So the audit is unconditional, which is the rule
3754  /// [`transforms`](Self::transforms) states for the pins — **a declaration's refusals may not depend
3755  /// on a feature set**.
3756  fn codec_audits(&self) -> proc_macro2::TokenStream {
3757    let Some(host) = self.record.as_ref() else {
3758      return proc_macro2::TokenStream::new();
3759    };
3760    let fragment = &self.fragment;
3761    let cursor_codec = self.framework(&["cursor"], "CursorCodec");
3762    let rows = host
3763      .databases
3764      .iter()
3765      .enumerate()
3766      .filter_map(|(nth, built)| {
3767        let codec = built.cursor.as_ref()?;
3768        let db = built.kind.as_str();
3769        Some(self.witness(
3770          codec,
3771          &format_ident!("__IngraphMountedCursor{nth}"),
3772          &quote!(#cursor_codec<#fragment>),
3773          &format!(
3774            "`{{Self}}` is what `{fragment}` mounts as its `{db}` cursor codec, and it does not \
3775           answer that seat"
3776          ),
3777          "this type writes no cursor bytes for this fragment",
3778          &format!(
3779            "`{db}(cursor = \"…\")` replaces the framed default this tier writes at `{db}` — one \
3780           length-prefixed member per key column — so the type it names owes the whole byte form: \
3781           `ingraph::CursorCodec<{fragment}>`, whose `encode` appends this value's bytes and whose \
3782           `decode` reads them back. The two are ONE implementor because they are duals, and \
3783           `decode` is handed a CLIENT's bytes: it checks its own width and refuses with `None`, a \
3784           plausible value for bytes it did not write being how a forged cursor becomes a page"
3785          ),
3786        ))
3787      });
3788    quote!(#(#rows)*)
3789  }
3790
3791  /// **A KEY MEMBER IS ONE COLUMN**, asserted at the declaration for every member the key names.
3792  ///
3793  /// # What it refuses, and why the missing `CursorValue` row stopped being enough
3794  ///
3795  /// A member whose type spans several columns is a NESTED key, and until this knife a fragment
3796  /// could not hold one that was also a paging position: the inner value had no `CursorValue` row
3797  /// unless it declared `cursor`, and nothing that declared `cursor` was reachable as a member. The
3798  /// nesting recursion makes it reachable, so the refusal has to be POSITIVE — an inner fragment
3799  /// that wrote `cursor` satisfies the clause and would otherwise slip straight through.
3800  ///
3801  /// What stands in the way is a layout question rather than a codec one. The bytes would round-trip
3802  /// perfectly: each member is framed, and a nested one frames its own members inside that. The SQL
3803  /// keyset is the half with no answer — it compares this value's columns in the order `SEGMENTS`
3804  /// states and binds them in the order `Carrier` pushes, and for a nested member those two orders
3805  /// are the INNER declaration's, resumed at a boundary the outer statement composed. Which of the
3806  /// two follows the other is exactly the layout ruling `cursor`'s list form was held for. So the
3807  /// answer here is *not yet*, said by name, rather than a page that renders and resumes wrongly.
3808  ///
3809  /// # It is spelled as a WIDTH, because the front end holds tokens
3810  ///
3811  /// `Dimensions` and `String` are the same tokens, so *is this a fragment* is not a question the
3812  /// macro can ask — `SEGMENTS.is_empty()` is, at the one place the answer exists. The reading is
3813  /// therefore wider than the ruling's word by exactly one type: the framework's own
3814  /// [`Timestamp`](https://docs.rs/ingraph/latest/ingraph/struct.Timestamp.html) is a composite too,
3815  /// and a `cursor` fragment holding one is refused here beside a nested fragment. That is the
3816  /// honest breadth — the two are one shape at the keyset, and a rule that let one through would be
3817  /// a rule about a name rather than about a layout.
3818  ///
3819  /// Nothing is emitted for a fragment that wrote no `cursor`: a member's width is only a question
3820  /// where a key names it.
3821  fn plain_positions(&self, members: &[&Column]) -> proc_macro2::TokenStream {
3822    let fragment = &self.fragment;
3823    let column_kind = self.framework(&["column"], "ColumnKind");
3824    let checked = members.iter().map(|column| {
3825      let (name, ty) = (&column.name, &column.ty);
3826      let refusal = format!(
3827        "`{name}` spans more than one column, so it cannot be part of `{fragment}`'s cursor key — a \
3828         key member is ONE column's value, and a member that spans several is a NESTED key. The \
3829         bytes would round-trip; the SQL keyset would not, because the order it compares a nested \
3830         member's columns in and the order it binds them in are the INNER declaration's, and which \
3831         of the two the other follows is not ruled. Writing `cursor` on the inner value does not \
3832         rule it. Drop `{name}` from the key, or drop the `cursor` word: a fragment without one is \
3833         stored, filtered and read back exactly as before, and is simply not a paging position"
3834      );
3835      quote!(::core::assert!(<#ty as #column_kind>::SEGMENTS.is_empty(), #refusal);)
3836    });
3837    quote! {
3838      const _: () = {
3839        #(#checked)*
3840      };
3841    }
3842  }
3843
3844  /// ONE column's value, as an expression over `&self` — the one seam a rewrite moves, read by every
3845  /// emission that spends a value rather than a type.
3846  ///
3847  /// A held field is a PLACE (`self.width`) and a manifest field is a CALL (`Self::width(self)`),
3848  /// and the callers here all want a borrow of one: `&self.width` borrows storage, and
3849  /// `&Self::width(self)` borrows a temporary that lives as long as the argument it is passed as.
3850  ///
3851  /// `Self::#name(self)` rather than `self.#name()`, for [`wire`](Self::wire)'s reason: a rewrite's
3852  /// wrapper DEREFS to the remote, and a fully qualified call cannot be resolved through that seam
3853  /// by accident.
3854  /// The RECEIVER is a parameter because the head write moves exactly this seam:
3855  /// `record(write = "…")` binds the transformed value to a local and every DECLARED column reads it
3856  /// off that instead of off `self`. It is a `&Self` either way, so a place stays a place and a call
3857  /// stays a call. See [`written`](Self::written).
3858  /// The body of the fragment's [`ColumnEq`] row: one `column_eq` per DECLARED field, folded with
3859  /// `&&`.
3860  ///
3861  /// Both sides are read through [`held`](Self::held), so a REWRITE reads its accessor and an
3862  /// ordinary fragment reads its field — one seam, as every other walk over these fields takes.
3863  ///
3864  /// A fragment with no declared field at all compares equal, which is what an empty `&&` fold
3865  /// means and what a unit-shaped composite should say.
3866  ///
3867  /// [`ColumnEq`]: https://docs.rs/ingraph
3868  fn sameness(&self, column_eq: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
3869    let mine = format_ident!("self");
3870    let theirs = format_ident!("__ingraph_other");
3871    let same = quote!(true);
3872    let comparisons: Vec<proc_macro2::TokenStream> = self
3873      .laid()
3874      .filter_map(|one| {
3875        let condition = one.condition();
3876        let ty = one.ty();
3877        let field = one.declared()?;
3878        let lhs = self.held(&field.column, &mine);
3879        let rhs = self.held(&field.column, &theirs);
3880        let compared = quote::quote_spanned! {field.column.name.span()=>
3881          <#ty as #column_eq>::column_eq(&#lhs, &#rhs)
3882        };
3883        Some(condition.either(&compared, &same))
3884      })
3885      .collect();
3886    if comparisons.is_empty() {
3887      return same;
3888    }
3889    quote!(#(#comparisons)&&*)
3890  }
3891
3892  fn held(&self, column: &Column, receiver: &syn::Ident) -> proc_macro2::TokenStream {
3893    let (name, source) = (&column.name, &column.source);
3894    if self.remote.is_some() {
3895      quote!(Self::#name(#receiver))
3896    } else {
3897      quote!(#receiver.#source)
3898    }
3899  }
3900
3901  /// The SEGMENT NAMES, as one `const` every face that needs a name reads.
3902  ///
3903  /// # One list, three readers, and the drift it makes unspellable
3904  ///
3905  /// A fragment's column names are spent three times over: the WIDTH names them into
3906  /// [`ColumnKind::SEGMENTS`](Self::columns) — which is what a holder's `SELECT` and its `INSERT`
3907  /// list both descend — and the READ fetches each one by name ([`assemble`](Self::assemble)). Two
3908  /// spellings of `"width"` would be two places for a rename to be forgotten, and the forgetting is
3909  /// silent in the worst direction: a statement that selects `frame_width` beside a decode that
3910  /// fetches `frame_wdith` compiles perfectly and fails at the first row.
3911  ///
3912  /// So the names are minted ONCE and everything else indexes this. It is the arrangement the
3913  /// framework's own composite already has — [`Timestamp`] keeps `SECOND` and `NANOSECOND` beside
3914  /// its `SEGMENTS` and its decode reads both — written by the emitter instead of by hand.
3915  ///
3916  /// # A SLICE indexed by position, rather than one `const` per field
3917  ///
3918  /// A `const` apiece would have to be NAMED, and the only name available is the field's own,
3919  /// upper-cased. `myField` and `my_field` upper-case to ONE identifier, so two legal fields could
3920  /// mint one `const` — a duplicate definition inside an expansion, at a span the author cannot
3921  /// edit. A position cannot collide, and the line that spends it says which field it is.
3922  ///
3923  /// [`Timestamp`]: https://docs.rs/ingraph/latest/ingraph/struct.Timestamp.html
3924  fn names(&self) -> proc_macro2::TokenStream {
3925    // A FLATTENED field lends no name, so neither the width nor the read indexes its entry — and a
3926    // fragment whose every field is flattened indexes none of them at all. The list is then a
3927    // `const` nothing spends, which is `dead_code` inside an expansion its author cannot annotate.
3928    // Its entries stay POSITIONAL whenever it is written, so `[at]` is the field's own ordinal
3929    // whether or not the fields before it lent their names.
3930    if self.laid().all(|one| one.flatten()) {
3931      return proc_macro2::TokenStream::new();
3932    }
3933    let field_name = self.framework(&["field"], "FieldName");
3934    let held = format_ident!("{FIELDS}");
3935    let names = self.laid().map(|one| {
3936      // The STORED name, which is what a statement renders and a read fetches by. Where nothing
3937      // moved it the two names are one string and this is the field's own; `record(rename = "…")`
3938      // moves this one and leaves the DECLARED axis to `ColumnName`. A DERIVED column's is the word
3939      // that named it, which is its only axis.
3940      let (name, gate) = (self.stored_name(one), one.gate());
3941      quote!(#gate #field_name::new(#name),)
3942    });
3943    // A build whose predicates removed every field that LENDS a name leaves this list written and
3944    // unindexed, which is `dead_code` inside an expansion its author cannot annotate. The allow is
3945    // written only where a condition exists, so an ordinary fragment's expansion is unchanged.
3946    let unindexable = self
3947      .conditional()
3948      .then(|| quote!(#[allow(dead_code, reason = "a predicate may remove every named field")]));
3949    quote! {
3950      #unindexable
3951      const #held: &[&'static #field_name] = &[#(#names)*];
3952    }
3953  }
3954
3955  /// One predicate per DISTINCT COLUMN type, each owing `bound` — a repeated type says nothing the
3956  /// first said, and a `where` clause that stated it twice would report one missing row twice.
3957  ///
3958  /// Compared as TOKENS, which is the only comparison a macro has: `u32` and a `type Width = u32`
3959  /// are one type to the compiler and two spellings here, so the de-duplication is conservative in
3960  /// the direction that costs a duplicate predicate rather than a missing one.
3961  ///
3962  /// # A DERIVED column's type is in the union, and that is what makes its bind writable
3963  ///
3964  /// The bind is emitted inside a `Carrier<DB>` row generic in its dialect, so the obligation
3965  /// `T: Carrier<DB>` has to come off this clause — nothing about a generic `DB` proves it. That is
3966  /// the whole reason the `derived` word writes `type = "…"` when the function already carries the
3967  /// answer: a `where` clause names TYPES, and stable Rust has no spelling for a function's return.
3968  fn per_type(&self, bound: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
3969    self.owed(self.laid().map(|one| one.ty()), bound)
3970  }
3971
3972  /// [`per_type`](Self::per_type) over the DECLARED fields alone — the READ's clause.
3973  ///
3974  /// A derived column is never fetched, so demanding an `Assemble` row for its type would be a
3975  /// declaration asking for a capability nothing it emits ever reaches. The two clauses part exactly
3976  /// where the two walks part.
3977  fn per_type_declared(&self, bound: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
3978    self.owed(self.stored().map(|field| &field.column.ty), bound)
3979  }
3980
3981  /// The de-duplicating fold both clauses spend.
3982  fn owed<'a>(
3983    &self,
3984    types: impl Iterator<Item = &'a syn::Type>,
3985    bound: &proc_macro2::TokenStream,
3986  ) -> proc_macro2::TokenStream {
3987    let mut seen: Vec<String> = Vec::new();
3988    let mut owed = proc_macro2::TokenStream::new();
3989    for ty in types {
3990      let spelled = quote!(#ty).to_string();
3991      if seen.contains(&spelled) {
3992        continue;
3993      }
3994      seen.push(spelled);
3995      owed.extend(quote!(#ty: #bound,));
3996    }
3997    owed
3998  }
3999
4000  /// This fragment's shelf path to `name` — the same helper a record's emission reaches the
4001  /// framework through.
4002  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
4003    crate::emit::framework(&self.krate, module, name)
4004  }
4005
4006  /// Every method this emission declares, for the front end that has to refuse a collision before
4007  /// an expansion lands two of one name in a scope its author cannot edit.
4008  ///
4009  /// The walk a record's own drives, over ONE owner instead of seven: a fragment declares one impl,
4010  /// on itself. The hazard is identical — a field called `x` beside a `copy` field called `x` gives
4011  /// the type two `set_x` — and so is the answer.
4012  ///
4013  /// A REWRITE forks here exactly where [`readers`](Self::readers) forks and on the same predicate,
4014  /// which is what keeps the enumeration a statement about the emission rather than a second
4015  /// reading of the rule: one name per manifest field, the field's own, because a wrapper declares
4016  /// one reader and no member beside it.
4017  #[must_use]
4018  pub fn emitted_methods(&self) -> Vec<Emitted> {
4019    // The SEAT's own names, on BOTH sides of the fork and whether the entry mints or not. An entry
4020    // the emission mints declares the name here; one it does not — an ordinary fragment's, or a
4021    // rewrite's `on = self` — names a method the author must have written on `Self`, which collides
4022    // with an emitted accessor of that name exactly as a mint would. One walk, one hazard.
4023    let delegated = self.delegates.iter().map(|delegate| {
4024      let method = &delegate.signature.ident;
4025      Emitted {
4026        owner: Owner::Record,
4027        owner_name: self.fragment.clone(),
4028        name: method.clone(),
4029        origin: Origin::Delegate(method.clone()),
4030      }
4031    });
4032    if self.remote.is_some() {
4033      return self
4034        .declared()
4035        .map(|column| Emitted {
4036          owner: Owner::Record,
4037          owner_name: self.fragment.clone(),
4038          name: Member::Value.name(&column.name),
4039          origin: Origin::Column(ColumnOrigin {
4040            column: column.name.clone(),
4041            member: Member::Value,
4042          }),
4043        })
4044        .chain(delegated)
4045        .collect();
4046    }
4047    self
4048      .declared()
4049      .flat_map(|column| column.emitted(Owner::Record, &self.fragment, true))
4050      .chain(delegated)
4051      .collect()
4052  }
4053
4054  /// Every word this fragment's OBJECT publishes at one backend, paired with the token that chose
4055  /// it — the columns first, in declared order, then the lifted delegates.
4056  ///
4057  /// The ONE authority on those words, for [`Delegate::word`]'s own reason: a front end refusing a
4058  /// collision has to spell exactly what the emitter publishes, and a second spelling on that side
4059  /// is how a refusal and an emission come to disagree about a name nobody moved. A column's word is
4060  /// its `graphql(rename = "…")` or the camelCase fallback beneath it — read through
4061  /// [`wire_field`](Self::wire_field), the same function the `#[Object]` block spells each field
4062  /// with, so a renamed column is compared at the name it really publishes. A delegate's is its own
4063  /// `rename` or that same fallback over the restated method name.
4064  #[must_use]
4065  pub fn wire_words(&self, kind: crate::model::GraphqlKind) -> Vec<(String, syn::Ident)> {
4066    self
4067      .fields
4068      .iter()
4069      .map(|field| {
4070        (
4071          self.wire_field(Laid::Declared(field)),
4072          field.column.name.clone(),
4073        )
4074      })
4075      .chain(self.delegates.iter().filter_map(|delegate| {
4076        let method = delegate.signature.ident.clone();
4077        delegate.word(kind).map(|word| (word, method))
4078      }))
4079      .collect()
4080  }
4081
4082  /// Every field's COLUMN, in declared order.
4083  ///
4084  /// The reading all four FACES take, and the reason they take it is that none of them can tell the
4085  /// two modes apart: a width, a filter slot, a comparison conjunct and a wire member are each read
4086  /// off a declared name and a declared type, which a manifest states exactly as a held field does.
4087  fn declared(&self) -> impl Iterator<Item = &Column> {
4088    self.fields.iter().map(|field| &field.column)
4089  }
4090}