ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! The RECORD's CROSSING: a wire filter becomes one database's predicate, and the operands enter
//! storage.
//!
//! ```text
//! ReelFilter { title: Some(TextFilter::eq("matte")), frames: Some(ScalarFilter::gt(24)) }
//!   │
//!   ├─ per stored column: the comparison its filter crosses into, at the type this database pins
//!   ├─ the declared operand converter, where `graphql(input(comparison(<db>(try_into = "…"))))`
//!   │  names one
//!   └─ ReelSqliteComparison<Sqlite>
//! ```
//!
//! # It names a CONCRETE backend, and that is the whole of why it can be written
//!
//! [`DatabaseBackend::comparison_traits`](super::DatabaseBackend::comparison_traits) states the wall
//! this walks around, and does not walk THROUGH: a record's comparison is generic in its database on
//! purpose — a declaration storing one dialect must not need that dialect's driver to compile — and
//! at a generic `Db` the crossing is unwritable, because a `where` clause whose self type is
//! `<F as ToDatabaseComparison<V, Db>>::Comparison` makes rustc resolve the projection through the
//! impl that DEFINES it, so the clause demands whatever that impl demands of `Db`.
//!
//! What that note ended on is *a per-dialect crossing beside a dialect-generic type is a shape nobody
//! has ruled*. This is that shape, and what rules it is the one that was already ruled next door:
//! [`crate::interface::cross`] writes exactly this impl for an interface, at a concrete backend,
//! inside that backend's gate. A record reaches the same place through the same door —
//! `Record<Sqlite>` is already emitted per DECLARED ∩ COMPILED-IN backend, and its
//! `type Comparison = <E>SqliteComparison<Sqlite>` is the concrete type this impl is written for. So
//! every projection here NORMALISES: the column's comparison resolves to a kind, that kind's
//! `TryFromFilter` row is available, and its inherent `try_from_filter_with` exists.
//!
//! The dialect-generic `ToDatabaseComparison` map is untouched beside it. One is the type-level
//! question — *what does a filter of this kind cross into* — and one is the value-level crossing at a
//! dialect somebody actually compiled.
//!
//! # It is emitted where the WIRE spends it — at ONE database, and under the face's own condition
//!
//! Two halves. [`RecordModel::wire_filters`](crate::model::RecordModel::wire_filters) is the
//! condition the filter FACE rides, read here rather than restated; and the database is the one
//! `RecordModel::wire_query_row` names, which is where this record's root fields are served from. A
//! record stored in two dialects gets ONE crossing, because it answers its list from one — a client
//! must never see a schema that varies with a deployment's storage choice, and a crossing at a
//! dialect no resolver reaches would be an obligation nothing discharges and nothing uses.
//!
//! The reason the condition exists at all is measured rather than tidy: a column
//! whose operand cannot enter storage without a converter the declaration did not write is `E0277`
//! at this impl, naming the pair. `ingraph-derive`'s `labels.rs` is the declaration that shows it —
//! `speakers: Vec<Tag>` is stored as `String` elements through a declared ROW conversion and names
//! no OPERAND converter, so `String: TryFrom<Tag>` is a row nobody wrote. That record has no stored
//! id and therefore no query lane, so nothing on the wire asks it for a predicate, and nothing here
//! demands one. A record that IS queried and has such a column says so at this impl, which is where
//! the declaration can answer with `graphql(input(comparison(<db>(try_into = "…"))))`.
//!
//! # A declared converter REPLACES the chain rather than joining it
//!
//! `graphql(input(comparison(<db>(try_into = "…"))))` on a FIELD is handed one operand and answers
//! with the stored form, and the declaration owns the whole hop. A field with no entry crosses
//! through the stored type's own [`TryFrom`] — which for the identity crossing is
//! [`Infallible`](core::convert::Infallible) through std's own reflexive blanket, so a column that
//! stores what it holds is provably unable to refuse.
//!
//! An INFALLIBLE declared leg (`into = "…"`) reaches the same entry point wrapped, because that entry
//! point takes a fallible function and there is no second one: the wrapper's error is `Infallible`,
//! which the record's own error cell absorbs exactly as it absorbs every other leg.
//!
//! # ONE spelling, whatever KIND the column is
//!
//! This emitter cannot tell a collection column from a scalar one and must not try: `type Ids =
//! Vec<Uuid7>` and a scalar are the same tokens. So the declared leg is written once, at two
//! arguments, and the kind the projection resolves to decides what happens — the argument
//! [`crate::interface::cross`] already makes, and the composition it relies on
//! (`try_from_filter_with_element`, where a collection's own operands and its nested `any` filter are
//! made of the same element) is the kinds' own.
//!
//! # The FILTER's own spelling and the COMPARISON's are two projections, and both are read here
//!
//! A column's filter reaches this file twice. `<E>Filter`'s field is the WIRE form's filter —
//! `graphql(type = "…")` moves it — and the comparison's field is held at the DOMAIN form's, because
//! that is what [`DatabaseBackend::comparison`](super::DatabaseBackend::comparison) wrote. Both are
//! spelled from their own source rather than one being assumed to equal the other, and the kinds are
//! generic in the operand — `TryFromFilter<ScalarFilter<D>> for SqlScalarComparison<S, Db>` holds for
//! any `D` with `S: TryFrom<D>` — so the two meet at the crossing exactly where a conversion exists
//! between them, and are `E0277` naming the pair where none does.

use quote::quote;

use crate::{
  emit::leading,
  model::{Conversion, Crossing, DatabaseBackend, RecordModel},
};

impl DatabaseBackend {
  /// `TryFromFilter<<E>Filter>` for THIS database's predicate, at the concrete backend and inside
  /// its gate.
  ///
  /// # THE DECLARATION'S OWN OBLIGATION: a queried column that converts owes a THIRD leg
  ///
  /// A column whose stored form is not its domain form carries whole VALUES between the record and
  /// the row through `<db>(from = "…", into = "…")` — two legs, and they are the only two
  /// a record that is never queried needs. A record with a QUERY LANE spends a third: the impl this
  /// function writes crosses a filter's OPERANDS into the same stored form, and the leg it reads is
  /// [`RecordModel::operand`](crate::model::RecordModel::operand)'s —
  /// `graphql(input(comparison(<db>(try_into = "…"))))`, or its total twin `into = "…"`.
  ///
  /// The operand leg is a THIRD DIRECTION rather than a repetition of the row's pair, and the
  /// difference is the LEVEL as much as the direction: a collection's row conversion is
  /// `Vec<Domain> -> Vec<Stored>`, while its operand leg is `Domain -> Stored` one level down,
  /// because a collection's own operands and the operands inside its nested `any` filter are made
  /// of the same ELEMENT.
  ///
  /// A field that declares nothing crosses through the stored type's own [`TryFrom`], so the
  /// obligation bites only where the two forms differ — a column that stores what it holds crosses
  /// through std's reflexive blanket at [`Infallible`](core::convert::Infallible) and is provably
  /// unable to refuse. Where they DO differ and the leg is missing, `Stored: TryFrom<Domain>` is a
  /// row nobody wrote and this impl is `E0277` AT THE DECLARATION, naming that pair. That refusal
  /// is the whole enforcement, and it is a COMPILE-TIME one: a declaration that reaches a running
  /// server has the leg.
  ///
  /// ```ignore
  /// #[ingraph::record(table = "mixes", sqlite, graphql(async_graphql))]
  /// pub struct Mix {
  ///   #[ingraph(id)]
  ///   id: i64,
  ///   #[ingraph(
  ///     r#enum,
  ///     // The ROW's pair: whole values, between `Channel` and the `String` the column stores.
  ///     sqlite(type = "String", from = "channel_name", into = "channel_of"),
  ///     // The OPERAND leg: ONE filter operand, `Channel` into `String`. Delete this line and the
  ///     // crossing emitted below asks for `String: TryFrom<Channel>`, which nothing wrote.
  ///     graphql(input(comparison(sqlite(into = "channel_name"))))
  ///   )]
  ///   channel: Channel,
  /// }
  /// ```
  ///
  /// What a FALLIBLE leg refuses with at RUN TIME is a separate fact and a separate word: the
  /// refusal lands in the cell `graphql(input(comparison(<db>(try_into(error = "…")))))` names,
  /// and the emitted list resolver renders it to the client as `UNSUPPORTED_FILTER` through
  /// `ingraph::graphql::refused_filter` — the schema is backend-neutral by design, so it offers
  /// operands a compiled store may not be able to hold.
  /// ONE leg per REVERSE POSITION: the quantifier a client sent, over the far side's own crossed
  /// predicate, correlated on the column THIS DATABASE stores the back-reference under.
  ///
  /// # The stored name is ASKED FOR, in a `const`, and a miss is `E0080` at the declaration
  ///
  /// A reverse position is declared at the TARGET, whose expansion cannot see the source's
  /// `<db>(rename = "…")`. So the name is not rebuilt: the DECLARED half — the literal a
  /// `field = "…"` wrote, or the one the evidence answers for the shorthand — is the key, and
  /// `stored_column` over `<<Source as Record<Db>>::Row as SqlQuery<Db>>::COLUMNS` is the lookup.
  /// That list is per DATABASE, so a source stored in two dialects under two spellings correlates
  /// correctly in both, and the `Db` is CONCRETE here — this whole impl is inside one backend's gate
  /// — which is what lets the projection normalise inside a `const`.
  ///
  /// The `None` arm is the second half of the audit `Related::COLUMNS` already carries. That one
  /// refuses a `field = "…"` naming no `ref` of the source; this one refuses a name the source's ROW
  /// does not store — a field left out of this database's `persist(…)` block, or one whose type
  /// spans several columns and so has no single name to be a join's side. Both land at the
  /// declaration; this one carries the sentence written below.
  ///
  /// # The quantifier arms are written out, because the two families construct differently
  ///
  /// `SqlDerivedComparison::new` takes a `RelatedRow` where MongoDB's takes a
  /// `MongoRelatedDocument`, so the map that makes the member's TYPE family-blind cannot make its
  /// CONSTRUCTION so. The four arms are `RelatedFilter`'s own vocabulary 1:1 — `any`/`all`/`none`
  /// carry the far side's predicate and `count` carries the position's cardinality — and an ABSENT
  /// position is the bare one, which lowers to no conjunct at all.
  fn relation_legs(&self, model: &RecordModel) -> Vec<proc_macro2::TokenStream> {
    let backend = self.backend_type(model);
    let related_filter = model.framework(&["graphql"], "RelatedFilter");
    let derived = model.framework(&["comparison", "sql"], "SqlDerivedComparison");
    let related_row = model.framework(&["comparison", "sql"], "RelatedRow");
    let try_from_filter = model.framework(&["comparison"], "TryFromFilter");
    let stored_column = model.framework(&["column"], "stored_column");
    let field_name = model.framework(&["field"], "FieldName");
    let record_of = model.framework(&["transform"], "Record");
    let sql_query = model.framework(&["query", "sql"], "SqlQuery");

    self
      .relations(model)
      .into_iter()
      .map(|row| {
        let (member, source, declared) = (&row.member, &row.path, &row.declared);
        let nested = quote!(<#source as #record_of<#backend>>::Comparison);
        let far_row = quote!(<#source as #record_of<#backend>>::Row);
        let why = format!(
          "`{source}` stores no single column for the field the `{position}` reverse position \
           points back through. A relation joins ONE column to one column, so the field has to be \
           in this database's `persist(…)` block and has to span one column there — a field spanning \
           several has no single name to be a join's side.",
          source = quote!(#source).to_string().replace(' ', ""),
          position = member,
        );
        // Crossed one arm at a time rather than through a helper taking a closure: each arm's
        // refusal is absorbed by THIS record's error cell at the point it happens, which is the
        // posture every column leg above already takes.
        let cross = |bound: &proc_macro2::TokenStream| {
          quote! {
            match #try_from_filter::try_from_filter(#bound) {
              ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
              ::core::result::Result::Err(__ingraph_why) => {
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            }
          }
        };
        let quantifier = cross(&quote!(__ingraph_nested));
        let cardinality = cross(&quote!(__ingraph_count));
        quote! {
          let #member = {
            const __INGRAPH_POINTS_BACK__: &'static #field_name = {
              const __INGRAPH_DECLARED__: &'static ::core::primitive::str = #declared;
              match #stored_column(
                <#far_row as #sql_query<#backend>>::COLUMNS,
                __INGRAPH_DECLARED__,
              ) {
                ::core::option::Option::Some(__ingraph_stored) => __ingraph_stored,
                ::core::option::Option::None => ::core::panic!(#why),
              }
            };
            let __ingraph_position = <#derived<#nested, #backend>>::new(
              #related_row::of::<#far_row, #backend>(),
              __INGRAPH_POINTS_BACK__,
            );
            match __ingraph_filter.#member {
              ::core::option::Option::Some(__ingraph_held) => match *__ingraph_held {
                #related_filter::Any(__ingraph_nested) =>
                  __ingraph_position.with_any(#quantifier),
                #related_filter::All(__ingraph_nested) =>
                  __ingraph_position.with_all(#quantifier),
                #related_filter::None(__ingraph_nested) =>
                  __ingraph_position.with_none(#quantifier),
                #related_filter::Count(__ingraph_count) =>
                  __ingraph_position.with_count(#cardinality),
              },
              // A position the client said nothing about: no quantifier asked, so the lowering
              // renders no conjunct — the same reading an unwritten column takes.
              ::core::option::Option::None => __ingraph_position,
            }
          };
        }
      })
      .collect()
  }

  /// ONE FORWARD position's leg: the nested predicate a client wrote about the row a `ref` points
  /// at, crossed through the TARGET's own comparison and held as a semi-join.
  ///
  /// # The target crosses ITSELF, and that is the whole of the recursion
  ///
  /// `<Target as Record<Db>>::Comparison` is what the target's own declaration emitted, and its
  /// `TryFromFilter` row is that declaration's own crossing — so a nested filter is converted by the
  /// code that owns it, at any depth the client wrote, and this leg states nothing about what is
  /// inside. Each level is one `IN ( SELECT … )` at lowering, which is exactly what
  /// `SqlRefComparison` already renders.
  ///
  /// # The BOX, and where the allocation is
  ///
  /// The predicate is held behind a pointer for the reason the wire arm is: two records that refer
  /// to each other make two comparisons each containing the other. One allocation per WRITTEN level
  /// at crossing time, none for an absent arm, and never one per row.
  ///
  /// # An ABSENT arm is `None`, and it renders nothing
  ///
  /// The member is an `Option` because *nothing was asked* has no value to be — an emitted
  /// comparison has no `Default` — and `ComplexComparison for Option<C>` is what lowers the absence
  /// to no conjunct at all.
  fn forward_leg(
    &self,
    model: &RecordModel,
    row: &crate::emit::graphql::ForwardRow,
  ) -> proc_macro2::TokenStream {
    let backend = self.backend_type(model);
    let target = &row.target;
    let reference = model.framework(&["comparison", "sql"], "SqlRefComparison");
    let related_row = model.framework(&["comparison", "sql"], "RelatedRow");
    let try_from_filter = model.framework(&["comparison"], "TryFromFilter");
    let record_of = model.framework(&["transform"], "Record");
    let nested = quote!(<#target as #record_of<#backend>>::Comparison);
    let far_row = quote!(<#target as #record_of<#backend>>::Row);
    quote! {
      match __ingraph_related {
        ::core::option::Option::Some(__ingraph_nested) => {
          let __ingraph_crossed: #nested =
            match #try_from_filter::try_from_filter(*__ingraph_nested) {
              ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
              ::core::result::Result::Err(__ingraph_why) => {
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            };
          ::core::option::Option::Some(<#reference<::std::boxed::Box<#nested>, #backend>>::new(
            #related_row::of::<#far_row, #backend>(),
            ::std::boxed::Box::new(__ingraph_crossed),
          ))
        }
        ::core::option::Option::None => ::core::option::Option::None,
      }
    }
  }

  /// ONE NARROWED column's leg: the runtime NAMED REFUSAL a request spends the schema's word on and
  /// this database cannot answer.
  ///
  /// # The word is in the schema and the column is not in this store
  ///
  /// A per-database-narrowed column keeps its filter word, because the schema states the
  /// DECLARATION's truth rather than any one deployment's — the same service, deployed against two
  /// databases, publishes one vocabulary. What differs is the ANSWER, and this is where the
  /// difference is spoken: a client that wrote a predicate over a column this database has not got
  /// is refused BY NAME, naming the column and the dialect, before a statement exists to be
  /// rendered. The alternative is what the ruling forbids — a bare *no such column* out of the
  /// driver, which names a physical column of a table nobody can look at.
  ///
  /// # A client that wrote NOTHING is not refused
  ///
  /// The absent arm is the same silence every other column's is: an unwritten field narrows nothing.
  /// So a deployment on the narrowing database serves every query that does not actually spend the
  /// word, which is what makes the word's presence in the schema cost nothing until it is used.
  ///
  /// The refusal travels the crossing's OWN error channel — the cell `graphql(input(comparison(…)))`
  /// names, or the boxed refusal — so nothing new carries it and a declaration that typed its
  /// crossing absorbs this through the same `Into` every other leg goes through.
  ///
  /// No member is bound, because this database's comparison has none: `compared` is the storage-true
  /// list and `Self::new` takes exactly it.
  fn unstored_leg(
    &self,
    model: &RecordModel,
    row: &crate::emit::graphql::FilterRow,
  ) -> proc_macro2::TokenStream {
    let sent = &row.member;
    let condition = model.gate(sent);
    let not_stored = model.framework(&["query"], "ColumnNotStored");
    let term_name = model.framework(&["cursor"], "TermName");
    // The RENAME-PROOF identity — the record field's own name, which is what the schema published
    // and what the client wrote — rather than a column name of the databases that do store it.
    let identity = crate::name::RustSafeName::from_ident(sent)
      .external()
      .to_owned();
    let database = self.kind().as_str();
    quote! {
      #condition
      if ::core::option::Option::is_some(&__ingraph_filter.#sent) {
        return ::core::result::Result::Err(::core::convert::Into::into(
          #not_stored::new(#term_name::new(#identity), #database),
        ));
      }
    }
  }

  pub(crate) fn filter_crossing(&self, model: &RecordModel) -> proc_macro2::TokenStream {
    let Some(graphql) = model.graphql.as_ref() else {
      return proc_macro2::TokenStream::new();
    };
    // THIS database and not merely SOME database: the crossing is emitted where the wire SPENDS it,
    // and `wire_query_row` is the one place that decides which database a record's root fields are
    // served from. A record stored in two of them gets ONE crossing, at the one a resolver reaches,
    // rather than a second at a dialect whose predicate nothing asks for — which would be an
    // obligation nothing reads, DEMANDED inside an expansion its author cannot edit.
    if !model.wire_filters()
      || model
        .wire_query_row()
        .is_none_or(|served| served.kind() != self.kind())
    {
      return proc_macro2::TokenStream::new();
    }
    let rows = graphql.filter_rows(model);
    if rows.is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let kind = self.kind();
    let filter = graphql.filter.safe();
    let comparison = self.comparison_name();
    let backend = self.backend_type(model);
    let error = model.error(Crossing::Comparison, kind);
    let try_from_filter = model.framework(&["comparison"], "TryFromFilter");
    let to_comparison = model.framework(&["comparison"], "ToDatabaseComparison");
    let gate = model.framework(&["gate"], &kind.gate().to_string());

    // Each argument carries its column's CONDITION, which is the same gate the parameter it fills
    // wears on `Self::new` — a call argument and a function parameter are both attribute positions,
    // so the two walks contract together or neither does.
    let mut members: Vec<proc_macro2::TokenStream> = self
      .compared(model)
      .into_iter()
      .map(|column| {
        let (condition, member) = (model.gate(&column.source), column.member());
        quote!(#condition #member,)
      })
      .collect();
    members.extend(self.relations(model).into_iter().map(|row| {
      let member = row.member;
      quote!(#member,)
    }));
    // A `ref` field may not be conditional, so a forward position never carries a gate.
    members.extend(self.forwards(model).into_iter().map(|row| {
      let position = row.position;
      quote!(#position,)
    }));
    // JOINED by source rather than zipped, because the two lists are no longer one. The filter's
    // rows are the DECLARATION's — a per-database-narrowed column keeps its word in the schema, the
    // schema stating the declaration's truth rather than any one deployment's — while this
    // database's comparison holds only the columns it really has. So the walk is the filter's and
    // each row asks this database whether it stores the column; the members `Self::new` takes are
    // the ones that answered yes, in this same order, which is what keeps the positional call
    // honest.
    let forwards = self.forwards(model);
    let legs = rows.iter().map(|row| {
      let sent = &row.member;
      let Some(column) = self.stores(sent) else {
        return self.unstored_leg(model, row);
      };
      let member = column.member();
      // The COLUMN's own filter, never the widened one: what a `ref` column's `related` arm carries
      // crosses through the TARGET's row and is taken off before this leg sees the value.
      let wire = &row.operators;
      let stored = column.ty();
      // The comparison's OWN field type, spelled from the DOMAIN form exactly as
      // `DatabaseBackend::comparison` spelled it — the same tokens, so the crossing lands on the
      // type the struct really holds rather than on one that happens to resolve alongside it.
      let domain = super::filter_of(
        &model.krate,
        &column.domain,
        model.marker_of(&column.source),
        super::FilterFace::Column,
      );
      let held = quote!(<#domain as #to_comparison<#stored, #backend>>::Comparison);
      let crossed = match model.operand(&column.source, kind) {
        // The DECLARED leg and the default one are two shapes rather than one with a hole, for the
        // reason a declared marker and an inferred one are: what a declared converter SAYS is *do
        // not ask the stored type how to take this value, I have answered*.
        Some(Conversion::Fallible(convert)) => {
          let path = &convert.path;
          // The ESCAPE is the map from the FUNCTION's error into the record's, where `From` cannot
          // exist — two foreign types either side of the impl, or an error a caller wants to wrap.
          // Absent, the cell absorbs the refusal through `Into`, which is the plain `?` this
          // expansion spells out.
          let absorb = convert.escape.as_ref().map_or_else(
            || quote!(::core::convert::Into::into(__ingraph_why)),
            |escape| quote!(#escape(__ingraph_why)),
          );
          quote! {
            match <#held>::try_from_filter_with(__ingraph_held, #path) {
              ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
              ::core::result::Result::Err(__ingraph_why) => {
                return ::core::result::Result::Err(#absorb);
              }
            }
          }
        }
        // An infallible declared leg reaches the SAME entry point, because there is only one: the
        // kinds take a fallible function, so a total one is wrapped here at `Infallible` rather than
        // given a second door that would be this one with the arm deleted.
        Some(Conversion::Infallible(path)) => quote! {
          match <#held>::try_from_filter_with(
            __ingraph_held,
            |__ingraph_operand| ::core::result::Result::<_, ::core::convert::Infallible>::Ok(
              #path(__ingraph_operand),
            ),
          ) {
            ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
            ::core::result::Result::Err(__ingraph_why) => {
              return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
            }
          }
        },
        Some(Conversion::Default) | None => quote! {
          match <#held as #try_from_filter<#wire>>::try_from_filter(__ingraph_held) {
            ::core::result::Result::Ok(__ingraph_crossed) => __ingraph_crossed,
            ::core::result::Result::Err(__ingraph_why) => {
              // Bound to the NAMED type before it is converted, so a cell that cannot absorb this
              // column's crossing is `E0277` at the declaration naming WHICH — the posture the
              // interface's own crossing takes, and the reason the `?` is written out.
              let __ingraph_why: <#held as #try_from_filter<#wire>>::Error = __ingraph_why;
              return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
            }
          }
        },
      };
      // A WIDENED column arrives as ONE field holding two questions, so the value is taken apart
      // before either leg reads it: the column's own operators keep the leg above, and the nested
      // predicate goes to the forward position's own member. Both locals are bound even where the
      // client sent nothing, because the two arms of the read are the two arms of the field.
      let condition = model.gate(&column.source);
      let Some(forward) = forwards.iter().find(|row| row.column == *member) else {
        return quote! {
          #condition
          let #member = match __ingraph_filter.#sent {
            ::core::option::Option::Some(__ingraph_held) => #crossed,
            // A column the client said nothing about: the EMPTY comparison, which renders no
            // conjunct — so an unwritten field narrows nothing rather than matching nothing.
            ::core::option::Option::None => ::core::default::Default::default(),
          };
        };
      };
      let position = &forward.position;
      let nested = self.forward_leg(model, forward);
      quote! {
        #condition
        let (__ingraph_column, __ingraph_related) = match __ingraph_filter.#sent {
          ::core::option::Option::Some(__ingraph_widened) => {
            let (__ingraph_column, __ingraph_related) = __ingraph_widened.into_parts();
            (
              ::core::option::Option::Some(__ingraph_column),
              __ingraph_related,
            )
          }
          ::core::option::Option::None => (
            ::core::option::Option::None,
            ::core::option::Option::None,
          ),
        };
        #condition
        let #member = match __ingraph_column {
          ::core::option::Option::Some(__ingraph_held) => #crossed,
          ::core::option::Option::None => ::core::default::Default::default(),
        };
        #condition
        let #position = #nested;
      }
    });

    let relations = self.relation_legs(model);
    let record = &model.record;
    let doc = leading(&format!(
      "Cross a wire filter into the predicate a [`{record}`] is queried by in this database — every \
       operand through the crossing its declaration names, and the empty comparison wherever the \
       client asked nothing.\n\n# Errors\nWhatever an operand's crossing into its stored form \
       refused with, absorbed by the cell `graphql(input(comparison(…)))` names."
    ));
    quote! {
      #gate! {
        #[automatically_derived]
        impl #try_from_filter<#filter> for #comparison<#backend> {
          type Error = #error;

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