Skip to main content

ingraph_codegen/
id.rs

1//! The ID DEVICE's model: what `#[derive(ingraph::Id)]` emits for a `#[repr(transparent)]` tuple
2//! wrapper — the whole register a product's own id type used to hand-write, from one word.
3//!
4//! ```text
5//! #[derive(ingraph::Id)]
6//! #[repr(transparent)]
7//! pub struct TrackId(uuid::Uuid);
8//! ```
9//!
10//! # Named for the TRAIT IT ADMITS, which is the `derive(Clone)` convention
11//!
12//! The word is `Id` because what the door hands out is [`Id`](../../../ingraph/trait.Id.html)
13//! membership, the same way `#[derive(Clone)]` is named for `Clone`. It is deliberately NOT the
14//! attribute spelling `#[ingraph(id)]`: that word is the RECORD's, naming which FIELD of a
15//! declaration is its address, and one word meaning two things across two devices is a vocabulary a
16//! reader has to disambiguate by position.
17//!
18//! # THE ROSTER IS A MEASUREMENT, and the measurement is two live registers
19//!
20//! Everything below was hand-written — twice, independently, to the impl — by `findit`'s `MediaId`
21//! and `mediagraph`'s `VolumeId`, each a `pub struct X(uuid::Uuid)`. This device emits that register
22//! and nothing beside it, so the door's content is a census rather than a wish list:
23//!
24//! | face | mechanism |
25//! |---|---|
26//! | `DelegatesId` | the transparency assertion — key admission |
27//! | `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash` | delegated to the inner |
28//! | `Display`, `FromStr` | delegated to the inner |
29//! | `From<Inner>`, `From<Self> for Inner`, `From<Self> for String` | the conversions, and the SQL comparison's crossing |
30//! | `CursorValue` | delegated to the inner |
31//! | `ColumnKind` | one column, the default |
32//! | `IdColumn<Db>` | the storage seam, delegating — UNGATED, see below |
33//! | `StoredAs<Db>` | the seam's word, UNGATED — see below |
34//! | `Carrier<Db>`, `Assemble<'_, R>` | the seam's bind and read back, gated — see below |
35//! | `ToGraphqlInput`, `ToGraphqlOutput` | the identity crossing and the borrow |
36//! | `ScalarWire`, `CompositeFilterMarker`, `DefaultMarker` | the filter reading, over a minted `<Name>Wire` |
37//! | `async_graphql::ScalarType` | the scalar itself, wide in and strict out |
38//! | the CASTS | `from_ref`, `as_inner`, `from_slice`, `as_inner_slice` |
39//!
40//! # THE STORAGE SEAM, and the census that closed the road it replaced
41//!
42//! The three storage rows delegate to the inner THROUGH
43//! [`IdColumn<Db>`](../../../ingraph/trait.IdColumn.html) — the framework trait that answers *how
44//! does an id wrapping me reach a column?* per member, per dialect. That trait's own note carries the
45//! ruling, the per-member roads and the completeness audit; what belongs here is why this device
46//! reads a trait rather than the inner directly or a word at the declaration.
47//!
48//! **What the road used to be, and why.** `ingraph` shipped a bare [`uuid::Uuid`] exactly four rows —
49//! `Id` membership, the filesystem segment, the column-language row and `CursorValue` — no
50//! `ColumnKind`, no `StoredAs<Db>`, no `Carrier<Db>`, no `Assemble`; and `sqlx`'s own `uuid` feature
51//! was off everywhere in the graph. A row spelled `where Inner: Carrier<Db>` was therefore
52//! unsatisfiable at the one declaration this device exists for, so both live registers bound on
53//! `String` and bound the CANONICAL TEXT, and this device emitted what they wrote.
54//!
55//! **The 2026-08-29 uuid knife filled every one of those rows** — each backend storing a uuid in its
56//! own native form — which removed the bound blocker and left a COVERAGE one. Measured against the
57//! sealed set on SQLite (ingraph #452), twelve members had no `ColumnKind`/`StoredAs`/`Carrier`/
58//! `Assemble` at all — `i128`, `u64`, `u128`, the six `core::net` address types,
59//! `smol_str::SmolStr`, `bson::Uuid` and `bson::oid::ObjectId` — so re-bounding the rows on `#inner`
60//! would have turned each of those from *stored as text* into *not storable*, through a VACUOUS impl
61//! rather than a named refusal.
62//!
63//! **`IdColumn<Db>` is what closes both at once**, and it is #452's 呈裁 1 resolved as a seam rather
64//! than as a word: every member of the sealed vocabulary has a row, so nothing is un-stored, and each
65//! row names the form that member actually stores in, so a uuid inherits its native sixteen bytes.
66//! The twelve are on the text road their `Display`/`FromStr` already gave them; the one member that
67//! MOVED is [`uuid::Uuid`].
68//!
69//! ## Why the seam is a trait and not an attribute
70//!
71//! **A MACRO SEES TOKENS.** `type MyId = uuid::Uuid` reaches this device as the word `MyId`, and no
72//! front-end pass can tell what it names — the same floor [`inner_is_string`](IdModel::inner_is_string)
73//! is documented at, where the failure mode is a legible `E0119`. A uuid branch decided on tokens
74//! would fail as a SILENT DIVERGENCE IN STORED FORM instead, which is the one failure a storage
75//! decision must not have. So per-inner dispatch has to be resolved by the type system.
76//!
77//! An attribute at the declaration was the other candidate and is refused for three reasons rather
78//! than one: it re-adds ceremony against the zero-ceremony ruling this door was opened under, it
79//! restates a TYPE-LEVEL fact once per declaration where the type already knows it, and a declaration
80//! that names the wrong road gets an `E0277` naming nothing a reader can act on. An optional override
81//! word MAY come later as sugar OVER the seam; it is not here.
82//!
83//! ## What the switch changed, stated rather than left to be discovered
84//!
85//! A wrapper over a [`uuid::Uuid`] declares, binds and reads back the NATIVE form — PostgreSQL
86//! `uuid`, MySQL `binary(16)`, SQLite `BLOB` — where it used to spend the canonical 36-character
87//! text. Nothing in this workspace is published, so there is no migration ceremony: a declarer
88//! re-emits its schema on the next sync. A wrapper over any other member stores exactly what it
89//! stored before.
90//!
91//! `StoredAs<Db>` carries NO FURTHER GATE, as it did not before — the trait puts no
92//! `Db: sqlx::Database` bound on itself, so there is nothing here for a family gate to guard — and
93//! neither does the wrapper's own `IdColumn<Db>` row, which is the seam read one layer out so that an
94//! id over an id stores.
95//!
96//! # THE ONE OBLIGATION ON WHAT IS WRAPPED: a canonical text form
97//!
98//! The obligation SURVIVED the seam and it survived unchanged, because what asks for it was never
99//! the storage rows alone: an id must implement [`Display`](core::fmt::Display) and
100//! [`FromStr`](core::str::FromStr). The delegating text pair spends both, the SQL crossing spends
101//! the first, and the GraphQL scalar — wide in through the door, canonical out — spends both again,
102//! so an inner type with neither is one this device has nothing to write the register with.
103//!
104//! What the seam moved is which row ASKS. The storage rows used to carry `Inner: Display` and
105//! `Inner: FromStr` because they crossed through text themselves; they now carry
106//! `Inner: IdColumn<Db>`, and the text obligation rides the seam's own text-road impls where it is a
107//! fact about a concrete member rather than a predicate on a declaration. The refusals a declaration
108//! gets are unchanged, which is asserted rather than assumed —
109//! `key_admission/derive/an_id_wrapper_with_no_text_form` is the golden.
110//!
111//! That is a REAL boundary and not a formality. `[u8; N]` is a measured member of the id vocabulary
112//! and has neither face, so `#[derive(ingraph::Id)] #[repr(transparent)] struct Sha256([u8; 32])` is
113//! refused — at the declaration, naming the two missing faces, because the obligations ride the
114//! rows' own `where` clauses. `smol_bytes::Utf8Bytes` has `Display` and no `FromStr`, and is refused
115//! for the half it is missing. A digest and a text carrier are perfectly good keys; what they are not
116//! is text-shaped VALUES, and the road for them is the one they always had —
117//! `unsafe impl ingraph::DelegatesId`, which asks for no text at all.
118//!
119//! The obligation is stated rather than checked at the front end, deliberately. A macro sees TOKENS:
120//! `type Inner = MyAlias` reaches this device as the word `MyAlias`, so a front-end test of *does it
121//! render* would be a guess about a name. A `where` predicate is the compiler's own answer, at the
122//! declaration, naming the type and the trait.
123//!
124//! # WHY THE IDENTITY KIT IS EMITTED AND NOT LEFT TO `#[derive(…)]`
125//!
126//! [`DelegatesId`](../../../ingraph/trait.DelegatesId.html)'s safety contract has a clause a shape
127//! check cannot close: *two `Self`s are equal exactly when their delegates are*. The shape law
128//! closes the other two — no second field, no tag, no width — but a hand-written `PartialEq` that
129//! ignored a case would falsify the assertion this device makes on the declaration's behalf, and
130//! what that buys is two distinct keys resolving one stored row rather than a compile error.
131//!
132//! So the door writes the identity kit itself, delegating, and the obligation closes STRUCTURALLY:
133//! there is no `PartialEq` on this type that is not the inner's own, because the one that exists is
134//! emitted here and a second is `E0119`.
135//!
136//! `Ord` and `PartialOrd` are NOT among them, and the absence is MEASURED rather than economical. No
137//! id duty reads either — the stored order is the backend's reading of the value, and the filesystem
138//! segment is `store::fs`'s `Render`, which the delegation row routes to the inner — and
139//! `ingraph/tests/aggregate_group_newtype_probe.rs` stands a deliberately `Ord`-refusing wrapper at a
140//! live group-key position to prove it. A door that minted an order would be inventing one for a type
141//! whose author refused it. `Copy` is absent for the opposite reason: `#[derive(Copy)]` beside this
142//! word resolves against the `Clone` emitted here, and a `Copy` row bounded on the inner would refuse
143//! every text-carried id outright.
144//!
145//! # THE CASTS, and the door that has no invariant to break
146//!
147//! `from_ref` views a `&Inner` as a `&Self`, which is sound because the type is
148//! `#[repr(transparent)]` over exactly one field — the front end refuses every other shape — and
149//! unsound the moment a wrapper carries a CONSTRUCTOR INVARIANT its inner does not. This door
150//! declares it has none: an id is an address, the whole of its content is the value it holds, and a
151//! type whose values are a checked subset of its inner's belongs at
152//! `#[derive(ingraph::NewType)]`'s `scalar(check = "…")` door, where every read is spent on the
153//! check.
154
155use quote::{format_ident, quote};
156use syn::ext::IdentExt as _;
157
158#[cfg(test)]
159mod tests;
160
161/// A declared ID WRAPPER, as the device reads it.
162///
163/// PLAIN, for [`Kits`](crate::newtype::Kits)' reason — public fields, no constructor, no validation.
164/// What is checked is checked at the FRONT END, where the tokens an author wrote are still in hand
165/// and a refusal can point at one.
166pub struct IdModel {
167  /// The declaration's own visibility, which the minted reading and the casts take: a door minted
168  /// for a type nobody outside the module can name has no business being wider than the type.
169  pub vis: syn::Visibility,
170  /// The wrapper the faces are OF.
171  pub subject: syn::Ident,
172  /// The `ingraph` root the expansion spells its shelf through.
173  pub krate: syn::Path,
174  /// The ONE type this wrapper holds, at position zero.
175  pub inner: syn::Type,
176}
177
178impl IdModel {
179  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
180  /// them.
181  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
182    crate::emit::framework(&self.krate, module, name)
183  }
184
185  /// A whole VENDORED crate on that shelf, as the string an attribute's `crate = …` takes.
186  fn vendored(&self, name: &str) -> String {
187    crate::emit::vendored(&self.krate, name)
188  }
189
190  /// The reading this device mints for the filter face — `<Name>Wire`, the shape both live registers
191  /// wrote by hand.
192  #[must_use]
193  pub fn reading_name(&self) -> syn::Ident {
194    format_ident!("{}Wire", self.subject)
195  }
196
197  /// The name a SCHEMA writes: the Rust one, unraw'd.
198  ///
199  /// No rename knob, where `#[derive(ingraph::NewType)]` has one. A newtype publishes a VALUE and may
200  /// well want the schema to call it something else; an id publishes an ADDRESS, and the type's own
201  /// name is the only thing a client can correlate it with — both live registers spell
202  /// `#[Scalar(name = "<the type>")]` and neither reached for anything else.
203  fn sdl(&self) -> String {
204    self.subject.unraw().to_string()
205  }
206
207  /// The predicate `Inner: <trait>` — the OBLIGATION every delegation carries.
208  ///
209  /// Over the INNER TYPE, which is [`NewTypeModel::owes`](crate::newtype)'s choice for the same
210  /// reason: a transparent wrapper answers a face exactly when the value it holds does, so the
211  /// refusal for a missing one is `E0277` naming that type and that trait AT THE DECLARATION rather
212  /// than a method-not-found inside an expansion.
213  ///
214  /// It also SCREENS the door. A predicate over a concrete inner is a trivial bound and rustc
215  /// refuses an unsatisfied one at the impl, so `#[derive(ingraph::Id)] struct Ratio(f64)` is
216  /// `E0277` naming `f64: Eq` where it is written. An address whose value cannot answer identity is
217  /// not an address, and this is where that is said.
218  fn owes(&self, bound: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
219    let inner = &self.inner;
220    quote!(#inner: #bound)
221  }
222
223  /// The KEY ROW — the sealed vocabulary's third admission law, written by the device instead of by
224  /// hand.
225  fn key_delegation(&self) -> proc_macro2::TokenStream {
226    let subject = &self.subject;
227    let inner = &self.inner;
228    let delegates = self.framework(&["id"], "DelegatesId");
229    quote! {
230      // SAFETY: the front end refuses every shape but a `#[repr(transparent)]` tuple struct holding
231      // exactly one field, so there is no second field, no tag and no width of this type's own; this
232      // row hands that one field back by reference and does nothing else, so it is pure and answers
233      // the same inner every time; and the identity kit this device emits beside it is the inner's
234      // own, so two values are equal exactly when their delegates are. Every clause of the
235      // transparency contract is closed by construction rather than asserted by a reader.
236      #[automatically_derived]
237      unsafe impl #delegates for #subject {
238        type Inner = #inner;
239
240        #[inline]
241        fn delegate(&self) -> &#inner {
242          &self.0
243        }
244      }
245    }
246  }
247
248  /// The IDENTITY KIT — five rows, each the inner's own answer under this type's name.
249  ///
250  /// Fully qualified throughout, on the emission law [`newtype`](crate::newtype)'s module note
251  /// states: `<Inner as Trait>::method(&self.0, …)` pins method resolution, so an inner type growing
252  /// an inherent `eq` or `hash` cannot silently take the call away from the trait the row is
253  /// implementing.
254  fn identity(&self) -> proc_macro2::TokenStream {
255    let subject = &self.subject;
256    let inner = &self.inner;
257    let name = subject.to_string();
258    let debug = self.owes(quote!(::core::fmt::Debug));
259    let clone = self.owes(quote!(::core::clone::Clone));
260    let partial_eq = self.owes(quote!(::core::cmp::PartialEq));
261    let eq = self.owes(quote!(::core::cmp::Eq));
262    let hash = self.owes(quote!(::core::hash::Hash));
263
264    quote! {
265      #[automatically_derived]
266      impl ::core::fmt::Debug for #subject where #debug {
267        #[inline]
268        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
269          // The held value under this type's own name — `TypedId`'s hand-written row, for its
270          // reason: what the wrapper adds is a NAME, and a reader has already been shown it.
271          let mut __ingraph_tuple = ::core::fmt::Formatter::debug_tuple(__ingraph_f, #name);
272          ::core::fmt::DebugTuple::field(&mut __ingraph_tuple, &self.0);
273          ::core::fmt::DebugTuple::finish(&mut __ingraph_tuple)
274        }
275      }
276
277      #[automatically_derived]
278      impl ::core::clone::Clone for #subject where #clone {
279        #[inline]
280        fn clone(&self) -> Self {
281          Self(<#inner as ::core::clone::Clone>::clone(&self.0))
282        }
283      }
284
285      #[automatically_derived]
286      impl ::core::cmp::PartialEq for #subject where #partial_eq {
287        #[inline]
288        fn eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
289          <#inner as ::core::cmp::PartialEq>::eq(&self.0, &__ingraph_other.0)
290        }
291      }
292
293      #[automatically_derived]
294      impl ::core::cmp::Eq for #subject where #eq {}
295
296      #[automatically_derived]
297      impl ::core::hash::Hash for #subject where #hash {
298        #[inline]
299        fn hash<__IngraphHasher>(&self, __ingraph_state: &mut __IngraphHasher)
300        where
301          __IngraphHasher: ::core::hash::Hasher,
302        {
303          <#inner as ::core::hash::Hash>::hash(&self.0, __ingraph_state);
304        }
305      }
306    }
307  }
308
309  /// The TEXT PAIR and the three conversions.
310  ///
311  /// [`Display`](core::fmt::Display) and [`FromStr`](core::str::FromStr) are the door every storage
312  /// and wire row below spends: the bind renders through one, the decode and the scalar's `parse`
313  /// read through the other. Both delegate, so the canonical spelling is the inner type's own and
314  /// this device invents no grammar.
315  ///
316  /// `FromStr::Err` is the INNER's refusal rather than a minted wrapper. Both live registers minted
317  /// one — `ParseMediaIdError`, `ParseVolumeIdError`, each a newtype over `uuid::Error` — and what
318  /// the mint buys is a name in the declaring crate's own error vocabulary, which is a choice about
319  /// that crate rather than a fact about the wrapper. Delegating is the smaller claim and the one a
320  /// device can make truthfully: the spellings this type admits are exactly the inner's, so the
321  /// refusal for a spelling it does not admit is exactly the inner's too.
322  ///
323  /// `From<Self> for String` is the SQL comparison's crossing INTO A DECLARED TEXT COLUMN and not a
324  /// convenience: it is what gives `String: TryFrom<Self>` through std's blanket, which
325  /// `SqlScalarComparison<String, Db>` asks for. It is no longer what this device's own storage rows
326  /// spend — those go through [`IdColumn`](../../../ingraph/trait.IdColumn.html), and a field whose
327  /// storage type IS its own resolves the crossing reflexively — so what the row serves now is a
328  /// declaration that says `<db>(type = "String")` over an id. It cannot fail, the rendering being
329  /// this type's own `Display`.
330  fn text(&self) -> proc_macro2::TokenStream {
331    let subject = &self.subject;
332    let inner = &self.inner;
333    let display = self.owes(quote!(::core::fmt::Display));
334    let from_str = self.owes(quote!(::core::str::FromStr));
335
336    // The SQL crossing, WITHHELD where it would be the row above spelled twice. A wrapper over a
337    // `String` already gets `From<Self> for String` as its inner conversion, and emitting the
338    // crossing beside it is `E0119` on one impl written by one device — the worst kind, since a
339    // declarer cannot edit either half.
340    //
341    // A TOKEN comparison, because a macro sees tokens: `type Text = String` reaches here as the word
342    // `Text` and nothing can tell this pass otherwise. So the check catches the spellings a
343    // declaration actually writes and an ALIAS still collides — with `E0119` naming two impls of
344    // `From<…> for String`, which is at least a refusal that says what it is. It is the same floor
345    // every macro reads a type name at.
346    let crossing = if self.inner_is_string() {
347      quote!()
348    } else {
349      quote! {
350        #[automatically_derived]
351        impl ::core::convert::From<#subject> for ::std::string::String where #display {
352          #[inline]
353          fn from(__ingraph_id: #subject) -> Self {
354            ::std::string::ToString::to_string(&__ingraph_id)
355          }
356        }
357      }
358    };
359
360    quote! {
361      #[automatically_derived]
362      impl ::core::fmt::Display for #subject where #display {
363        #[inline]
364        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
365          <#inner as ::core::fmt::Display>::fmt(&self.0, __ingraph_f)
366        }
367      }
368
369      #[automatically_derived]
370      impl ::core::str::FromStr for #subject where #from_str {
371        type Err = <#inner as ::core::str::FromStr>::Err;
372
373        #[inline]
374        fn from_str(__ingraph_text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
375          ::core::result::Result::map(
376            <#inner as ::core::str::FromStr>::from_str(__ingraph_text),
377            Self,
378          )
379        }
380      }
381
382      #[automatically_derived]
383      impl ::core::convert::From<#inner> for #subject {
384        #[inline]
385        fn from(__ingraph_inner: #inner) -> Self {
386          Self(__ingraph_inner)
387        }
388      }
389
390      #[automatically_derived]
391      impl ::core::convert::From<#subject> for #inner {
392        #[inline]
393        fn from(__ingraph_id: #subject) -> Self {
394          __ingraph_id.0
395        }
396      }
397
398      #crossing
399    }
400  }
401
402  /// Whether the wrapped type is `String` AS THIS DECLARATION SPELLS IT.
403  ///
404  /// The four spellings a declaration writes, and no more — see [`text`](Self::text) for why a token
405  /// comparison is the floor here rather than a shortcut.
406  fn inner_is_string(&self) -> bool {
407    const SPELLINGS: [&str; 4] = [
408      "String",
409      "std :: string :: String",
410      ":: std :: string :: String",
411      "alloc :: string :: String",
412    ];
413    let written = quote::ToTokens::to_token_stream(&self.inner).to_string();
414    SPELLINGS.contains(&written.as_str())
415  }
416
417  /// The PAGE and STORAGE rows.
418  ///
419  /// [`CursorValue`] delegates to the inner, which was the ONE value-column face `ingraph` shipped a
420  /// bare `uuid::Uuid` when this device landed — both live registers delegated here and hand-wrote
421  /// everything else, and that asymmetry was the whole shape of the original census. A uuid now has
422  /// all of them, and this row is unchanged by that: delegating to the inner is what it always did.
423  ///
424  /// [`ColumnKind`] is the default: one column. It is ungated, as the trait is — a width names no
425  /// database.
426  ///
427  /// # The three storage rows go through `IdColumn<Db>` AT THE INNER
428  ///
429  /// `StoredAs<Db>`, `Carrier<Db>` and `Assemble` are all written over ONE projection —
430  /// `<Inner as IdColumn<Db>>::Stored` — so the word a `CREATE TABLE` declares, the value the bind
431  /// pushes and the value the decode reads back are one decision made in one place. The seam's own
432  /// note has the ruling and the census; what belongs here is the shape it takes at the emission:
433  ///
434  /// * the row a member takes is the INNER's, so `TrackId(Uuid)` inherits the native sixteen bytes
435  ///   and `SomethingId(SmolStr)` keeps the canonical text, with no word at either declaration;
436  /// * the obligation is `Inner: IdColumn<Db>` and no longer `Display`/`FromStr`. Those two are
437  ///   still owed — the text pair, the crossing and the scalar spend them — so the door's one
438  ///   requirement on what is wrapped is unchanged; what moved is which row asks;
439  /// * the crossing's refusal is the seam's `Refusal`, whose `Error + Send + Sync + 'static` bound
440  ///   the trait carries, so this emission states none of it.
441  ///
442  /// It also emits the wrapper's OWN `IdColumn<Db>` row, delegating to what it holds. That is the
443  /// seam read one layer out: an id over an id stores, resolving to whichever member the chain
444  /// grounds in, exactly as [`DelegatesId`] admits one duty over.
445  ///
446  /// # The one place the door NARROWED, recorded rather than left to be met
447  ///
448  /// An inner this crate has never seen used to reach the storage rows on `Display` + `FromStr`
449  /// alone, since that is what the text road spent. It now needs an `IdColumn<Db>` row of its own —
450  /// one impl, three lines, named at the refusal by that trait's `on_unimplemented` — and the
451  /// trade is that a downstream inner now SAYS what it is stored as instead of being assumed to be
452  /// text.
453  ///
454  /// The row this device emits is what keeps the framework's own compositions free: a wrapper over
455  /// another `#[derive(ingraph::Id)]` wrapper needs nothing, through the delegating row this
456  /// `storage` emits below. A wrapper over a `#[derive(ingraph::NewType)]` value needs the impl
457  /// too, and — as of the 信己 ruling — that device now emits it unconditionally, the same posture
458  /// this one already takes: `newtype::NewTypeModel::id_column_delegation` is the mirror, written
459  /// beside that device's own `key_delegation` for `DelegatesId`'s reason. An id over a newtype
460  /// therefore needs nothing either, closing the one gap this note used to name.
461  ///
462  /// The two GATED SQL rows ride the FAMILY gate rather than a dialect's, and they are generic over
463  /// the database exactly as both registers wrote them: what varies per dialect is the stored form's
464  /// own row, and stating the obligation as `Stored: Carrier<Db>` is what lets ONE impl serve every
465  /// dialect this build has.
466  fn storage(&self) -> proc_macro2::TokenStream {
467    let subject = &self.subject;
468    let inner = &self.inner;
469    let cursor_value = self.framework(&["cursor"], "CursorValue");
470    let column_kind = self.framework(&["column"], "ColumnKind");
471    let column_eq = self.framework(&["column"], "ColumnEq");
472    let owed_eq = self.owes(quote!(#column_eq));
473    let order_leaves = self.framework(&["column"], "DeclaredLeaves");
474    let stored_as = self.framework(&["column"], "StoredAs");
475    let assemble = self.framework(&["column"], "Assemble");
476    let id_column = self.framework(&["id"], "IdColumn");
477    let carrier = self.framework(&["comparison", "sql"], "Carrier");
478    let path = self.framework(&["comparison"], "Path");
479    let gate = self.framework(&["gate"], "if_sqlx");
480    let database = self.framework(&["sqlx"], "Database");
481    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
482    let result = self.framework(&["sqlx"], "Result");
483    let sqlx_error = self.framework(&["sqlx"], "Error");
484    let row = self.framework(&["sqlx"], "Row");
485    let cursor = self.owes(quote!(#cursor_value));
486    // The seam AT THE INNER, spelled once per position it is read at. `Db` is the emitted parameter
487    // for the rows that carry one; `Row::Database` is what the decode has instead, the read half
488    // being parameterised by the ROW rather than by the dialect.
489    let seam = quote!(#id_column<__IngraphDb>);
490    let stored = quote!(<#inner as #seam>::Stored);
491    let row_seam = quote!(#id_column<<__IngraphRow as #row>::Database>);
492    let row_stored = quote!(<#inner as #row_seam>::Stored);
493
494    quote! {
495      #[automatically_derived]
496      impl #cursor_value for #subject where #cursor {
497        #[inline]
498        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
499          <#inner as #cursor_value>::write_cursor(&self.0, __ingraph_out)
500        }
501
502        #[inline]
503        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
504          ::core::option::Option::map(
505            <#inner as #cursor_value>::read_cursor(__ingraph_bytes),
506            Self,
507          )
508        }
509      }
510
511      #[automatically_derived]
512      impl #column_kind for #subject {}
513
514      // **THE SAMENESS ROW**, delegated to the inner exactly as the `PartialEq` in `identity` is —
515      // one more line on that face table reading *delegated to the inner*, and the one an emitted
516      // row now folds where it used to derive `PartialEq` over its field types. It owes the INNER's
517      // `ColumnEq` rather than a `PartialEq`, so a key over a type whose sameness is not `==` is a
518      // key this device writes with no special case.
519      #[automatically_derived]
520      impl #column_eq for #subject where #owed_eq {
521        #[inline]
522        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
523          <#inner as #column_eq>::column_eq(&self.0, &__ingraph_other.0)
524        }
525      }
526
527      // **ONE LEAF, AND IT IS THE VALUE** — the word that lets a cursor slot over this type be
528      // spelled the one way every column is spelled. It states no `ColumnKind::ORDER`, so no term
529      // over it ever expands and nothing ever asks it for a leaf narrower than itself; what the word
530      // buys is that `<<T as DefaultMarker>::Marker as ToOrderLeaves>::Leaf` RESOLVES for it, which
531      // is what keeps the emitted cursor free of a scalar/composite branch a macro cannot make.
532      //
533      // NO BOUNDS, deliberately: the `Clone` a boundary costs rides the blanket this word is the key
534      // to, so it is asked for at the first page that holds one rather than at every declaration.
535      #[automatically_derived]
536      impl #order_leaves for #subject {}
537
538      // THE SEAM, READ ONE LAYER OUT: this wrapper is stored exactly as the value it holds is, so an
539      // id wrapping THIS id stores too — the chain resolving to whichever vocabulary member it
540      // grounds in. Ungated, as the trait is, and it costs a declaration nothing.
541      #[automatically_derived]
542      impl<__IngraphDb> #seam for #subject
543      where
544        #inner: #seam,
545      {
546        type Stored = #stored;
547        type Refusal = <#inner as #seam>::Refusal;
548
549        #[inline]
550        fn to_stored(&self) -> Self::Stored {
551          <#inner as #seam>::to_stored(&self.0)
552        }
553
554        #[inline]
555        fn from_stored(
556          __ingraph_stored: Self::Stored,
557        ) -> ::core::result::Result<Self, Self::Refusal> {
558          ::core::result::Result::map(<#inner as #seam>::from_stored(__ingraph_stored), Self)
559        }
560      }
561
562      // The FOURTH face, beside the width above: what a `CREATE TABLE` declares this column as. It
563      // rides no gate — `StoredAs<Db>` names no `sqlx::Database` bound, so nothing here depends on
564      // the SQL family being compiled in — and it reads the word off the INNER's stored form rather
565      // than restating one, which is what keeps the declaration and the bind below the same decision.
566      #[automatically_derived]
567      impl<__IngraphDb> #stored_as<__IngraphDb> for #subject
568      where
569        #inner: #seam,
570        #stored: #stored_as<__IngraphDb>,
571      {
572        const WORDS: &'static [&'static ::core::primitive::str] =
573          <#stored as #stored_as<__IngraphDb>>::WORDS;
574      }
575
576      #gate! {
577        // The bind is the OWNED stored form, which is what `push_bind` takes: the value is moved
578        // into the builder's argument buffer, so nothing borrowed from `&self` can be handed over.
579        #[automatically_derived]
580        impl<__IngraphDb> #carrier<__IngraphDb> for #subject
581        where
582          __IngraphDb: #database,
583          #inner: #seam,
584          #stored: #carrier<__IngraphDb>,
585        {
586          #[inline]
587          fn push_bind(&self, __ingraph_qb: &mut #query_builder<__IngraphDb>) {
588            <#stored as #carrier<__IngraphDb>>::push_bind(
589              &<#inner as #seam>::to_stored(&self.0),
590              __ingraph_qb,
591            );
592          }
593        }
594
595        // The decode: one column back through the seam's own door, which CANONICALISES wherever the
596        // road parses — a column holding a spelling the inner type folds still reads back the same
597        // identity — and is the identity wherever the stored form IS the value.
598        #[automatically_derived]
599        impl<'__ingraph, __IngraphRow> #assemble<'__ingraph, __IngraphRow> for #subject
600        where
601          __IngraphRow: #row,
602          #inner: #row_seam,
603          #row_stored: #assemble<'__ingraph, __IngraphRow>,
604        {
605          fn assemble(
606            __ingraph_row: &'__ingraph __IngraphRow,
607            __ingraph_under: ::core::option::Option<&#path<'_>>,
608          ) -> #result<Self> {
609            let __ingraph_stored = <#row_stored as #assemble<'__ingraph, __IngraphRow>>::assemble(
610              __ingraph_row,
611              __ingraph_under,
612            )?;
613            ::core::result::Result::map(
614              ::core::result::Result::map_err(
615                <#inner as #row_seam>::from_stored(__ingraph_stored),
616                |__ingraph_refused| {
617                  #sqlx_error::Decode(::std::boxed::Box::new(__ingraph_refused))
618                },
619              ),
620              Self,
621            )
622          }
623        }
624      }
625    }
626  }
627
628  /// The WIRE rows — the crossings, the minted reading, the two markers and the scalar itself.
629  ///
630  /// The crossings are the IDENTITY: a type that publishes a scalar of its own crosses as itself, so
631  /// `cross` is `Ok` and `carry` is a clone. That is not a delegation missed — it is what *this type
632  /// IS its own GraphQL scalar* means, and both live registers wrote exactly these bodies.
633  ///
634  /// `<Name>Wire` is an uninhabited enum, minted OUTSIDE the anonymous const because
635  /// [`CompositeFilterMarker`] names it in an associated type a downstream resolves — a reading is a
636  /// name the declaring scope has to be able to write.
637  fn wire(
638    &self,
639  ) -> (
640    proc_macro2::TokenStream,
641    proc_macro2::TokenStream,
642    proc_macro2::TokenStream,
643  ) {
644    let subject = &self.subject;
645    let inner = &self.inner;
646    let vis = &self.vis;
647    let reading = self.reading_name();
648    let filter_name = format!("{}Filter", self.sdl());
649    let ag = self.framework(&[], "async_graphql");
650    let gate = self.framework(&["gate"], "if_async_graphql");
651    let shelf = self.vendored("async_graphql");
652    let sdl = self.sdl();
653    let input = self.framework(&["graphql"], "ToGraphqlInput");
654    let output = self.framework(&["graphql"], "ToGraphqlOutput");
655    let scalar_wire = self.framework(&["graphql"], "ScalarWire");
656    let scalar_filter = self.framework(&["graphql"], "ScalarFilter");
657    let composite_filter_marker = self.framework(&["marker"], "CompositeFilterMarker");
658    let composite_marker = self.framework(&["marker"], "CompositeMarker");
659    let default_marker = self.framework(&["marker"], "DefaultMarker");
660    let clone = self.owes(quote!(::core::clone::Clone));
661    let display = self.owes(quote!(::core::fmt::Display));
662    let from_str = self.owes(quote!(::core::str::FromStr));
663
664    let doc = format!(
665      " How a [`{subject}`] crosses when the framework's own ordering filter holds it — the reading \
666       that gives `ScalarFilter<{subject}, {reading}>` a face.\n\n Uninhabited: it is a NAME the \
667       filter is parameterised by and never a value anything builds."
668    );
669
670    let declaration = quote! {
671      #[doc = #doc]
672      #vis enum #reading {}
673    };
674
675    let rows = quote! {
676      #[automatically_derived]
677      impl #input for #subject where #clone {
678        type Input = Self;
679        type Error = ::core::convert::Infallible;
680
681        #[inline]
682        fn cross(__ingraph_input: Self::Input) -> ::core::result::Result<Self, Self::Error> {
683          ::core::result::Result::Ok(__ingraph_input)
684        }
685
686        #[inline]
687        fn carry(__ingraph_operand: &Self) -> Self::Input {
688          ::core::clone::Clone::clone(__ingraph_operand)
689        }
690      }
691
692      #[automatically_derived]
693      impl #output for #subject {
694        type Output<'__ingraph>
695          = &'__ingraph Self
696        where
697          Self: '__ingraph;
698
699        #[inline]
700        fn to_graphql_output(__ingraph_value: &Self) -> &Self {
701          __ingraph_value
702        }
703      }
704
705      #[automatically_derived]
706      impl #scalar_wire<#subject> for #reading where #clone {
707        const NAME: &'static ::core::primitive::str = #filter_name;
708
709        type Carrier = #subject;
710        type Error = ::core::convert::Infallible;
711
712        #[inline]
713        fn cross(
714          __ingraph_carrier: Self::Carrier,
715        ) -> ::core::result::Result<#subject, Self::Error> {
716          ::core::result::Result::Ok(__ingraph_carrier)
717        }
718
719        #[inline]
720        fn carry(__ingraph_operand: &#subject) -> Self::Carrier {
721          ::core::clone::Clone::clone(__ingraph_operand)
722        }
723      }
724
725      // The same predicate at both host kinds: an id occupies one column and the whole of it is
726      // stored, so there is no rowless/row-holding difference for the two seats to record.
727      #[automatically_derived]
728      impl #composite_filter_marker for #subject {
729        type Filter = #scalar_filter<#subject, #reading>;
730        type ColumnFilter = #scalar_filter<#subject, #reading>;
731      }
732
733      // The interpretation a field of this type is read under: the framework's COMPOSITE reading,
734      // one value occupying a column of its own.
735      #[automatically_derived]
736      impl #default_marker for #subject {
737        type Marker = #composite_marker<#subject>;
738      }
739    };
740
741    // OUTSIDE the anonymous const, which is where `#[derive(ingraph::NewType)]` puts its own: the
742    // `#[Scalar]` attribute is a vendored macro over the impl it decorates, and an emission does not
743    // put another crate's expansion somewhere that crate never agreed to be.
744    let scalar = quote! {
745      #gate! {
746        // WIDE IN, STRICT OUT. The door is this type's own `FromStr`, so what spellings are admitted
747        // is the inner type's business and there is no second grammar here to keep in step; what
748        // this layer adds is the JSON SHAPE, and the refusal a client gets for anything else. The
749        // rendering is `Display`'s, which is the one spelling this type writes back.
750        #[#ag::Scalar(crate = #shelf, name = #sdl)]
751        impl #ag::ScalarType for #subject
752        where
753          #display,
754          #from_str,
755          <#inner as ::core::str::FromStr>::Err: ::core::fmt::Display,
756        {
757          fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
758            match &__ingraph_value {
759              #ag::Value::String(__ingraph_text) => ::core::result::Result::map_err(
760                <Self as ::core::str::FromStr>::from_str(__ingraph_text),
761                #ag::InputValueError::custom,
762              ),
763              _ => ::core::result::Result::Err(#ag::InputValueError::expected_type(
764                ::core::clone::Clone::clone(&__ingraph_value),
765              )),
766            }
767          }
768
769          fn is_valid(__ingraph_value: &#ag::Value) -> ::core::primitive::bool {
770            match __ingraph_value {
771              #ag::Value::String(__ingraph_text) => ::core::result::Result::is_ok(
772                &<Self as ::core::str::FromStr>::from_str(__ingraph_text),
773              ),
774              _ => false,
775            }
776          }
777
778          fn to_value(&self) -> #ag::Value {
779            #ag::Value::String(::std::string::ToString::to_string(self))
780          }
781        }
782      }
783    };
784
785    (declaration, rows, scalar)
786  }
787
788  /// The INHERENT face: the constructor, the two readings and the four casts.
789  ///
790  /// # The soundness argument for the casts, in three clauses
791  ///
792  /// 1. **LAYOUT.** The front end refuses a declaration that is not `#[repr(transparent)]` over
793  ///    exactly one field, so `Self` and `Inner` have identical size, alignment and ABI — that is
794  ///    what the representation MEANS, and it is the compiler's guarantee rather than this device's
795  ///    prose.
796  /// 2. **VALIDITY.** A one-field transparent wrapper has the validity invariant of the field:
797  ///    every bit pattern that is a valid `Inner` is a valid `Self` and back, there being no second
798  ///    field, no discriminant and no padding of the wrapper's own.
799  /// 3. **NO INVARIANT AT THIS DOOR.** A `from_ref` is unsound for a wrapper whose values are a
800  ///    CHECKED SUBSET of its inner's, and this door declares it has none — see the module note.
801  ///
802  /// The slice pair rests on those three plus one more: a `[Inner]` and a `[Self]` of one length
803  /// have identical layout because their ELEMENTS do, so the fat pointer's length metadata means the
804  /// same thing on both sides and crosses unchanged.
805  ///
806  /// # `transmute` rather than a pointer cast, which is `ingraph::name`'s measured choice
807  ///
808  /// `borrowed_name!` writes its own view the same way, and the reason is which of the two the
809  /// compiler RECHECKS: a `*const Inner as *const Self` cast keeps compiling if either side ever
810  /// stops being sized, silently dropping the metadata, where the transmute is `E0512` at that
811  /// moment. It is also the only one of the two that is `const` on this crate's floor.
812  fn inherent(&self) -> proc_macro2::TokenStream {
813    let subject = &self.subject;
814    let inner = &self.inner;
815    let vis = &self.vis;
816    let new = format!(
817      " The [`{subject}`] `inner` names.\n\n `const`, and it validates nothing: this door carries no \
818       constructor invariant — see `#[derive(ingraph::Id)]`."
819    );
820    let into_inner = format!(" The value this [`{subject}`] IS, taken.");
821    let as_inner = format!(" The value this [`{subject}`] IS, borrowed.");
822    let from_ref = format!(
823      " View `inner` as a [`{subject}`], borrowing rather than moving.\n\n Free under \
824       `#[repr(transparent)]` — the two have one layout. Legal because this door carries no \
825       constructor invariant to walk around."
826    );
827    let from_slice = format!(
828      " View a slice of held values as a slice of [`{subject}`]s.\n\n The reference cast one length \
829       further out: the elements have identical layout, so the slice does."
830    );
831    let as_inner_slice = format!(
832      " View a slice of [`{subject}`]s as a slice of the values they are.\n\n An associated function \
833       rather than a method, because the receiver is the SLICE and not one wrapper."
834    );
835
836    // NO `#[automatically_derived]`: the attribute is valid on a TRAIT impl and warns on an inherent
837    // one, which is the rule `emit`'s conversion pair states.
838    quote! {
839      impl #subject {
840        #[doc = #new]
841        #[inline]
842        #[must_use]
843        #vis const fn new(__ingraph_inner: #inner) -> Self {
844          Self(__ingraph_inner)
845        }
846
847        #[doc = #into_inner]
848        #[inline]
849        #[must_use]
850        #vis fn into_inner(self) -> #inner {
851          self.0
852        }
853
854        #[doc = #as_inner]
855        #[inline]
856        #[must_use]
857        #vis const fn as_inner(&self) -> &#inner {
858          &self.0
859        }
860
861        #[doc = #from_ref]
862        #[inline]
863        #[must_use]
864        #vis const fn from_ref(__ingraph_inner: &#inner) -> &Self {
865          // SAFETY: the three clauses on `IdModel::inherent` — `#[repr(transparent)]` over one
866          // field (verified by the front end, which refuses every other shape), the validity
867          // invariant that follows from it, and this door's declared absence of any constructor
868          // invariant. Both sides are ordinary borrows of one place, and the elided lifetimes tie
869          // the result to the argument, so the borrow stays the caller's.
870          unsafe { ::core::mem::transmute::<&#inner, &Self>(__ingraph_inner) }
871        }
872
873        #[doc = #from_slice]
874        #[inline]
875        #[must_use]
876        #vis const fn from_slice(__ingraph_inner: &[#inner]) -> &[Self] {
877          // SAFETY: as `from_ref`, plus the element clause — a `[Inner]` and a `[Self]` of one
878          // length have identical layout because the elements do, so the length metadata means the
879          // same thing on both sides and crosses unchanged.
880          unsafe { ::core::mem::transmute::<&[#inner], &[Self]>(__ingraph_inner) }
881        }
882
883        #[doc = #as_inner_slice]
884        #[inline]
885        #[must_use]
886        #vis const fn as_inner_slice(__ingraph_this: &[Self]) -> &[#inner] {
887          // SAFETY: `from_slice`'s note, read the other way — the claim is symmetric.
888          unsafe { ::core::mem::transmute::<&[Self], &[#inner]>(__ingraph_this) }
889        }
890      }
891    }
892  }
893
894  /// The whole device, emitted.
895  ///
896  /// TWO scopes, and the split is the one every emitter here draws: a name the declaring scope has
897  /// to be able to WRITE goes outside — the minted reading is named by an associated type a
898  /// downstream crate resolves — and everything else goes inside an anonymous `const`, which is
899  /// where an emission puts what it owes the declaring scope no name for.
900  ///
901  /// The INHERENT face is outside too, and for the stronger version of the same reason: an inherent
902  /// impl inside a `const _` block is invisible to every caller, which would make the casts a door
903  /// nobody can open.
904  #[must_use]
905  pub fn emit(&self) -> proc_macro2::TokenStream {
906    let (reading, wire, scalar) = self.wire();
907    let inherent = self.inherent();
908    let key = self.key_delegation();
909    let identity = self.identity();
910    let text = self.text();
911    let storage = self.storage();
912    quote! {
913      #reading
914
915      #inherent
916
917      const _: () = {
918        #key
919        #identity
920        #text
921        #storage
922        #wire
923      };
924
925      #scalar
926    }
927  }
928}