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
//! The ID DEVICE's model: what `#[derive(ingraph::Id)]` emits for a `#[repr(transparent)]` tuple
//! wrapper — the whole register a product's own id type used to hand-write, from one word.
//!
//! ```text
//! #[derive(ingraph::Id)]
//! #[repr(transparent)]
//! pub struct TrackId(uuid::Uuid);
//! ```
//!
//! # Named for the TRAIT IT ADMITS, which is the `derive(Clone)` convention
//!
//! The word is `Id` because what the door hands out is [`Id`](../../../ingraph/trait.Id.html)
//! membership, the same way `#[derive(Clone)]` is named for `Clone`. It is deliberately NOT the
//! attribute spelling `#[ingraph(id)]`: that word is the RECORD's, naming which FIELD of a
//! declaration is its address, and one word meaning two things across two devices is a vocabulary a
//! reader has to disambiguate by position.
//!
//! # THE ROSTER IS A MEASUREMENT, and the measurement is two live registers
//!
//! Everything below was hand-written — twice, independently, to the impl — by `findit`'s `MediaId`
//! and `mediagraph`'s `VolumeId`, each a `pub struct X(uuid::Uuid)`. This device emits that register
//! and nothing beside it, so the door's content is a census rather than a wish list:
//!
//! | face | mechanism |
//! |---|---|
//! | `DelegatesId` | the transparency assertion — key admission |
//! | `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash` | delegated to the inner |
//! | `Display`, `FromStr` | delegated to the inner |
//! | `From<Inner>`, `From<Self> for Inner`, `From<Self> for String` | the conversions, and the SQL comparison's crossing |
//! | `CursorValue` | delegated to the inner |
//! | `ColumnKind` | one column, the default |
//! | `IdColumn<Db>` | the storage seam, delegating — UNGATED, see below |
//! | `StoredAs<Db>` | the seam's word, UNGATED — see below |
//! | `Carrier<Db>`, `Assemble<'_, R>` | the seam's bind and read back, gated — see below |
//! | `ToGraphqlInput`, `ToGraphqlOutput` | the identity crossing and the borrow |
//! | `ScalarWire`, `CompositeFilterMarker`, `DefaultMarker` | the filter reading, over a minted `<Name>Wire` |
//! | `async_graphql::ScalarType` | the scalar itself, wide in and strict out |
//! | the CASTS | `from_ref`, `as_inner`, `from_slice`, `as_inner_slice` |
//!
//! # THE STORAGE SEAM, and the census that closed the road it replaced
//!
//! The three storage rows delegate to the inner THROUGH
//! [`IdColumn<Db>`](../../../ingraph/trait.IdColumn.html) — the framework trait that answers *how
//! does an id wrapping me reach a column?* per member, per dialect. That trait's own note carries the
//! ruling, the per-member roads and the completeness audit; what belongs here is why this device
//! reads a trait rather than the inner directly or a word at the declaration.
//!
//! **What the road used to be, and why.** `ingraph` shipped a bare [`uuid::Uuid`] exactly four rows —
//! `Id` membership, the filesystem segment, the column-language row and `CursorValue` — no
//! `ColumnKind`, no `StoredAs<Db>`, no `Carrier<Db>`, no `Assemble`; and `sqlx`'s own `uuid` feature
//! was off everywhere in the graph. A row spelled `where Inner: Carrier<Db>` was therefore
//! unsatisfiable at the one declaration this device exists for, so both live registers bound on
//! `String` and bound the CANONICAL TEXT, and this device emitted what they wrote.
//!
//! **The 2026-08-29 uuid knife filled every one of those rows** — each backend storing a uuid in its
//! own native form — which removed the bound blocker and left a COVERAGE one. Measured against the
//! sealed set on SQLite (ingraph #452), twelve members had no `ColumnKind`/`StoredAs`/`Carrier`/
//! `Assemble` at all — `i128`, `u64`, `u128`, the six `core::net` address types,
//! `smol_str::SmolStr`, `bson::Uuid` and `bson::oid::ObjectId` — so re-bounding the rows on `#inner`
//! would have turned each of those from *stored as text* into *not storable*, through a VACUOUS impl
//! rather than a named refusal.
//!
//! **`IdColumn<Db>` is what closes both at once**, and it is #452's 呈裁 1 resolved as a seam rather
//! than as a word: every member of the sealed vocabulary has a row, so nothing is un-stored, and each
//! row names the form that member actually stores in, so a uuid inherits its native sixteen bytes.
//! The twelve are on the text road their `Display`/`FromStr` already gave them; the one member that
//! MOVED is [`uuid::Uuid`].
//!
//! ## Why the seam is a trait and not an attribute
//!
//! **A MACRO SEES TOKENS.** `type MyId = uuid::Uuid` reaches this device as the word `MyId`, and no
//! front-end pass can tell what it names — the same floor [`inner_is_string`](IdModel::inner_is_string)
//! is documented at, where the failure mode is a legible `E0119`. A uuid branch decided on tokens
//! would fail as a SILENT DIVERGENCE IN STORED FORM instead, which is the one failure a storage
//! decision must not have. So per-inner dispatch has to be resolved by the type system.
//!
//! An attribute at the declaration was the other candidate and is refused for three reasons rather
//! than one: it re-adds ceremony against the zero-ceremony ruling this door was opened under, it
//! restates a TYPE-LEVEL fact once per declaration where the type already knows it, and a declaration
//! that names the wrong road gets an `E0277` naming nothing a reader can act on. An optional override
//! word MAY come later as sugar OVER the seam; it is not here.
//!
//! ## What the switch changed, stated rather than left to be discovered
//!
//! A wrapper over a [`uuid::Uuid`] declares, binds and reads back the NATIVE form — PostgreSQL
//! `uuid`, MySQL `binary(16)`, SQLite `BLOB` — where it used to spend the canonical 36-character
//! text. Nothing in this workspace is published, so there is no migration ceremony: a declarer
//! re-emits its schema on the next sync. A wrapper over any other member stores exactly what it
//! stored before.
//!
//! `StoredAs<Db>` carries NO FURTHER GATE, as it did not before — the trait puts no
//! `Db: sqlx::Database` bound on itself, so there is nothing here for a family gate to guard — and
//! neither does the wrapper's own `IdColumn<Db>` row, which is the seam read one layer out so that an
//! id over an id stores.
//!
//! # THE ONE OBLIGATION ON WHAT IS WRAPPED: a canonical text form
//!
//! The obligation SURVIVED the seam and it survived unchanged, because what asks for it was never
//! the storage rows alone: an id must implement [`Display`](core::fmt::Display) and
//! [`FromStr`](core::str::FromStr). The delegating text pair spends both, the SQL crossing spends
//! the first, and the GraphQL scalar — wide in through the door, canonical out — spends both again,
//! so an inner type with neither is one this device has nothing to write the register with.
//!
//! What the seam moved is which row ASKS. The storage rows used to carry `Inner: Display` and
//! `Inner: FromStr` because they crossed through text themselves; they now carry
//! `Inner: IdColumn<Db>`, and the text obligation rides the seam's own text-road impls where it is a
//! fact about a concrete member rather than a predicate on a declaration. The refusals a declaration
//! gets are unchanged, which is asserted rather than assumed —
//! `key_admission/derive/an_id_wrapper_with_no_text_form` is the golden.
//!
//! That is a REAL boundary and not a formality. `[u8; N]` is a measured member of the id vocabulary
//! and has neither face, so `#[derive(ingraph::Id)] #[repr(transparent)] struct Sha256([u8; 32])` is
//! refused — at the declaration, naming the two missing faces, because the obligations ride the
//! rows' own `where` clauses. `smol_bytes::Utf8Bytes` has `Display` and no `FromStr`, and is refused
//! for the half it is missing. A digest and a text carrier are perfectly good keys; what they are not
//! is text-shaped VALUES, and the road for them is the one they always had —
//! `unsafe impl ingraph::DelegatesId`, which asks for no text at all.
//!
//! The obligation is stated rather than checked at the front end, deliberately. A macro sees TOKENS:
//! `type Inner = MyAlias` reaches this device as the word `MyAlias`, so a front-end test of *does it
//! render* would be a guess about a name. A `where` predicate is the compiler's own answer, at the
//! declaration, naming the type and the trait.
//!
//! # WHY THE IDENTITY KIT IS EMITTED AND NOT LEFT TO `#[derive(…)]`
//!
//! [`DelegatesId`](../../../ingraph/trait.DelegatesId.html)'s safety contract has a clause a shape
//! check cannot close: *two `Self`s are equal exactly when their delegates are*. The shape law
//! closes the other two — no second field, no tag, no width — but a hand-written `PartialEq` that
//! ignored a case would falsify the assertion this device makes on the declaration's behalf, and
//! what that buys is two distinct keys resolving one stored row rather than a compile error.
//!
//! So the door writes the identity kit itself, delegating, and the obligation closes STRUCTURALLY:
//! there is no `PartialEq` on this type that is not the inner's own, because the one that exists is
//! emitted here and a second is `E0119`.
//!
//! `Ord` and `PartialOrd` are NOT among them, and the absence is MEASURED rather than economical. No
//! id duty reads either — the stored order is the backend's reading of the value, and the filesystem
//! segment is `store::fs`'s `Render`, which the delegation row routes to the inner — and
//! `ingraph/tests/aggregate_group_newtype_probe.rs` stands a deliberately `Ord`-refusing wrapper at a
//! live group-key position to prove it. A door that minted an order would be inventing one for a type
//! whose author refused it. `Copy` is absent for the opposite reason: `#[derive(Copy)]` beside this
//! word resolves against the `Clone` emitted here, and a `Copy` row bounded on the inner would refuse
//! every text-carried id outright.
//!
//! # THE CASTS, and the door that has no invariant to break
//!
//! `from_ref` views a `&Inner` as a `&Self`, which is sound because the type is
//! `#[repr(transparent)]` over exactly one field — the front end refuses every other shape — and
//! unsound the moment a wrapper carries a CONSTRUCTOR INVARIANT its inner does not. This door
//! declares it has none: an id is an address, the whole of its content is the value it holds, and a
//! type whose values are a checked subset of its inner's belongs at
//! `#[derive(ingraph::NewType)]`'s `scalar(check = "…")` door, where every read is spent on the
//! check.

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

#[cfg(test)]
mod tests;

/// A declared ID WRAPPER, as the device reads it.
///
/// PLAIN, for [`Kits`](crate::newtype::Kits)' 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 IdModel {
  /// The declaration's own visibility, which the minted reading and the casts take: a door minted
  /// for a type nobody outside the module can name has no business being wider than the type.
  pub vis: syn::Visibility,
  /// The wrapper the faces are OF.
  pub subject: syn::Ident,
  /// The `ingraph` root the expansion spells its shelf through.
  pub krate: syn::Path,
  /// The ONE type this wrapper holds, at position zero.
  pub inner: syn::Type,
}

impl IdModel {
  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
  /// them.
  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
    crate::emit::framework(&self.krate, module, name)
  }

  /// A whole VENDORED crate on that shelf, as the string an attribute's `crate = …` takes.
  fn vendored(&self, name: &str) -> String {
    crate::emit::vendored(&self.krate, name)
  }

  /// The reading this device mints for the filter face — `<Name>Wire`, the shape both live registers
  /// wrote by hand.
  #[must_use]
  pub fn reading_name(&self) -> syn::Ident {
    format_ident!("{}Wire", self.subject)
  }

  /// The name a SCHEMA writes: the Rust one, unraw'd.
  ///
  /// No rename knob, where `#[derive(ingraph::NewType)]` has one. A newtype publishes a VALUE and may
  /// well want the schema to call it something else; an id publishes an ADDRESS, and the type's own
  /// name is the only thing a client can correlate it with — both live registers spell
  /// `#[Scalar(name = "<the type>")]` and neither reached for anything else.
  fn sdl(&self) -> String {
    self.subject.unraw().to_string()
  }

  /// The predicate `Inner: <trait>` — the OBLIGATION every delegation carries.
  ///
  /// Over the INNER TYPE, which is [`NewTypeModel::owes`](crate::newtype)'s choice for the same
  /// reason: a transparent wrapper answers a face exactly when the value it holds does, so the
  /// refusal for a missing one is `E0277` naming that type and that trait AT THE DECLARATION rather
  /// than a method-not-found inside an expansion.
  ///
  /// It also SCREENS the door. A predicate over a concrete inner is a trivial bound and rustc
  /// refuses an unsatisfied one at the impl, so `#[derive(ingraph::Id)] struct Ratio(f64)` is
  /// `E0277` naming `f64: Eq` where it is written. An address whose value cannot answer identity is
  /// not an address, and this is where that is said.
  fn owes(&self, bound: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
    let inner = &self.inner;
    quote!(#inner: #bound)
  }

  /// The KEY ROW — the sealed vocabulary's third admission law, written by the device instead of by
  /// hand.
  fn key_delegation(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let inner = &self.inner;
    let delegates = self.framework(&["id"], "DelegatesId");
    quote! {
      // SAFETY: the front end refuses every shape but a `#[repr(transparent)]` tuple struct holding
      // exactly one field, so there is no second field, no tag and no width of this type's own; this
      // row hands that one field back by reference and does nothing else, so it is pure and answers
      // the same inner every time; and the identity kit this device emits beside it is the inner's
      // own, so two values are equal exactly when their delegates are. Every clause of the
      // transparency contract is closed by construction rather than asserted by a reader.
      #[automatically_derived]
      unsafe impl #delegates for #subject {
        type Inner = #inner;

        #[inline]
        fn delegate(&self) -> &#inner {
          &self.0
        }
      }
    }
  }

  /// The IDENTITY KIT — five rows, each the inner's own answer under this type's name.
  ///
  /// Fully qualified throughout, on the emission law [`newtype`](crate::newtype)'s module note
  /// states: `<Inner as Trait>::method(&self.0, …)` pins method resolution, so an inner type growing
  /// an inherent `eq` or `hash` cannot silently take the call away from the trait the row is
  /// implementing.
  fn identity(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let inner = &self.inner;
    let name = subject.to_string();
    let debug = self.owes(quote!(::core::fmt::Debug));
    let clone = self.owes(quote!(::core::clone::Clone));
    let partial_eq = self.owes(quote!(::core::cmp::PartialEq));
    let eq = self.owes(quote!(::core::cmp::Eq));
    let hash = self.owes(quote!(::core::hash::Hash));

    quote! {
      #[automatically_derived]
      impl ::core::fmt::Debug for #subject where #debug {
        #[inline]
        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          // The held value under this type's own name — `TypedId`'s hand-written row, for its
          // reason: what the wrapper adds is a NAME, and a reader has already been shown it.
          let mut __ingraph_tuple = ::core::fmt::Formatter::debug_tuple(__ingraph_f, #name);
          ::core::fmt::DebugTuple::field(&mut __ingraph_tuple, &self.0);
          ::core::fmt::DebugTuple::finish(&mut __ingraph_tuple)
        }
      }

      #[automatically_derived]
      impl ::core::clone::Clone for #subject where #clone {
        #[inline]
        fn clone(&self) -> Self {
          Self(<#inner as ::core::clone::Clone>::clone(&self.0))
        }
      }

      #[automatically_derived]
      impl ::core::cmp::PartialEq for #subject where #partial_eq {
        #[inline]
        fn eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
          <#inner as ::core::cmp::PartialEq>::eq(&self.0, &__ingraph_other.0)
        }
      }

      #[automatically_derived]
      impl ::core::cmp::Eq for #subject where #eq {}

      #[automatically_derived]
      impl ::core::hash::Hash for #subject where #hash {
        #[inline]
        fn hash<__IngraphHasher>(&self, __ingraph_state: &mut __IngraphHasher)
        where
          __IngraphHasher: ::core::hash::Hasher,
        {
          <#inner as ::core::hash::Hash>::hash(&self.0, __ingraph_state);
        }
      }
    }
  }

  /// The TEXT PAIR and the three conversions.
  ///
  /// [`Display`](core::fmt::Display) and [`FromStr`](core::str::FromStr) are the door every storage
  /// and wire row below spends: the bind renders through one, the decode and the scalar's `parse`
  /// read through the other. Both delegate, so the canonical spelling is the inner type's own and
  /// this device invents no grammar.
  ///
  /// `FromStr::Err` is the INNER's refusal rather than a minted wrapper. Both live registers minted
  /// one — `ParseMediaIdError`, `ParseVolumeIdError`, each a newtype over `uuid::Error` — and what
  /// the mint buys is a name in the declaring crate's own error vocabulary, which is a choice about
  /// that crate rather than a fact about the wrapper. Delegating is the smaller claim and the one a
  /// device can make truthfully: the spellings this type admits are exactly the inner's, so the
  /// refusal for a spelling it does not admit is exactly the inner's too.
  ///
  /// `From<Self> for String` is the SQL comparison's crossing INTO A DECLARED TEXT COLUMN and not a
  /// convenience: it is what gives `String: TryFrom<Self>` through std's blanket, which
  /// `SqlScalarComparison<String, Db>` asks for. It is no longer what this device's own storage rows
  /// spend — those go through [`IdColumn`](../../../ingraph/trait.IdColumn.html), and a field whose
  /// storage type IS its own resolves the crossing reflexively — so what the row serves now is a
  /// declaration that says `<db>(type = "String")` over an id. It cannot fail, the rendering being
  /// this type's own `Display`.
  fn text(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let inner = &self.inner;
    let display = self.owes(quote!(::core::fmt::Display));
    let from_str = self.owes(quote!(::core::str::FromStr));

    // The SQL crossing, WITHHELD where it would be the row above spelled twice. A wrapper over a
    // `String` already gets `From<Self> for String` as its inner conversion, and emitting the
    // crossing beside it is `E0119` on one impl written by one device — the worst kind, since a
    // declarer cannot edit either half.
    //
    // A TOKEN comparison, because a macro sees tokens: `type Text = String` reaches here as the word
    // `Text` and nothing can tell this pass otherwise. So the check catches the spellings a
    // declaration actually writes and an ALIAS still collides — with `E0119` naming two impls of
    // `From<…> for String`, which is at least a refusal that says what it is. It is the same floor
    // every macro reads a type name at.
    let crossing = if self.inner_is_string() {
      quote!()
    } else {
      quote! {
        #[automatically_derived]
        impl ::core::convert::From<#subject> for ::std::string::String where #display {
          #[inline]
          fn from(__ingraph_id: #subject) -> Self {
            ::std::string::ToString::to_string(&__ingraph_id)
          }
        }
      }
    };

    quote! {
      #[automatically_derived]
      impl ::core::fmt::Display for #subject where #display {
        #[inline]
        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          <#inner as ::core::fmt::Display>::fmt(&self.0, __ingraph_f)
        }
      }

      #[automatically_derived]
      impl ::core::str::FromStr for #subject where #from_str {
        type Err = <#inner as ::core::str::FromStr>::Err;

        #[inline]
        fn from_str(__ingraph_text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
          ::core::result::Result::map(
            <#inner as ::core::str::FromStr>::from_str(__ingraph_text),
            Self,
          )
        }
      }

      #[automatically_derived]
      impl ::core::convert::From<#inner> for #subject {
        #[inline]
        fn from(__ingraph_inner: #inner) -> Self {
          Self(__ingraph_inner)
        }
      }

      #[automatically_derived]
      impl ::core::convert::From<#subject> for #inner {
        #[inline]
        fn from(__ingraph_id: #subject) -> Self {
          __ingraph_id.0
        }
      }

      #crossing
    }
  }

  /// Whether the wrapped type is `String` AS THIS DECLARATION SPELLS IT.
  ///
  /// The four spellings a declaration writes, and no more — see [`text`](Self::text) for why a token
  /// comparison is the floor here rather than a shortcut.
  fn inner_is_string(&self) -> bool {
    const SPELLINGS: [&str; 4] = [
      "String",
      "std :: string :: String",
      ":: std :: string :: String",
      "alloc :: string :: String",
    ];
    let written = quote::ToTokens::to_token_stream(&self.inner).to_string();
    SPELLINGS.contains(&written.as_str())
  }

  /// The PAGE and STORAGE rows.
  ///
  /// [`CursorValue`] delegates to the inner, which was the ONE value-column face `ingraph` shipped a
  /// bare `uuid::Uuid` when this device landed — both live registers delegated here and hand-wrote
  /// everything else, and that asymmetry was the whole shape of the original census. A uuid now has
  /// all of them, and this row is unchanged by that: delegating to the inner is what it always did.
  ///
  /// [`ColumnKind`] is the default: one column. It is ungated, as the trait is — a width names no
  /// database.
  ///
  /// # The three storage rows go through `IdColumn<Db>` AT THE INNER
  ///
  /// `StoredAs<Db>`, `Carrier<Db>` and `Assemble` are all written over ONE projection —
  /// `<Inner as IdColumn<Db>>::Stored` — so the word a `CREATE TABLE` declares, the value the bind
  /// pushes and the value the decode reads back are one decision made in one place. The seam's own
  /// note has the ruling and the census; what belongs here is the shape it takes at the emission:
  ///
  /// * the row a member takes is the INNER's, so `TrackId(Uuid)` inherits the native sixteen bytes
  ///   and `SomethingId(SmolStr)` keeps the canonical text, with no word at either declaration;
  /// * the obligation is `Inner: IdColumn<Db>` and no longer `Display`/`FromStr`. Those two are
  ///   still owed — the text pair, the crossing and the scalar spend them — so the door's one
  ///   requirement on what is wrapped is unchanged; what moved is which row asks;
  /// * the crossing's refusal is the seam's `Refusal`, whose `Error + Send + Sync + 'static` bound
  ///   the trait carries, so this emission states none of it.
  ///
  /// It also emits the wrapper's OWN `IdColumn<Db>` row, delegating to what it holds. That is the
  /// seam read one layer out: an id over an id stores, resolving to whichever member the chain
  /// grounds in, exactly as [`DelegatesId`] admits one duty over.
  ///
  /// # The one place the door NARROWED, recorded rather than left to be met
  ///
  /// An inner this crate has never seen used to reach the storage rows on `Display` + `FromStr`
  /// alone, since that is what the text road spent. It now needs an `IdColumn<Db>` row of its own —
  /// one impl, three lines, named at the refusal by that trait's `on_unimplemented` — and the
  /// trade is that a downstream inner now SAYS what it is stored as instead of being assumed to be
  /// text.
  ///
  /// The row this device emits is what keeps the framework's own compositions free: a wrapper over
  /// another `#[derive(ingraph::Id)]` wrapper needs nothing, through the delegating row this
  /// `storage` emits below. A wrapper over a `#[derive(ingraph::NewType)]` value needs the impl
  /// too, and — as of the 信己 ruling — that device now emits it unconditionally, the same posture
  /// this one already takes: `newtype::NewTypeModel::id_column_delegation` is the mirror, written
  /// beside that device's own `key_delegation` for `DelegatesId`'s reason. An id over a newtype
  /// therefore needs nothing either, closing the one gap this note used to name.
  ///
  /// The two GATED SQL rows ride the FAMILY gate rather than a dialect's, and they are generic over
  /// the database exactly as both registers wrote them: what varies per dialect is the stored form's
  /// own row, and stating the obligation as `Stored: Carrier<Db>` is what lets ONE impl serve every
  /// dialect this build has.
  fn storage(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let inner = &self.inner;
    let cursor_value = self.framework(&["cursor"], "CursorValue");
    let column_kind = self.framework(&["column"], "ColumnKind");
    let column_eq = self.framework(&["column"], "ColumnEq");
    let owed_eq = self.owes(quote!(#column_eq));
    let order_leaves = self.framework(&["column"], "DeclaredLeaves");
    let stored_as = self.framework(&["column"], "StoredAs");
    let assemble = self.framework(&["column"], "Assemble");
    let id_column = self.framework(&["id"], "IdColumn");
    let carrier = self.framework(&["comparison", "sql"], "Carrier");
    let path = self.framework(&["comparison"], "Path");
    let gate = self.framework(&["gate"], "if_sqlx");
    let database = self.framework(&["sqlx"], "Database");
    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
    let result = self.framework(&["sqlx"], "Result");
    let sqlx_error = self.framework(&["sqlx"], "Error");
    let row = self.framework(&["sqlx"], "Row");
    let cursor = self.owes(quote!(#cursor_value));
    // The seam AT THE INNER, spelled once per position it is read at. `Db` is the emitted parameter
    // for the rows that carry one; `Row::Database` is what the decode has instead, the read half
    // being parameterised by the ROW rather than by the dialect.
    let seam = quote!(#id_column<__IngraphDb>);
    let stored = quote!(<#inner as #seam>::Stored);
    let row_seam = quote!(#id_column<<__IngraphRow as #row>::Database>);
    let row_stored = quote!(<#inner as #row_seam>::Stored);

    quote! {
      #[automatically_derived]
      impl #cursor_value for #subject where #cursor {
        #[inline]
        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          <#inner as #cursor_value>::write_cursor(&self.0, __ingraph_out)
        }

        #[inline]
        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
          ::core::option::Option::map(
            <#inner as #cursor_value>::read_cursor(__ingraph_bytes),
            Self,
          )
        }
      }

      #[automatically_derived]
      impl #column_kind for #subject {}

      // **THE SAMENESS ROW**, delegated to the inner exactly as the `PartialEq` in `identity` is —
      // one more line on that face table reading *delegated to the inner*, and the one an emitted
      // row now folds where it used to derive `PartialEq` over its field types. It owes the INNER's
      // `ColumnEq` rather than a `PartialEq`, so a key over a type whose sameness is not `==` is a
      // key this device writes with no special case.
      #[automatically_derived]
      impl #column_eq for #subject where #owed_eq {
        #[inline]
        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
          <#inner as #column_eq>::column_eq(&self.0, &__ingraph_other.0)
        }
      }

      // **ONE LEAF, AND IT IS THE VALUE** — the word that lets a cursor slot over this type be
      // spelled the one way every column is spelled. It states no `ColumnKind::ORDER`, so no term
      // over it ever expands and nothing ever asks it for a leaf narrower than itself; what the word
      // buys is that `<<T as DefaultMarker>::Marker as ToOrderLeaves>::Leaf` RESOLVES for it, which
      // is what keeps the emitted cursor free of a scalar/composite branch a macro cannot make.
      //
      // NO BOUNDS, deliberately: the `Clone` a boundary costs rides the blanket this word is the key
      // to, so it is asked for at the first page that holds one rather than at every declaration.
      #[automatically_derived]
      impl #order_leaves for #subject {}

      // THE SEAM, READ ONE LAYER OUT: this wrapper is stored exactly as the value it holds is, so an
      // id wrapping THIS id stores too — the chain resolving to whichever vocabulary member it
      // grounds in. Ungated, as the trait is, and it costs a declaration nothing.
      #[automatically_derived]
      impl<__IngraphDb> #seam for #subject
      where
        #inner: #seam,
      {
        type Stored = #stored;
        type Refusal = <#inner as #seam>::Refusal;

        #[inline]
        fn to_stored(&self) -> Self::Stored {
          <#inner as #seam>::to_stored(&self.0)
        }

        #[inline]
        fn from_stored(
          __ingraph_stored: Self::Stored,
        ) -> ::core::result::Result<Self, Self::Refusal> {
          ::core::result::Result::map(<#inner as #seam>::from_stored(__ingraph_stored), Self)
        }
      }

      // The FOURTH face, beside the width above: what a `CREATE TABLE` declares this column as. It
      // rides no gate — `StoredAs<Db>` names no `sqlx::Database` bound, so nothing here depends on
      // the SQL family being compiled in — and it reads the word off the INNER's stored form rather
      // than restating one, which is what keeps the declaration and the bind below the same decision.
      #[automatically_derived]
      impl<__IngraphDb> #stored_as<__IngraphDb> for #subject
      where
        #inner: #seam,
        #stored: #stored_as<__IngraphDb>,
      {
        const WORDS: &'static [&'static ::core::primitive::str] =
          <#stored as #stored_as<__IngraphDb>>::WORDS;
      }

      #gate! {
        // The bind is the OWNED stored form, which is what `push_bind` takes: the value is moved
        // into the builder's argument buffer, so nothing borrowed from `&self` can be handed over.
        #[automatically_derived]
        impl<__IngraphDb> #carrier<__IngraphDb> for #subject
        where
          __IngraphDb: #database,
          #inner: #seam,
          #stored: #carrier<__IngraphDb>,
        {
          #[inline]
          fn push_bind(&self, __ingraph_qb: &mut #query_builder<__IngraphDb>) {
            <#stored as #carrier<__IngraphDb>>::push_bind(
              &<#inner as #seam>::to_stored(&self.0),
              __ingraph_qb,
            );
          }
        }

        // The decode: one column back through the seam's own door, which CANONICALISES wherever the
        // road parses — a column holding a spelling the inner type folds still reads back the same
        // identity — and is the identity wherever the stored form IS the value.
        #[automatically_derived]
        impl<'__ingraph, __IngraphRow> #assemble<'__ingraph, __IngraphRow> for #subject
        where
          __IngraphRow: #row,
          #inner: #row_seam,
          #row_stored: #assemble<'__ingraph, __IngraphRow>,
        {
          fn assemble(
            __ingraph_row: &'__ingraph __IngraphRow,
            __ingraph_under: ::core::option::Option<&#path<'_>>,
          ) -> #result<Self> {
            let __ingraph_stored = <#row_stored as #assemble<'__ingraph, __IngraphRow>>::assemble(
              __ingraph_row,
              __ingraph_under,
            )?;
            ::core::result::Result::map(
              ::core::result::Result::map_err(
                <#inner as #row_seam>::from_stored(__ingraph_stored),
                |__ingraph_refused| {
                  #sqlx_error::Decode(::std::boxed::Box::new(__ingraph_refused))
                },
              ),
              Self,
            )
          }
        }
      }
    }
  }

  /// The WIRE rows — the crossings, the minted reading, the two markers and the scalar itself.
  ///
  /// The crossings are the IDENTITY: a type that publishes a scalar of its own crosses as itself, so
  /// `cross` is `Ok` and `carry` is a clone. That is not a delegation missed — it is what *this type
  /// IS its own GraphQL scalar* means, and both live registers wrote exactly these bodies.
  ///
  /// `<Name>Wire` is an uninhabited enum, minted OUTSIDE the anonymous const because
  /// [`CompositeFilterMarker`] names it in an associated type a downstream resolves — a reading is a
  /// name the declaring scope has to be able to write.
  fn wire(
    &self,
  ) -> (
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
  ) {
    let subject = &self.subject;
    let inner = &self.inner;
    let vis = &self.vis;
    let reading = self.reading_name();
    let filter_name = format!("{}Filter", self.sdl());
    let ag = self.framework(&[], "async_graphql");
    let gate = self.framework(&["gate"], "if_async_graphql");
    let shelf = self.vendored("async_graphql");
    let sdl = self.sdl();
    let input = self.framework(&["graphql"], "ToGraphqlInput");
    let output = self.framework(&["graphql"], "ToGraphqlOutput");
    let scalar_wire = self.framework(&["graphql"], "ScalarWire");
    let scalar_filter = self.framework(&["graphql"], "ScalarFilter");
    let composite_filter_marker = self.framework(&["marker"], "CompositeFilterMarker");
    let composite_marker = self.framework(&["marker"], "CompositeMarker");
    let default_marker = self.framework(&["marker"], "DefaultMarker");
    let clone = self.owes(quote!(::core::clone::Clone));
    let display = self.owes(quote!(::core::fmt::Display));
    let from_str = self.owes(quote!(::core::str::FromStr));

    let doc = format!(
      " How a [`{subject}`] crosses when the framework's own ordering filter holds it — the reading \
       that gives `ScalarFilter<{subject}, {reading}>` a face.\n\n Uninhabited: it is a NAME the \
       filter is parameterised by and never a value anything builds."
    );

    let declaration = quote! {
      #[doc = #doc]
      #vis enum #reading {}
    };

    let rows = quote! {
      #[automatically_derived]
      impl #input for #subject where #clone {
        type Input = Self;
        type Error = ::core::convert::Infallible;

        #[inline]
        fn cross(__ingraph_input: Self::Input) -> ::core::result::Result<Self, Self::Error> {
          ::core::result::Result::Ok(__ingraph_input)
        }

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

      #[automatically_derived]
      impl #output for #subject {
        type Output<'__ingraph>
          = &'__ingraph Self
        where
          Self: '__ingraph;

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

      #[automatically_derived]
      impl #scalar_wire<#subject> for #reading where #clone {
        const NAME: &'static ::core::primitive::str = #filter_name;

        type Carrier = #subject;
        type Error = ::core::convert::Infallible;

        #[inline]
        fn cross(
          __ingraph_carrier: Self::Carrier,
        ) -> ::core::result::Result<#subject, Self::Error> {
          ::core::result::Result::Ok(__ingraph_carrier)
        }

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

      // The same predicate at both host kinds: an id occupies one column and the whole of it is
      // stored, so there is no rowless/row-holding difference for the two seats to record.
      #[automatically_derived]
      impl #composite_filter_marker for #subject {
        type Filter = #scalar_filter<#subject, #reading>;
        type ColumnFilter = #scalar_filter<#subject, #reading>;
      }

      // The interpretation a field of this type is read under: the framework's COMPOSITE reading,
      // one value occupying a column of its own.
      #[automatically_derived]
      impl #default_marker for #subject {
        type Marker = #composite_marker<#subject>;
      }
    };

    // OUTSIDE the anonymous const, which is where `#[derive(ingraph::NewType)]` puts its own: the
    // `#[Scalar]` attribute is a vendored macro over the impl it decorates, and an emission does not
    // put another crate's expansion somewhere that crate never agreed to be.
    let scalar = quote! {
      #gate! {
        // WIDE IN, STRICT OUT. The door is this type's own `FromStr`, so what spellings are admitted
        // is the inner type's business and there is no second grammar here to keep in step; what
        // this layer adds is the JSON SHAPE, and the refusal a client gets for anything else. The
        // rendering is `Display`'s, which is the one spelling this type writes back.
        #[#ag::Scalar(crate = #shelf, name = #sdl)]
        impl #ag::ScalarType for #subject
        where
          #display,
          #from_str,
          <#inner as ::core::str::FromStr>::Err: ::core::fmt::Display,
        {
          fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
            match &__ingraph_value {
              #ag::Value::String(__ingraph_text) => ::core::result::Result::map_err(
                <Self as ::core::str::FromStr>::from_str(__ingraph_text),
                #ag::InputValueError::custom,
              ),
              _ => ::core::result::Result::Err(#ag::InputValueError::expected_type(
                ::core::clone::Clone::clone(&__ingraph_value),
              )),
            }
          }

          fn is_valid(__ingraph_value: &#ag::Value) -> ::core::primitive::bool {
            match __ingraph_value {
              #ag::Value::String(__ingraph_text) => ::core::result::Result::is_ok(
                &<Self as ::core::str::FromStr>::from_str(__ingraph_text),
              ),
              _ => false,
            }
          }

          fn to_value(&self) -> #ag::Value {
            #ag::Value::String(::std::string::ToString::to_string(self))
          }
        }
      }
    };

    (declaration, rows, scalar)
  }

  /// The INHERENT face: the constructor, the two readings and the four casts.
  ///
  /// # The soundness argument for the casts, in three clauses
  ///
  /// 1. **LAYOUT.** The front end refuses a declaration that is not `#[repr(transparent)]` over
  ///    exactly one field, so `Self` and `Inner` have identical size, alignment and ABI — that is
  ///    what the representation MEANS, and it is the compiler's guarantee rather than this device's
  ///    prose.
  /// 2. **VALIDITY.** A one-field transparent wrapper has the validity invariant of the field:
  ///    every bit pattern that is a valid `Inner` is a valid `Self` and back, there being no second
  ///    field, no discriminant and no padding of the wrapper's own.
  /// 3. **NO INVARIANT AT THIS DOOR.** A `from_ref` is unsound for a wrapper whose values are a
  ///    CHECKED SUBSET of its inner's, and this door declares it has none — see the module note.
  ///
  /// The slice pair rests on those three plus one more: a `[Inner]` and a `[Self]` of one length
  /// have identical layout because their ELEMENTS do, so the fat pointer's length metadata means the
  /// same thing on both sides and crosses unchanged.
  ///
  /// # `transmute` rather than a pointer cast, which is `ingraph::name`'s measured choice
  ///
  /// `borrowed_name!` writes its own view the same way, and the reason is which of the two the
  /// compiler RECHECKS: a `*const Inner as *const Self` cast keeps compiling if either side ever
  /// stops being sized, silently dropping the metadata, where the transmute is `E0512` at that
  /// moment. It is also the only one of the two that is `const` on this crate's floor.
  fn inherent(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let inner = &self.inner;
    let vis = &self.vis;
    let new = format!(
      " The [`{subject}`] `inner` names.\n\n `const`, and it validates nothing: this door carries no \
       constructor invariant — see `#[derive(ingraph::Id)]`."
    );
    let into_inner = format!(" The value this [`{subject}`] IS, taken.");
    let as_inner = format!(" The value this [`{subject}`] IS, borrowed.");
    let from_ref = format!(
      " View `inner` as a [`{subject}`], borrowing rather than moving.\n\n Free under \
       `#[repr(transparent)]` — the two have one layout. Legal because this door carries no \
       constructor invariant to walk around."
    );
    let from_slice = format!(
      " View a slice of held values as a slice of [`{subject}`]s.\n\n The reference cast one length \
       further out: the elements have identical layout, so the slice does."
    );
    let as_inner_slice = format!(
      " View a slice of [`{subject}`]s as a slice of the values they are.\n\n An associated function \
       rather than a method, because the receiver is the SLICE and not one wrapper."
    );

    // NO `#[automatically_derived]`: the attribute is valid on a TRAIT impl and warns on an inherent
    // one, which is the rule `emit`'s conversion pair states.
    quote! {
      impl #subject {
        #[doc = #new]
        #[inline]
        #[must_use]
        #vis const fn new(__ingraph_inner: #inner) -> Self {
          Self(__ingraph_inner)
        }

        #[doc = #into_inner]
        #[inline]
        #[must_use]
        #vis fn into_inner(self) -> #inner {
          self.0
        }

        #[doc = #as_inner]
        #[inline]
        #[must_use]
        #vis const fn as_inner(&self) -> &#inner {
          &self.0
        }

        #[doc = #from_ref]
        #[inline]
        #[must_use]
        #vis const fn from_ref(__ingraph_inner: &#inner) -> &Self {
          // SAFETY: the three clauses on `IdModel::inherent` — `#[repr(transparent)]` over one
          // field (verified by the front end, which refuses every other shape), the validity
          // invariant that follows from it, and this door's declared absence of any constructor
          // invariant. Both sides are ordinary borrows of one place, and the elided lifetimes tie
          // the result to the argument, so the borrow stays the caller's.
          unsafe { ::core::mem::transmute::<&#inner, &Self>(__ingraph_inner) }
        }

        #[doc = #from_slice]
        #[inline]
        #[must_use]
        #vis const fn from_slice(__ingraph_inner: &[#inner]) -> &[Self] {
          // SAFETY: as `from_ref`, plus the element clause — a `[Inner]` and a `[Self]` of one
          // length have identical layout because the elements do, so the length metadata means the
          // same thing on both sides and crosses unchanged.
          unsafe { ::core::mem::transmute::<&[#inner], &[Self]>(__ingraph_inner) }
        }

        #[doc = #as_inner_slice]
        #[inline]
        #[must_use]
        #vis const fn as_inner_slice(__ingraph_this: &[Self]) -> &[#inner] {
          // SAFETY: `from_slice`'s note, read the other way — the claim is symmetric.
          unsafe { ::core::mem::transmute::<&[Self], &[#inner]>(__ingraph_this) }
        }
      }
    }
  }

  /// The whole device, emitted.
  ///
  /// TWO scopes, and the split is the one every emitter here draws: a name the declaring scope has
  /// to be able to WRITE goes outside — the minted reading is named by an associated type a
  /// downstream crate resolves — and everything else goes inside an anonymous `const`, which is
  /// where an emission puts what it owes the declaring scope no name for.
  ///
  /// The INHERENT face is outside too, and for the stronger version of the same reason: an inherent
  /// impl inside a `const _` block is invisible to every caller, which would make the casts a door
  /// nobody can open.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let (reading, wire, scalar) = self.wire();
    let inherent = self.inherent();
    let key = self.key_delegation();
    let identity = self.identity();
    let text = self.text();
    let storage = self.storage();
    quote! {
      #reading

      #inherent

      const _: () = {
        #key
        #identity
        #text
        #storage
        #wire
      };

      #scalar
    }
  }
}