ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! The ELEMENT MODE's model: what `#[derive(ingraph::Filter)]` emits when the declaration wears
//! `#[ingraph(operator(<family>))]` — a filter type the DECLARING crate owns, plus the citizenship
//! its element needs to be an operand at all.
//!
//! # The wall this walks around
//!
//! A declaring crate's own element could not be filtered under most families, and the reason was the
//! orphan rule read from one side. `TextFilter<Tag>`, `ScalarFilter<Db>` and `BytesFilter<Sum>` are
//! FOREIGN types there, so `impl async_graphql::InputType` for any of them is `E0117` — RFC 2451
//! does not admit `ForeignTrait for ForeignType<Local>`, the trait taking no parameter for a local
//! type to sit in — and `ingraph` could not write the row either: every one of those faces was one
//! REGISTRATION PER OPERAND, and the set of a declarer's operands is open.
//!
//! The wall is not climbed. This door MINTS `<T>Filter` in the declaring crate, so every impl below
//! names a local self type and coherence is never in the conversation.
//!
//! # The framework has since opened a SECOND road, and this one is not the lesser of the two
//!
//! `ingraph`'s three carrier readings — `TextWire`, `ScalarWire`, `BytesWire` — moved every one of
//! those registrations onto a marker, so a declaring crate can now reach the framework's OWN filter
//! by writing a reading instead of taking a mint. The two answer different questions and a
//! declaration picks by what it wants:
//!
//! - a MINT gives the element a filter type of its own, with a name and an inherent face the
//!   declaring crate owns, and it is the road for an element that also wants the scalar, the output
//!   crossing and the marker rows this door writes;
//! - a READING gives the element the framework's own filter under a name the reading chooses, with
//!   no new type at all — one impl where this door emits a dozen.
//!
//! Neither is going away, and nothing here changed: this door emits what it always did.
//!
//! # What the minted filter HOLDS, and why it is a newtype
//!
//! The framework's own filter for the family, at the element — `TagFilter(TextFilter<Tag>)`. The
//! operation set, the emptiness answer and the lowering map are therefore the framework's, stated
//! once, and this door adds a face rather than a second implementation of the family. A minted type
//! whose slots were its own would be the text family's twenty operators written a second time, in a
//! crate that cannot see when the first ones change.
//!
//! # The NULLABLE wall came down, and the ENUM family's ALIAS came down with it
//!
//! A newtype's remaining cost used to be the same orphan rule one type over: `Nullable` is the
//! framework's, so `impl InputType for Nullable<TagFilter>` is `E0117` here, and an `Option<Tag>`
//! column had no wire face at all. The framework's own answer is `ingraph::NullableFace` — a
//! delegation trait it writes ONE blanket `Nullable<F>` row over — and this door writes that trait
//! on the minted filter, whose self type is local. So `Option<Tag>` is spellable now, for the
//! reason `Option<Codec>` always was, and no family is on the wall.
//!
//! The ENUM family used to route AROUND that wall instead of standing off it: its door was a TYPE
//! ALIAS, `pub type CodecFilter = EnumFilter<Codec>`, so `Nullable<CodecFilter>` was
//! `Nullable<EnumFilter<Codec>>` and resolved into a row `ingraph` had already written. With the
//! wall down the detour bought nothing and went on charging three accounts, all of them now closed:
//!
//! - **NOMINAL DISTINCTNESS.** An alias is not a type, so an impl written on the door's name was an
//!   impl on `EnumFilter<T>` — `E0119` against the framework's own generic rows, measured in
//!   `ingraph`'s `tests/element_mint_parity.rs`. A row of exactly that shape is how a minted element
//!   reaches a dialect (`tests/nullable_face.rs` writes one for the scalar family), so the enum
//!   family was the one family whose elements could not have a crossing of their own.
//! - **THE RENAME WORD.** `filter(rename = "…")` moved the RUST name and left the wire name where
//!   `EnumFilter<T>`'s own derivation put it, where the other three families moved both.
//! - **TWO SHAPES TO MAINTAIN.** Every emission below had to answer *does this family mint*, and
//!   every reader of this file had to carry the answer.
//!
//! **The SDL did not move when the alias retired**, and that is arithmetic rather than luck:
//! `EnumFilter<T>` named itself `<T's schema name>Filter` and a mint names itself
//! [`RustSafeName::external`], which for an element that renames nothing is the same string. What
//! the mint adds is that a RENAME now moves it, which is the second account above.
//!
//! So there is ONE shape at four doors, and [`ElementModel::emit`] writes it once.
//!
//! # WHAT THE MINT HANDS ON, and the two rows that are one decision
//!
//! A minted filter is a value somebody else lowers, so the door owes a way OUT of it as well as a
//! way in. `into_inner` is that way — the held filter taken by value — and it is what every crossing
//! actually wants: an entry point that lowers a filter consumes it, so a hand-written row reached
//! through `get` had to clone a value its caller already owned.
//!
//! The DECLARED-CONVERTER leg needs one more thing, and it is the same fact stated as a trait:
//! every crossing entry takes its filter as `TryMapFilter<D, V>` — the wrapper's
//! (`SqlNullable::<C>::try_from_filter_with`) and, since the byte kinds split, all ten flat ones too
//! — so an element column with `comparison(<db>(into = "…"))` written on it reaches a bound the mint
//! has to satisfy, `Option` or not. [`ElementModel::operand_map`] emits that row, delegating through
//! `into_inner` — which is why the two land together rather than one at a time.
//!
//! # The element's OWN citizenship comes with it
//!
//! A filter's operand crosses the wire, so the element needs a wire face before its filter can have
//! one — and that face is the half only the declaring crate can write. It is emitted here for the
//! same reason `#[derive(ingraph::Enum)]` emits a vocabulary's: it is mechanical from the
//! declaration, and a door that minted the filter and left the operand to a hand-written `#[Scalar]`
//! would be a door that does not close.
//!
//! The scalar is async-graphql's own attribute over an `impl ScalarType`, which is what a declaring
//! crate wrote by hand before this door existed — the same tokens, from the same declaration, so the
//! retirement of a hand impl is a deletion rather than a translation. It also settles the OUTPUT
//! leg's `boxed-trait` question by not asking it: the attribute runs inside async-graphql and writes
//! whichever `resolve` shape that build compiled, where an `async fn` written out here would compile
//! under one of the two.
//!
//! # The wire form is the INNER type's, under the ELEMENT's name
//!
//! `Tag(String)` crosses as a string, `Db(u32)` as a number, `Sum(Vec<u8>)` as whatever `Vec<u8>`'s
//! own face renders — the element does not invent a grammar, it names one. The SDL name defaults to
//! the element's Rust name and is moved by the declaration's own `graphql(rename = "…")`, which is
//! `#[derive(ingraph::Enum)]`'s word for its reason: a wire type name is a schema commitment, and a
//! commitment gets a word of its OWN rather than riding on a Rust rename.

use quote::{format_ident, quote};
use syn::ext::IdentExt as _;

use crate::name::RustSafeName;

#[cfg(test)]
mod tests;

/// One operator slot of a family: the member the framework's filter holds it in, the name a client
/// writes, and whether it takes a LIST of operands.
///
/// Spelled rather than derived from the member. A wire name is a schema commitment — `in_` is `in`
/// and `contains_nocase` is `containsNocase` — and a casing function here would be a second author
/// for a string `ingraph`'s own faces already publish.
struct Operation {
  /// The member `ingraph`'s filter holds this operand in, which is also the stem of the accessor
  /// family this door delegates through.
  member: &'static str,
  /// What a client writes.
  wire: &'static str,
  /// A LIST slot — `in`/`notIn` — which crosses as a list of operands rather than as one.
  list: bool,
}

/// One inline operand slot.
const fn one(member: &'static str, wire: &'static str) -> Operation {
  Operation {
    member,
    wire,
    list: false,
  }
}

/// One LIST operand slot.
const fn many(member: &'static str, wire: &'static str) -> Operation {
  Operation {
    member,
    wire,
    list: true,
  }
}

/// The MEMBERSHIP pair every family here ends with, in the order the framework's own faces publish
/// them.
const MEMBERSHIP: [Operation; 2] = [many("in_", "in"), many("not_in", "notIn")];

/// The ORDERING + EQUALITY six every family but the enumeration opens with.
const ORDERED: [Operation; 6] = [
  one("eq", "eq"),
  one("ne", "ne"),
  one("gt", "gt"),
  one("gte", "gte"),
  one("lt", "lt"),
  one("lte", "lte"),
];

/// A family an ELEMENT may be read under — the word `operator(…)` takes.
///
/// FOUR of the framework's eight interpretation words, and the four are measured rather than
/// chosen. `bool` and `duration` are refused because their filter kinds carry NO OPERAND PARAMETER
/// — `BooleanFilter`'s operands are `bool` and `DurationFilter`'s are `jiff::SignedDuration`, so
/// there is no *this kind over the declarer's element* for a minted filter to hold. `list` and `set`
/// are refused because they are COLLECTION positions rather than elements: what a collection holds
/// is the question its element answers, and an element mode over one would be asking a declaration
/// to name itself as its own member.
///
/// The refusals are BY NAME at the word, which is what keeps the vocabulary a fact a declaration can
/// read off a message rather than a list it has to have been told.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElementFamily {
  /// A NUMBER: one totally ordered value.
  Scalar,
  /// TEXT: one string of characters, with the substring and affix questions.
  String,
  /// A BYTE STRING: one opaque run of bytes.
  Bytes,
  /// An ENUMERATION: a closed vocabulary, so membership is the whole question.
  Enum,
}

impl ElementFamily {
  /// Every family with an element mode, in the order a refusal lists them.
  pub const ALL: [Self; 4] = [Self::Scalar, Self::String, Self::Bytes, Self::Enum];

  /// The word a declaration writes inside `operator(…)`.
  ///
  /// The interpretation vocabulary's own words, so `operator(string)` and a field's `string` name
  /// one family — a door with a second spelling would be a second vocabulary to keep in step.
  pub const fn word(self) -> &'static str {
    match self {
      Self::Scalar => "scalar",
      Self::String => "string",
      Self::Bytes => "bytes",
      Self::Enum => "enum",
    }
  }

  /// The framework filter the minted type holds.
  const fn filter(self) -> &'static str {
    match self {
      Self::Scalar => "ScalarFilter",
      Self::String => "TextFilter",
      Self::Bytes => "BytesFilter",
      Self::Enum => "EnumFilter",
    }
  }

  /// The family trait that carries this element's filter — the map a field's reading resolves
  /// through.
  const fn reading(self) -> &'static str {
    match self {
      Self::Scalar => "ScalarFilterMarker",
      Self::String => "StringFilterMarker",
      Self::Bytes => "BytesFilterMarker",
      Self::Enum => "EnumFilterMarker",
    }
  }

  /// The marker this family's reading is spelled as, which the element's DEFAULT resolves to.
  const fn marker(self) -> &'static str {
    match self {
      Self::Scalar => "ScalarMarker",
      Self::String => "StringMarker",
      Self::Bytes => "BytesMarker",
      Self::Enum => "EnumMarker",
    }
  }

  /// This family's operator slots, in the order the framework's own face publishes them — which is
  /// the order a client reads, the SDL rendering fields as the registry received them.
  ///
  /// Answered for EVERY family and SPENT by every one of them: the accessor face, the input
  /// object's field list and its render are all this list walked. The enumeration's four —
  /// `eq`, `ne`, `in`, `notIn` — are `EnumFilter<T>`'s own slots in `EnumFilter<T>`'s own order,
  /// which is what makes the mint's face byte-identical to the alias's on the wire.
  fn operations(self) -> Vec<Operation> {
    let mut slots = Vec::new();
    match self {
      Self::Scalar => slots.extend(ORDERED),
      Self::Enum => slots.push(one("eq", "eq")),
      Self::Bytes | Self::String => {
        slots.extend(ORDERED);
        slots.push(one("contains", "contains"));
        if self == Self::String {
          slots.push(one("contains_nocase", "containsNocase"));
        }
        slots.push(one("not_contains", "notContains"));
        if self == Self::String {
          slots.extend([
            one("not_contains_nocase", "notContainsNocase"),
            one("starts_with", "startsWith"),
            one("starts_with_nocase", "startsWithNocase"),
            one("not_starts_with", "notStartsWith"),
            one("not_starts_with_nocase", "notStartsWithNocase"),
            one("ends_with", "endsWith"),
            one("ends_with_nocase", "endsWithNocase"),
            one("not_ends_with", "notEndsWith"),
            one("not_ends_with_nocase", "notEndsWithNocase"),
          ]);
        }
      }
    }
    if self == Self::Enum {
      slots.push(one("ne", "ne"));
    }
    slots.extend(MEMBERSHIP);
    slots
  }
}

/// A declared ELEMENT, as the element mode reads it.
///
/// PLAIN, for [`StandaloneModel`](crate::standalone::StandaloneModel)'s reason — public fields, no
/// constructor, no validation. What is checked is checked at the FRONT END, where the tokens an
/// author wrote are still in hand and a refusal can point at one.
pub struct ElementModel {
  /// The declaration's own visibility, which the minted filter takes.
  pub vis: syn::Visibility,
  /// The element the faces are OF.
  pub subject: syn::Ident,
  /// The `ingraph` root the expansion spells its shelf through.
  pub krate: syn::Path,
  /// What the minted filter is called.
  pub filter: RustSafeName,
  /// The family this element is read under.
  pub family: ElementFamily,
  /// The single field the element holds its value in — positional or named.
  pub member: syn::Member,
  /// That field's type, which is what the element crosses the wire AS.
  pub inner: syn::Type,
  /// `graphql(rename = "…")` — what a SCHEMA calls this element's scalar, where the declaration
  /// moved it.
  ///
  /// `None` is the Rust name unraw'd, which is what [`ElementModel::sdl`] resolves. EMISSION-ONLY:
  /// the declared type keeps its name, the minted filter keeps `filter(rename = "…")`, and the two
  /// crossings are written for the Rust type either way.
  pub wire_name: Option<String>,
}

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

  /// The framework filter this element's minted type holds, at this element.
  fn held(&self) -> proc_macro2::TokenStream {
    let kind = self.framework(&["graphql"], self.family.filter());
    let subject = &self.subject;
    quote!(#kind<#subject>)
  }

  /// This element's name as a SCHEMA writes it — the declaration's [`wire_name`](Self::wire_name),
  /// else the Rust name unraw'd.
  ///
  /// The `r#` an unrenamed name drops is Rust's escape for a word that collides with ITS grammar and
  /// no part of the name.
  ///
  /// The knob arrived with the rename-parity ruling, replacing *there is no rename knob, for the
  /// reason `#[derive(ingraph::Enum)]` has none*. That reason — a wire type name is a schema
  /// commitment and a Rust rename is not a schema change — is unchanged and is now what the SEPARATE
  /// word is FOR: `filter(rename = "…")` moves the minted filter's Rust name and the input object it
  /// publishes, and this moves the scalar, and neither reaches the other's axis.
  fn sdl(&self) -> String {
    self
      .wire_name
      .clone()
      .unwrap_or_else(|| self.subject.unraw().to_string())
  }

  /// The whole element mode, emitted.
  ///
  /// ONE SHAPE, at four doors. Half of it belongs to the FILTER — the minted type, its accessor
  /// face, the emptiness contract, the lowering map, the operand map and the input object — and half
  /// to the ELEMENT: the readings a field resolves through, and the scalar and the two crossings only
  /// a declaring crate can write. The family decides what is IN each item and never which items
  /// there are.
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let declaration = self.declaration();
    let face = self.inherent();
    let contract = self.emptiness();
    let lowering = self.lowering();
    let operands = self.operand_map();
    let readings = self.readings();
    let wire = self.wire();
    quote! {
      #declaration
      #face
      #contract
      #lowering
      #operands
      #readings
      #wire
    }
  }

  /// The filter this door puts the element's name on — a NEWTYPE, at every family.
  ///
  /// # The newtype, and its member
  ///
  /// A newtype over the framework's own filter for the family, whose member is `pub(crate)` — the
  /// three-layer naming law's substrate visibility, so a sibling expansion reads it and a downstream
  /// crate spends the accessor face beside it.
  ///
  /// The three derives are CONDITIONAL on the element through the newtype's own field, exactly as
  /// the held filter's are: an element with no `Debug` mints a filter with none, and nothing here
  /// demands one.
  ///
  /// # The ORPHAN RULE is why it is a newtype, and the wall it used to cost is down
  ///
  /// A newtype's whole cost WAS the orphan rule at its NULLABLE twin. `Nullable` is the framework's
  /// and `TagFilter` is the declarer's, so `impl InputType for Nullable<TagFilter>` is `E0117` in
  /// the declaring crate and unwritable in `ingraph`, which has never heard of the element — so an
  /// OPTIONAL column of a minted element had no wire face. The enum family was off that wall by
  /// ALIASING — `ingraph` carries a generic row over `Nullable<EnumFilter<T>>` and an alias resolves
  /// INTO it — and every family is off it now through `ingraph::NullableFace`, which
  /// [`filter_face`](Self::filter_face) writes on the minted type. With the wall down the alias was
  /// a detour to nowhere, and the module note lists the three accounts it went on charging.
  ///
  /// # `filter(rename = "…")` moves BOTH names, at every family
  ///
  /// The word is the struct mode's and means the same thing here: the minted type takes the name,
  /// and [`filter_face`](Self::filter_face) publishes [`RustSafeName::external`] as the SDL name, so
  /// the schema follows the declaration. An element that renames nothing keeps
  /// `<Element>Filter` — the convention [`crate::model::default_filter_name`] mints — which is the
  /// string `EnumFilter<T>`'s own derivation used to produce, so the retirement of the alias moved
  /// no schema.
  fn declaration(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = self.filter.safe();
    let held = self.held();
    let subject = &self.subject;
    let doc = format!(
      "The `{}` reading of [`{subject}`], as a client writes one — the framework's own {} filter \
       over an element this crate declares.",
      self.family.word(),
      self.family.word()
    );
    // The visibility is the DECLARATION's rather than a fixed `pub`: an element a crate keeps to
    // itself mints a filter it keeps to itself.
    quote! {
      #[doc = #doc]
      #[derive(Debug, Clone, PartialEq)]
      #vis struct #name(pub(crate) #held);

      #[automatically_derived]
      impl ::core::default::Default for #name {
        #[inline]
        fn default() -> Self {
          Self::new()
        }
      }
    }
  }

  /// The minted filter's own face: the empty filter, the emptiness question, and one accessor family
  /// per operator the family has.
  ///
  /// Every one of them DELEGATES. The held filter answers, so a minted type cannot come to mean
  /// something the framework's own does not — and an operator renamed upstream is a compile failure
  /// in the declaring crate rather than a face that quietly lost a slot.
  fn inherent(&self) -> proc_macro2::TokenStream {
    let name = self.filter.safe();
    let held = self.held();
    let subject = &self.subject;
    let slots = self.family.operations().into_iter().map(|slot| {
      let member = format_ident!("{}", slot.member);
      let with = format_ident!("with_{}", slot.member);
      let maybe = format_ident!("maybe_{}", slot.member);
      let read = format!(
        "The `{}` operand{}, or `None` while the operator is absent.",
        slot.wire,
        if slot.list { "s" } else { "" }
      );
      let set = format!("Set `{}` to `Some(value)` (consuming).", slot.wire);
      let assign = format!("Assign the raw `{}` option (consuming).", slot.wire);
      if slot.list {
        quote! {
          #[doc = #read]
          #[inline]
          pub fn #member(&self) -> ::core::option::Option<&[#subject]> {
            self.0.#member()
          }

          #[doc = #set]
          #[must_use]
          #[inline]
          pub fn #with(self, value: impl ::core::convert::Into<::std::boxed::Box<[#subject]>>) -> Self {
            Self(self.0.#with(value))
          }

          #[doc = #assign]
          #[must_use]
          #[inline]
          pub fn #maybe(
            self,
            value: ::core::option::Option<impl ::core::convert::Into<::std::boxed::Box<[#subject]>>>,
          ) -> Self {
            Self(self.0.#maybe(value))
          }
        }
      } else {
        quote! {
          #[doc = #read]
          #[inline]
          pub fn #member(&self) -> ::core::option::Option<&#subject> {
            self.0.#member()
          }

          #[doc = #set]
          #[must_use]
          #[inline]
          pub fn #with(self, value: #subject) -> Self {
            Self(self.0.#with(value))
          }

          #[doc = #assign]
          #[must_use]
          #[inline]
          pub fn #maybe(self, value: ::core::option::Option<#subject>) -> Self {
            Self(self.0.#maybe(value))
          }
        }
      }
    });
    quote! {
      #[automatically_derived]
      impl #name {
        /// The empty filter — no operator set.
        #[inline]
        #[must_use]
        pub const fn new() -> Self {
          Self(<#held>::new())
        }

        /// True while NO operator slot is set — so a lowering would emit nothing for this field.
        #[inline]
        #[must_use]
        pub const fn is_empty(&self) -> bool {
          self.0.is_empty()
        }

        /// The framework filter this reading holds, for a caller that needs the family's own type.
        #[inline]
        #[must_use]
        pub const fn get(&self) -> &#held {
          &self.0
        }

        /// The framework filter this reading holds, TAKEN OUT — the owning projection beside
        /// `get`.
        ///
        /// What a crossing needs. Every entry point that lowers a filter consumes it, so a
        /// hand-written row reached through `get` had to `.clone()` the held filter to hand it on
        /// — a copy of a value the caller already owned, and one that put a `Clone` demand on the
        /// element where the crossing itself has none.
        #[inline]
        #[must_use]
        pub fn into_inner(self) -> #held {
          self.0
        }

        #(#slots)*
      }
    }
  }

  /// The emptiness contract, asked where the FILTER ITSELF is a parameter.
  fn emptiness(&self) -> proc_macro2::TokenStream {
    let name = self.filter.safe();
    let contract = self.framework(&["graphql"], "GraphqlFilter");
    quote! {
      #[automatically_derived]
      impl #contract for #name {
        #[inline]
        fn is_empty(&self) -> bool {
          Self::is_empty(self)
        }
      }
    }
  }

  /// The LOWERING map, delegated to the held filter.
  ///
  /// The type-level half and only it, which is the half a minted filter can carry: the VALUE-level
  /// crossing's self type is the framework's own comparison, so `TryFromFilter<TagFilter> for
  /// SqlTextComparison<…>` is `E0117` in a declaring crate and unwritable in `ingraph`, which has
  /// never heard of `TagFilter`. A column of an element reaches a dialect through the held filter's
  /// own crossing, which is what `into_inner` is for.
  fn lowering(&self) -> proc_macro2::TokenStream {
    let name = self.filter.safe();
    let held = self.held();
    let backend = self.framework(&["comparison"], "Backend");
    let map = self.framework(&["comparison"], "ToDatabaseComparison");
    let value = crate::emit::parameter("V");
    let db = crate::emit::parameter("DB");
    quote! {
      #[automatically_derived]
      impl<#value, #db> #map<#value, #db> for #name
      where
        #db: #backend,
        #held: #map<#value, #db>,
      {
        type Comparison = <#held as #map<#value, #db>>::Comparison;
      }
    }
  }

  /// The OPERAND MAP, delegated to the held filter — the row a DECLARED CONVERTER is spent
  /// through.
  ///
  /// # What it is for, and the leg that could not be walked without it
  ///
  /// `graphql(input(comparison(<db>(into = "…"))))` names a function from the DOMAIN operand to the
  /// STORED one, and the emitted crossing spends it at the wrapper's entry point —
  /// `SqlNullable::<C>::try_from_filter_with(filter, f)`, whose wrapped filter is the generic
  /// `F: TryMapFilter<D, V>`. A minted filter is the type in that position for an `Option<element>`
  /// column, so without this row the declared word reaches a bound the mint does not satisfy, and a
  /// declaration is refused inside its own expansion at a span its author cannot edit.
  ///
  /// It was WRITABLE by hand before — `ingraph`'s `tests/element_nullable_enum.rs` carried exactly
  /// this impl — and what it cost was one hand-written row per element per stored type, in a crate
  /// that gets no help spelling it. The mint writes it because the row is mechanical: the held
  /// filter maps, and the mint hands it the operands.
  ///
  /// LOAD-BEARING, measured by deleting it rather than argued: with this emission suppressed and
  /// that file's hand row gone, its `#[ingraph::record]` is refused inside its own expansion —
  ///
  /// ```text
  /// error[E0277]: the trait bound `CodecFilter: TryMapFilter<_, _>` is not satisfied
  ///   --> ingraph/tests/element_nullable_enum.rs:94:1
  ///   --> ingraph/src/comparison/sql/nullable.rs:95:8
  /// ```
  ///
  /// — at the declaration's own span, naming the seam this row fills.
  ///
  /// # It DELEGATES, so the mint cannot come to mean something the framework's own does not
  ///
  /// `Mapped` is the held filter's own answer rather than a spelling of this door's — the enum
  /// family maps into `EnumFilter<V>` and the bytes family into `BytesFilter<V, K, I>`, and a
  /// projection is what keeps this door out of that decision. The value half is one call through
  /// `into_inner`, which is the whole reason that projection exists.
  ///
  /// # It costs the mint one blanket row of nominal distinctness, deliberately
  ///
  /// A declaring crate can no longer write its own `TryMapFilter` over a minted filter — this one
  /// is `E0119` against it. That is the trade the ruling takes: the hand row this replaces was the
  /// SAME delegation every time, so what a declarer loses is the ability to write a DIFFERENT
  /// operand map for an element than the family it declared. The rows a declarer still owns, and
  /// which no blanket here touches, are the dialect crossings — `TryFromFilter<TagFilter> for
  /// SqlTextComparison<…>` and its siblings, which name a foreign self type and are the whole of
  /// what the mint's own name buys.
  ///
  /// # WHAT IT NOW CLOSES — the FLAT column's declared leg, on the day `ingraph` generalised
  ///
  /// A NON-nullable element column with a declared converter used to stop one type over: the flat
  /// kinds' entry point was
  /// `SqlEnumComparison::<V, Db>::try_from_filter_with(filter: EnumFilter<D>, f)` — the filter
  /// parameter NAMED rather than generic — so a minted filter arriving there was `E0308` whatever it
  /// implemented, and only the WRAPPER's entry (`SqlNullable`) took `F: TryMapFilter<D, V>`.
  ///
  /// Every flat entry takes a BOUND now — `X: TryMapFilter<D, V, Mapped = <the kind's own filter>>`
  /// — so this row is what a minted filter reaches all ten of them by. Ten and not eight, because
  /// the byte families split by slot legality: one entry per (kind × dialect), each byte one serving
  /// `BytesFilter` and `FixedBytesFilter` alike.
  ///
  /// The wall that deferred it was the two BYTES kinds READING the filter before mapping it —
  /// `filter.contains()` against `K::SUBSTRING`, `filter.gt()` against `K::BYTEWISE`. The type split
  /// deleted the first (a fixed-width filter has no substring field) and the second const with it;
  /// MongoDB's own two refusals survive, and that entry normalises through the identity map so they
  /// still run BEFORE the operands convert. `ingraph/tests/flat_crossings.rs` is where the wall was
  /// measured and where its absence is asserted.
  ///
  /// What a declarer still writes by hand is the DEFAULT leg's dialect crossing —
  /// `TryFromFilter<CodecFilter> for SqlEnumComparison<…>`, which `ingraph-derive`'s
  /// `tests/fixtures.rs` writes twice — and that row is not a gap: it names a foreign self type, and
  /// it is the whole of what the mint's own name buys. See the section below.
  fn operand_map(&self) -> proc_macro2::TokenStream {
    let name = self.filter.safe();
    let held = self.held();
    let subject = &self.subject;
    let map = self.framework(&["graphql"], "TryMapFilter");
    let stored = crate::emit::parameter("STORED");
    let refusal = crate::emit::parameter("REFUSAL");
    let convert = crate::emit::parameter("CONVERT");
    quote! {
      #[automatically_derived]
      impl<#stored> #map<#subject, #stored> for #name {
        type Mapped = <#held as #map<#subject, #stored>>::Mapped;

        #[inline]
        fn try_map_filter<#refusal, #convert>(
          self,
          __ingraph_convert: #convert,
        ) -> ::core::result::Result<Self::Mapped, #refusal>
        where
          #convert: ::core::ops::FnMut(#subject) -> ::core::result::Result<#stored, #refusal>,
        {
          <#held as #map<#subject, #stored>>::try_map_filter(
            Self::into_inner(self),
            __ingraph_convert,
          )
        }
      }
    }
  }

  /// The two rows a FIELD of this element resolves through: the family's own map, and the default
  /// reading a declaration that writes no word takes.
  fn readings(&self) -> proc_macro2::TokenStream {
    let name = self.filter.safe();
    let subject = &self.subject;
    let reading = self.framework(&["marker"], self.family.reading());
    let default = self.framework(&["marker"], "DefaultMarker");
    let marker = self.framework(&["marker"], self.family.marker());
    quote! {
      #[automatically_derived]
      impl #reading for #subject {
        type Filter = #name;
      }

      #[automatically_derived]
      impl #default for #subject {
        type Marker = #marker<#subject>;
      }
    }
  }

  /// The WIRE half, behind the binding gate: the element's own scalar, the two crossings, and the
  /// minted filter's input object.
  ///
  /// The input object is why the type is minted at all — the same face over the framework's own
  /// `EnumFilter<Element>` would be `E0119` against `ingraph`'s generic row and `E0117` in the
  /// declaring crate besides — so it rides here for every family alike.
  ///
  /// Inside an anonymous `const`, which is where an emission puts everything it does not owe the
  /// declaring scope a name for.
  fn wire(&self) -> proc_macro2::TokenStream {
    let gate = self.framework(&["gate"], "if_async_graphql");
    let scalar = self.scalar();
    let input = self.input_crossing();
    let output = self.output_crossing();
    let face = self.filter_face();
    quote! {
      const _: () = {
        #gate! {
          #scalar
          #input
          #output
          #face
        }
      };
    }
  }

  /// The ELEMENT's own scalar — the half only the declaring crate can write.
  ///
  /// async-graphql's own attribute over an `impl ScalarType`, which is the shape a declaring crate
  /// wrote by hand before this door existed. Two things follow from spending the library's macro
  /// rather than writing the two faces out: the OUTPUT leg is whichever `resolve` shape that build
  /// compiled — the `boxed-trait` fork a hand-written `async fn` can only pick one side of — and the
  /// registry entry is the library's own, so a schema's scalar entry cannot drift from what that
  /// version of async-graphql publishes.
  ///
  /// The wire GRAMMAR is the inner type's: the element parses whatever its held type parses and
  /// renders whatever that renders, under a name of its own. So `Tag(String)` is a string named
  /// `Tag`, and an inner type with no wire face of its own is `E0277` here, naming that type.
  fn scalar(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let inner = &self.inner;
    let ag = self.framework(&[], "async_graphql");
    let shelf = crate::emit::vendored(&self.krate, "async_graphql");
    let sdl = self.sdl();
    let build = match &self.member {
      syn::Member::Named(ident) => quote!(|__ingraph_inner| Self { #ident: __ingraph_inner }),
      syn::Member::Unnamed(_) => quote!(Self),
    };
    let member = &self.member;
    quote! {
      #[#ag::Scalar(crate = #shelf, name = #sdl)]
      impl #ag::ScalarType for #subject {
        fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
          ::core::result::Result::map_err(
            ::core::result::Result::map(
              <#inner as #ag::InputType>::parse(::core::option::Option::Some(__ingraph_value)),
              #build,
            ),
            #ag::InputValueError::propagate,
          )
        }

        fn to_value(&self) -> #ag::Value {
          <#inner as #ag::InputType>::to_value(&self.#member)
        }
      }
    }
  }

  /// The INPUT CROSSING's row — what ONE OPERAND of this element looks like on the wire.
  ///
  /// The IDENTITY, for the reason a declared vocabulary's is the identity: the row above gives the
  /// element a wire face of its own, so the form it crosses as IS the type. It is owed by a
  /// COLLECTION of this element, whose slots ask the element rather than `InputType` — which is what
  /// lets an operand with no face of its own cross through a carrier, and what makes every element
  /// owe the row alike.
  fn input_crossing(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let crossing = self.framework(&["graphql"], "ToGraphqlInput");
    quote! {
      #[automatically_derived]
      impl #crossing for #subject {
        type Input = Self;
        type Error = ::core::convert::Infallible;

        #[inline]
        fn cross(
          __ingraph_value: Self,
        ) -> ::core::result::Result<Self, ::core::convert::Infallible> {
          ::core::result::Result::Ok(__ingraph_value)
        }

        #[inline]
        fn carry(__ingraph_value: &Self) -> Self {
          ::core::clone::Clone::clone(__ingraph_value)
        }
      }
    }
  }

  /// The OUTPUT CROSSING's row — what a wire face RETURNS a value of this element as.
  ///
  /// By REFERENCE, which is what keeps a row's elements free of a clone per response, and the
  /// identity for the input crossing's reason: the scalar above is already the form a resolver
  /// renders.
  fn output_crossing(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
    quote! {
      #[automatically_derived]
      impl #crossing for #subject {
        type Output<'__ingraph> = &'__ingraph Self;

        #[inline]
        fn to_graphql_output(__ingraph_value: &Self) -> &Self {
          __ingraph_value
        }
      }
    }
  }

  /// The minted filter's INPUT OBJECT — the face the whole mode exists to make writable.
  ///
  /// A LOCAL self type, so the orphan wall never appears: the same impl over the framework's own
  /// `TextFilter<Tag>` is `E0117` here, and `ingraph` reaches that type only through a READING — a
  /// marker the declaring crate owns, which is the module note's second road and not this one.
  ///
  /// Its slots are typed `Option<Element>` and read through async-graphql's own wrappers, because
  /// the element HAS a face by the time this one is registered — so the operand's grammar is stated
  /// once, in the scalar above, and this face spends it.
  ///
  /// The `Nullable` twin comes with it, through the DELEGATION TRAIT — and that is the road this
  /// note used to record as unbuilt.
  ///
  /// The wall was the orphan rule one type over: `Nullable` is the framework's, so
  /// `impl InputType for Nullable<TagFilter>` names a foreign type parameterised by a local one and
  /// is `E0117` here, while a per-concrete row in `ingraph` cannot be written for a filter that
  /// crate has never heard of. What blocked the generic row there was `E0119` against the concrete
  /// rows its own builtins minted — so those rows moved onto `NullableFace` and the generic one is
  /// unopposed. This door writes that trait on the MINTED filter, whose self type is local, and an
  /// `Option<Tag>` column reaches its face through the framework's single blanket.
  ///
  /// So `bare_fields` and `bare_values` are where the field list and the render live, and the
  /// `InputType` pair reads both back off the row: one list, published by the bare face and by its
  /// nullable twin alike.
  ///
  /// # The SHORTHAND LAW reaches a minted face
  ///
  /// `parse` reads what arrived through the framework's own `sent`, so a client writes `42` where
  /// this face means `{ eq: 42 }` exactly as it may at a framework column. The bare value is put
  /// under the FIRST slot's name and the ordinary reads run over that object, so the operand
  /// crosses through the same grammar the longhand takes rather than through a second reading of
  /// it. Rule ② is refused here and acted on by the nullable twin, which is nullability being a
  /// TYPE said at the parse.
  fn filter_face(&self) -> proc_macro2::TokenStream {
    let name = self.filter.safe();
    let subject = &self.subject;
    let held = self.held();
    let ag = self.framework(&[], "async_graphql");
    let nullable_face = self.framework(&["graphql"], "NullableFace");
    let sent = self.framework(&["graphql", "filter"], "sent");
    let sent_ty = self.framework(&["graphql", "filter"], "Sent");
    let sdl = self.filter.external().to_owned();
    let slots = self.family.operations();
    // The slot a BARE value lands in — `eq` at every family, read off the list rather than spelled
    // here so the shorthand and the registration cannot come to name different slots. `operations`
    // answers with at least one row for every family, so the `expect` below is unreachable.
    let bare = slots
      .first()
      .expect("an element family publishes at least one operator slot")
      .wire;

    let fields = slots.iter().map(|slot| {
      let wire = slot.wire;
      let ty = Self::slot_type(&quote!(#subject), slot.list);
      quote! {
        __ingraph_fields.insert(
          ::std::string::String::from(#wire),
          #ag::registry::MetaInputValue {
            name: ::std::string::String::from(#wire),
            description: ::core::option::Option::None,
            ty: <#ty as #ag::InputType>::create_type_info(__ingraph_registry),
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            default_value: ::core::option::Option::None,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });

    let reads = slots.iter().map(|slot| {
      let wire = slot.wire;
      let maybe = format_ident!("maybe_{}", slot.member);
      let ty = Self::slot_type(&quote!(#subject), slot.list);
      quote! {
        __ingraph_held = __ingraph_held.#maybe(
          ::core::result::Result::map_err(
            <#ty as #ag::InputType>::parse(
              #ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
            ),
            #ag::InputValueError::propagate,
          )?,
        );
      }
    });

    let writes = slots.iter().map(|slot| {
      let wire = slot.wire;
      let member = format_ident!("{}", slot.member);
      // Method calls rather than the fully qualified forms the rest of this emission writes:
      // `Option::cloned` is defined twice — once for `Option<&T>` and once for `Option<&mut T>` —
      // so the qualified spelling is `E0034` and only the receiver disambiguates it.
      // The box's own type is SPELLED at the conversion: `Box::from` alone leaves the allocator
      // parameter free, and three of async-graphql's `Box` rows then apply at once (`E0283`).
      let held = if slot.list {
        quote!(self.0.#member().map(<::std::boxed::Box<[#subject]>>::from))
      } else {
        quote!(self.0.#member().cloned())
      };
      quote! {
        __ingraph_map.insert(#ag::Name::new(#wire), #ag::InputType::to_value(&#held));
      }
    });

    quote! {
      #[automatically_derived]
      impl #ag::InputType for #name {
        type RawValueType = Self;

        #[inline]
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          __ingraph_registry.create_input_type::<Self, _>(
            #ag::registry::MetaTypeId::InputObject,
            |__ingraph_registry| #ag::registry::MetaType::InputObject {
              name: ::std::string::String::from(#sdl),
              description: ::core::option::Option::None,
              input_fields: <Self as #nullable_face>::bare_fields(__ingraph_registry),
              visible: ::core::option::Option::None,
              inaccessible: false,
              tags: ::std::vec::Vec::new(),
              rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
              oneof: false,
              directive_invocations: ::std::vec::Vec::new(),
            },
          )
        }

        fn parse(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> #ag::InputValueResult<Self> {
          let __ingraph_object = match #sent(__ingraph_value) {
            #sent_ty::Longhand(__ingraph_object) => __ingraph_object,
            // Rule ① — a bare value is this face's `eq`, put under that key so the reads below
            // cross it through the same grammar the longhand takes rather than through a second
            // reading of the operand.
            #sent_ty::Bare(__ingraph_bare) => {
              let mut __ingraph_object = #ag::indexmap::IndexMap::new();
              #ag::indexmap::IndexMap::insert(
                &mut __ingraph_object,
                #ag::Name::new(#bare),
                __ingraph_bare,
              );
              __ingraph_object
            }
            // Rule ② is REFUSED here and acted on by the nullable twin: a `NOT NULL` column has no
            // null test to set, which is nullability being a TYPE said at the parse.
            #sent_ty::Null => {
              return ::core::result::Result::Err(#ag::InputValueError::expected_type(
                #ag::Value::Null,
              ));
            }
            #sent_ty::Refused(__ingraph_sent) => {
              return ::core::result::Result::Err(#ag::InputValueError::expected_type(
                __ingraph_sent,
              ));
            }
          };
          let mut __ingraph_held = <#held>::new();
          #(#reads)*
          ::core::result::Result::Ok(Self(__ingraph_held))
        }

        fn to_value(&self) -> #ag::Value {
          #ag::Value::Object(<Self as #nullable_face>::bare_values(self))
        }

        #[inline]
        fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
          ::core::option::Option::Some(self)
        }
      }

      #[automatically_derived]
      impl #ag::InputObjectType for #name {}

      #[automatically_derived]
      impl #nullable_face for #name {
        fn bare_fields(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
          let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
          #(#fields)*
          __ingraph_fields
        }

        fn bare_values(&self) -> #ag::indexmap::IndexMap<#ag::Name, #ag::Value> {
          let mut __ingraph_map = #ag::indexmap::IndexMap::new();
          #(#writes)*
          __ingraph_map
        }
      }
    }
  }

  /// What ONE slot crosses as — an operand, or a list of them.
  fn slot_type(subject: &proc_macro2::TokenStream, list: bool) -> proc_macro2::TokenStream {
    if list {
      quote!(::core::option::Option<::std::boxed::Box<[#subject]>>)
    } else {
      quote!(::core::option::Option<#subject>)
    }
  }
}