Skip to main content

ingraph_codegen/
enumeration.rs

1//! The VOCABULARY face: what a unit-variant enum expands into.
2//!
3//! A vocabulary is not a node. It owns no storage, subscribes to nothing and carries no key — it is
4//! a VALUE a record's column holds, and the whole of what it needs is the rows that say how a column
5//! of it is read, the rows that say how one is stored, and the words its faces spell it as.
6//!
7//! # Storage is MACHINE-FACING, and the wire is not
8//!
9//! A database stores the DISCRIMINANT and a schema shows the NAME, and neither is a knob a
10//! declaration has to reach for: a column exists for a machine and a wire face exists for a person,
11//! so those are the defaults and a per-backend block is what overrides one.
12//!
13//! ```ignore
14//! #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
15//! #[repr(u8)]
16//! pub enum Grade { Low, High, Archived = 9 }
17//! ```
18//!
19//! stores `0`, `1` and `9` in every database this build compiled, shows `LOW`, `HIGH` and
20//! `ARCHIVED` on the wire, and declares none of it. The crossing is what joins the two: a filter's
21//! operand arrives as the enum, so the user's text is translated at the FILTER and never reaches an
22//! integer column as text.
23//!
24//! # The width follows `#[repr(…)]`, through the house carrier rules
25//!
26//! `#[repr(u8)]` is a `u8` column. What that means per dialect is not this module's invention: the
27//! framework's own carrier table already widens where a dialect has no such type — `u8` and `i8`
28//! bind as `SMALLINT` on Postgres, `u16` as `INT`, `u32` as `BIGINT` — and a vocabulary's rows take
29//! the same widening, which is why they are per-backend rather than one dialect-generic row.
30//!
31//! Absent a `#[repr(…)]`, the width is `i64`, and that is measured rather than picked for room. A
32//! fieldless enum with no repr hint has discriminants of type `isize`, so `Grade::High = 3_000_000_000`
33//! is a legal declaration on every 64-bit target; a narrower default would store it through an `as`
34//! cast that silently wraps, and a wrong number in somebody's database is exactly what a DEFAULT must
35//! not be able to produce. `i64` is also native on all three dialects — SQLite's `INTEGER`,
36//! Postgres's and MySQL's `BIGINT` — so the safe width costs no widening anywhere.
37//!
38//! # The set of rows, measured against what a working enum column actually needs
39//!
40//! | impl | who demands it | gated |
41//! |---|---|---|
42//! | `EnumFilterMarker` | the column's FILTER — `EnumMarker<T>` resolves through it | no |
43//! | `DefaultMarker` | the INFERENCE, so a column needs no `enum` word to be read as one | no |
44//! | `CursorValue` | the KEYSET cursor, which every persisted column is audited for | no |
45//! | `sqlx::Type` | the emitted `FromRow`, once per column | per backend |
46//! | `sqlx::Decode` | the emitted `FromRow`, once per column | per backend |
47//! | `sqlx::Encode` | the write side of the same binding — an authority names both directions | per backend |
48//! | `Carrier` | the comparison's LOWERING, which is what binds an operand into a query | per backend |
49//!
50//! The last four are the six-row template the vocabulary's first round measured, now written once
51//! per COMPILED-IN backend behind [`crate::model::DatabaseKind`]'s gate. What a gate makes an
52//! emission mean is `ingraph`'s crate note, under *The four gates*: an impl exists per declared ∩
53//! compiled-in backend, and a build without a driver has no impl rather than a deferred one.
54//!
55//! `ingraph-derive`'s `tests/enums.rs` is where the set is checked: it declares such a column and
56//! drives the whole circle through a live database, so a row that were merely plausible would fail
57//! there rather than pass a token comparison.
58//!
59//! # The FACE is hand-emitted, and it is backend-free
60//!
61//! `is_<variant>`, `VARIANTS`, `as_str`, one `as_<namespace>_str` per TEXT face, `FromStr` over the
62//! canonical namespace and one `TryFrom<&…Name>` per text face. None of it names a backend, so
63//! none of it rides a gate — what decides whether a namespace has a face is its FORM, since a
64//! backend storing a discriminant has no text for a name type to hold.
65//!
66//! No `derive_more`, and no derive of any kind: the methods are this crate's emission, so the
67//! expanded code names no foreign path and the errors are the vocabulary's own.
68//!
69//! # The REFUSAL type is the ONE name this expansion puts in the declaring scope, so it is the one
70//! that can be renamed
71//!
72//! Everything else sits inside an anonymous `const`, where it can collide with nothing anybody
73//! wrote. The refusal cannot: it is named in signatures a caller writes — `FromStr::Err`,
74//! `TryFrom::Error` — so it stands beside the enum, and a scope that already holds a
75//! `<Enum>ParseError` gets a duplicate definition at a span the declaration cannot edit.
76//! `error(rename = "…")` is the way out, and it is the ESCAPE from that collision rather than a
77//! spelling preference: the DEFAULT is unchanged, a declaration that names nothing is unaffected,
78//! and a scope with nothing in the way never has to know the knob exists.
79//!
80//! Renaming the type does NOT move the sentence it prints. The message names the VOCABULARY —
81//! *`Codec`: no variant answers to this name* — because what failed is a parse into the enum, and
82//! the type carrying the refusal is an implementation detail of how that is reported.
83//!
84//! # MongoDB is measured and stores NOTHING yet
85//!
86//! `MongoEnumComparison` exists and `MongoCarrier` is the row that would feed it, so the second
87//! backend is not blocked on a design. What is missing is a lane that can compile the row:
88//! `ingraph-derive`'s dev-dependency on `ingraph` carries no `mongo`, so a MongoDB storage row would
89//! ship with no configuration in this workspace able to build it. Its NAMESPACE is here regardless —
90//! `mongo(text)` gives a declaration `as_mongo_str` and `TryFrom<&MongoName>`, which is exactly
91//! what the hand-written `impl MongoCarrier` that trait's doc asks for is written in terms of.
92//!
93//! # The wire face rides in the SAME emission, behind the binding gate
94//!
95//! [`wire`] writes it and [`EnumModel::emit`] carries it — one organ, one word. There were two
96//! doors and the second was deleted: schema presence is REACHABILITY (an enum no wire type names
97//! never enters an SDL), so a macro was never the gatekeeper the split took it for, and what the
98//! split cost — a silent composition-order trap, two entry points onto one model — was the
99//! coexistence rather than a consequence of it.
100//!
101//! **The era rule never held that face, and the note that said so was stale.** A GraphQL face is a
102//! VENDORED trait impl rather than a framework one — `#krate::__private::async_graphql::InputType`
103//! IS `::async_graphql::InputType`, a third-party trait on a third-party release cadence — and
104//! `ingraph-codegen`'s own `framework_rooted` has exempted the vendored segment since the order door
105//! landed. What actually held it was THE WALL: a filter over a declarer's enum had no `InputType`,
106//! and the row that supplies it is `graphql::filter::r#enum`'s single generic impl.
107
108use std::collections::BTreeMap;
109
110use heck::{ToShoutySnakeCase as _, ToSnakeCase as _};
111use quote::{format_ident, quote};
112
113use crate::{
114  method::{Emitted, Origin, Owner},
115  model::{DatabaseKind, GraphqlKind},
116};
117
118mod own;
119mod remote;
120#[cfg(test)]
121mod tests;
122mod wire;
123
124/// What a face spells one variant AS.
125///
126/// The two the comparison layer already names — `SqlEnumComparison`'s own doc reads *"the type this
127/// database stores the column as — a text name or an integer discriminant, whichever the field
128/// declared"* — and no third, because a third would be a form no comparison kind can lower.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
130pub enum StorageForm {
131  /// The variant's NAME in this namespace.
132  ///
133  /// Verbatim, and never cased: a stored name is a value in somebody's database, and a mangling
134  /// rule that changed would rewrite every row. A raw identifier stores unraw'd — `r#type` is
135  /// `type` — because the `r#` is Rust's way of saying the word, not part of it. The one namespace
136  /// that does case its default is the wire, for the reason [`Namespace::Graphql`] gives.
137  Text,
138  /// The variant's DISCRIMINANT, at the declaration's own width.
139  ///
140  /// The declaration's own number — `Grade::High = 9` stores 9 — because the discriminant is a
141  /// number the declaration can already spell, and a second numbering invented here would disagree
142  /// with it.
143  Integer,
144}
145
146impl StorageForm {
147  /// Every form, in the order a refusal lists them.
148  pub const ALL: [Self; 2] = [Self::Text, Self::Integer];
149
150  /// The word a declaration writes.
151  pub const fn as_str(self) -> &'static str {
152    match self {
153      Self::Text => "text",
154      Self::Integer => "integer",
155    }
156  }
157}
158
159/// One face a vocabulary has: four databases and the wire.
160///
161/// A namespace is not merely a place a name is written — it is the TYPE the name is carried as, so
162/// that a conversion out of one cannot be handed a name from another. `ingraph`'s `name` module
163/// carries the five types and the argument for them.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
165pub enum Namespace {
166  /// SQLite's stored word.
167  Sqlite,
168  /// PostgreSQL's stored word.
169  Postgres,
170  /// MySQL's stored word.
171  Mysql,
172  /// MongoDB's stored word.
173  Mongo,
174  /// The member a GraphQL enum exposes.
175  Graphql,
176}
177
178impl Namespace {
179  /// Every namespace, in the order a refusal lists them.
180  pub const ALL: [Self; 5] = [
181    Self::Sqlite,
182    Self::Postgres,
183    Self::Mysql,
184    Self::Mongo,
185    Self::Graphql,
186  ];
187
188  /// The word a declaration writes for this namespace's block.
189  pub const fn as_str(self) -> &'static str {
190    match self {
191      Self::Sqlite => "sqlite",
192      Self::Postgres => "postgres",
193      Self::Mysql => "mysql",
194      Self::Mongo => "mongo",
195      Self::Graphql => "graphql",
196    }
197  }
198
199  /// The database this namespace belongs to, or nothing for the wire.
200  pub const fn database(self) -> Option<DatabaseKind> {
201    match self {
202      Self::Sqlite => Some(DatabaseKind::Sqlite),
203      Self::Postgres => Some(DatabaseKind::Postgres),
204      Self::Mysql => Some(DatabaseKind::Mysql),
205      Self::Mongo => Some(DatabaseKind::Mongo),
206      Self::Graphql => None,
207    }
208  }
209
210  /// The form this namespace takes when a declaration says nothing.
211  ///
212  /// Storage is for machines and a schema is for people, which is the whole of the split: a column
213  /// holds the discriminant, and the wire holds the name.
214  pub const fn default_form(self) -> StorageForm {
215    match self {
216      Self::Sqlite | Self::Postgres | Self::Mysql | Self::Mongo => StorageForm::Integer,
217      Self::Graphql => StorageForm::Text,
218    }
219  }
220
221  /// This namespace's name TYPE, on `ingraph`'s `name` shelf.
222  pub const fn name_type(self) -> &'static str {
223    match self {
224      Self::Sqlite => "SqliteName",
225      Self::Postgres => "PostgresName",
226      Self::Mysql => "MysqlName",
227      Self::Mongo => "MongoName",
228      Self::Graphql => "GraphqlName",
229    }
230  }
231
232  /// The accessor a TEXT face gets — `as_sqlite_str`, `as_graphql_str`.
233  ///
234  /// Mechanical from [`as_str`](Self::as_str), which is the word the declaration writes, so the
235  /// block a reader wrote and the method they reach for cannot drift apart.
236  pub fn accessor(self) -> syn::Ident {
237    format_ident!("as_{}_str", self.as_str())
238  }
239
240  /// The word this namespace spells `canonical` as when the declaration renamed nothing.
241  ///
242  /// Verbatim for a stored word and SHOUTED for the wire. The asymmetry is the ecosystem's rather
243  /// than this crate's: a GraphQL enum's members are `SCREAMING_SNAKE_CASE` by convention, so a face
244  /// spelling one `Vp9` would be the one schema that did not. A stored word has no such convention,
245  /// and a mangling rule that changed here would rewrite somebody's rows.
246  ///
247  /// The agreement that round owed is PAID, and paid by construction rather than by a pin: the
248  /// GraphQL face [`wire`] emits reads [`EnumVariant::name`] under [`Namespace::Graphql`], which is
249  /// this function, so the word `as_graphql_str` hands a caller and the value a client writes are one
250  /// string from one table. There is no second casing rule to disagree with `heck`'s, because there
251  /// is no derive applying one — the face is written out. `rename` is the escape from either.
252  pub fn default_name(self, canonical: &str) -> String {
253    match self {
254      Self::Sqlite | Self::Postgres | Self::Mysql | Self::Mongo => canonical.to_owned(),
255      Self::Graphql => canonical.to_shouty_snake_case(),
256    }
257  }
258}
259
260/// The width a vocabulary's discriminant is stored at — every integer `#[repr(…)]` the house's
261/// carrier table can carry, and no other.
262///
263/// `u64` is deliberately absent, and its absence is the table's rather than an oversight: MySQL has
264/// a native `u64` and SQLite and Postgres have none, so a `u64`-wide vocabulary would be storable in
265/// one of the three dialects. `usize` and `isize` are absent because they name no fixed width at
266/// all, and `i128`/`u128` because no dialect carries one.
267#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
268pub enum IntegerWidth {
269  /// `i8`.
270  I8,
271  /// `i16`.
272  I16,
273  /// `i32`.
274  I32,
275  /// `i64` — also the width a declaration with no `#[repr(…)]` takes.
276  I64,
277  /// `u8`.
278  U8,
279  /// `u16`.
280  U16,
281  /// `u32`.
282  U32,
283}
284
285impl IntegerWidth {
286  /// Every width, in the order a refusal lists them.
287  pub const ALL: [Self; 7] = [
288    Self::I8,
289    Self::I16,
290    Self::I32,
291    Self::I64,
292    Self::U8,
293    Self::U16,
294    Self::U32,
295  ];
296
297  /// The width a declaration with no integer `#[repr(…)]` takes — see the module note for why it is
298  /// the widest rather than the narrowest.
299  pub const DEFAULT: Self = Self::I64;
300
301  /// Rust's integer `#[repr(…)]` hints this framework cannot store, in the order a refusal lists
302  /// them.
303  pub const UNCARRIED: [&'static str; 5] = ["u64", "u128", "i128", "usize", "isize"];
304
305  /// The primitive this width is.
306  pub const fn as_str(self) -> &'static str {
307    match self {
308      Self::I8 => "i8",
309      Self::I16 => "i16",
310      Self::I32 => "i32",
311      Self::I64 => "i64",
312      Self::U8 => "u8",
313      Self::U16 => "u16",
314      Self::U32 => "u32",
315    }
316  }
317
318  /// The width this word names, when it is one this framework carries.
319  pub fn named(word: &str) -> Option<Self> {
320    Self::ALL.into_iter().find(|width| width.as_str() == word)
321  }
322
323  /// Whether `word` is one of Rust's INTEGER repr hints at all, carried here or not.
324  ///
325  /// The question a `#[repr(…)]` walk asks before refusing: `C`, `align(…)`, `packed` and
326  /// `transparent` are hints about LAYOUT that say nothing about a stored width, and an enum
327  /// carrying one is not a declaration this framework has anything to object to.
328  pub fn is_repr_word(word: &str) -> bool {
329    Self::named(word).is_some() || Self::UNCARRIED.contains(&word)
330  }
331
332  /// The primitive this database actually binds — the house widening, which only Postgres does.
333  ///
334  /// It is the framework's own `widened_carriers!` table restated for a vocabulary: Postgres has no
335  /// unsigned types and no `TINYINT`, so `i8` and `u8` bind as `i16`, `u16` as `i32` and `u32` as
336  /// `i64`. Every widening is lossless by construction — the target holds the source's whole range —
337  /// which is what makes an `as` cast to it exact rather than merely plausible.
338  pub const fn wire(self, database: DatabaseKind) -> Self {
339    match database {
340      DatabaseKind::Postgres => match self {
341        Self::I8 | Self::U8 => Self::I16,
342        Self::U16 => Self::I32,
343        Self::U32 => Self::I64,
344        Self::I16 | Self::I32 | Self::I64 => self,
345      },
346      DatabaseKind::Sqlite | DatabaseKind::Mysql | DatabaseKind::Mongo => self,
347    }
348  }
349}
350
351/// One variant, with whatever the declaration renamed it to.
352#[derive(Debug, Clone)]
353pub struct EnumVariant {
354  /// The variant as Rust spells it, `r#` and all.
355  pub ident: syn::Ident,
356  /// The GLOBAL `rename`, which moves the canonical word every namespace defaults from.
357  ///
358  /// A MIRROR has none — see [`upstream`](Self::upstream), which is what its `rename` names
359  /// instead.
360  pub rename: Option<String>,
361  /// The per-namespace renames, each overriding the canonical word in that one face.
362  ///
363  /// Always empty on a MIRROR: an upstream vocabulary spells itself, in one word, in every face.
364  pub names: BTreeMap<Namespace, String>,
365  /// On a MIRROR, the upstream variant this one restates, when it is not spelled alike.
366  pub upstream: Option<syn::Ident>,
367  /// The POSTURE of the `#[ingraph(other)]` escape — the one variant carrying a WORD rather than
368  /// naming a member — and [`None`] on every other variant.
369  ///
370  /// Its presence is the declaration saying the vocabulary is OPEN, in either mode. A vocabulary
371  /// this crate DECLARES takes [`Escape::Total`] and nothing else: the two gated postures point at a
372  /// totality living in somebody else's crate, and an open vocabulary with no upstream has no such
373  /// place for one to live.
374  pub escape: Option<Escape>,
375  /// The TEXT CARRIER an escape holds its word in — the marked variant's one unnamed field, as the
376  /// declaration wrote it — and [`None`] on every other variant.
377  ///
378  /// The carrier is the declaration's choice and this crate names no type for it: the door builds
379  /// one through [`From<&str>`](From) and reads one through [`AsRef<str>`](AsRef), so any text type
380  /// satisfying that pair holds a word. What is recorded here is the TOKEN, because one row needs
381  /// the type written rather than merely reachable through a bound — the key delegation, whose
382  /// `Inner` IS this type. Every other reader of an escape goes through the two traits and needs no
383  /// name at all.
384  ///
385  /// [`None`] beside a [`Some`] escape is a model that marked an escape and recorded no carrier;
386  /// the key row is what it costs, and the derive never builds one — see
387  /// [`key_delegation`](EnumModel::key_delegation).
388  pub carrier: Option<syn::Type>,
389}
390
391/// HOW a mirror turns a word its upstream does not name into an upstream value — the three postures
392/// `#[ingraph(other)]` takes, and the whole of what a mirror's openness can be.
393///
394/// The escape's presence says the upstream vocabulary is OPEN. What this says is where that openness
395/// LIVES, and the three answers are not interchangeable: one is a fact about the upstream's type, one
396/// is a fact about a function's signature, and one admits that the door itself can refuse.
397///
398/// # Why there are three, and not one
399///
400/// The first posture was the only one, and a vocabulary census walked into what it cannot express. A
401/// crate whose parse is behaviourally total but whose `FromStr::Err` is a shared refusal type — one
402/// error type serving a no-alloc tier that really can refuse and an alloc tier that cannot — reads as
403/// CLOSED to a bound on that type, while the same crate hands out a `fn other(impl AsRef<str>) ->
404/// Self` that is total in the only way that matters. Nine types were unmirrorable for that reason
405/// alone. The gate is what lets a declaration point at the totality instead of asking the type
406/// system to find it.
407#[derive(Debug, Clone)]
408pub enum Escape {
409  /// Bare `#[ingraph(other)]` — the UPSTREAM'S OWN parse is total, and its `FromStr::Err` is where
410  /// that is said.
411  ///
412  /// The strongest of the three and the one that needs no gate: the claim is spent as a bound on
413  /// `<Remote as FromStr>::Err`, and the compiler settles it. Nothing about this posture moved when
414  /// the other two arrived.
415  Total,
416  /// `#[ingraph(other(from = "…"))]` — an UNCONDITIONAL gate, `fn(impl AsRef<str>) -> Remote`.
417  ///
418  /// The totality is the GATE'S SIGNATURE rather than the upstream's error type, and the mirror is
419  /// as open as a bare `other`: its `FromStr::Err` is [`Infallible`](core::convert::Infallible) and
420  /// no refusal type is declared beside the enum. The door parses FIRST and falls to the gate only
421  /// on a refusal, so every word the upstream does name still reaches its own variant.
422  Gate(syn::Path),
423  /// `#[ingraph(other(try_from = "…"))]` — a gate that can REFUSE, which makes the mirror HALF-OPEN.
424  ///
425  /// Open outward: the `From<Remote>` arm list still carries the wildcard that absorbs an upstream
426  /// value this mirror does not restate. Closed inward: a word neither the upstream's parse nor the
427  /// gate accepts is a refusal, reported as this vocabulary's own `<Enum>ParseError` exactly as a
428  /// closed mirror reports its upstream's — which is why `error(rename = "…")` is legal here and in
429  /// neither of the other two.
430  ///
431  /// The gate's `Err` must BE `<Remote as FromStr>::Err`, and that law is what makes the posture
432  /// coherent rather than merely permitted: under it the door composes to a function with the same
433  /// type as `from_str` itself, so there is one refusal for the wrapping to name.
434  TryGate(syn::Path),
435}
436
437impl Escape {
438  /// The gate this posture spends, and [`None`] for the one that has none.
439  #[must_use]
440  pub const fn gate(&self) -> Option<&syn::Path> {
441    match self {
442      Self::Total => None,
443      Self::Gate(path) | Self::TryGate(path) => Some(path),
444    }
445  }
446
447  /// Whether the door this posture builds can REFUSE a word — the ONE question every fork in the
448  /// emission asks, and the reason the three postures are a type rather than two booleans.
449  #[must_use]
450  pub const fn refuses(&self) -> bool {
451    matches!(self, Self::TryGate(_))
452  }
453}
454
455impl EnumVariant {
456  /// The CANONICAL word: the global rename, else the variant's own name unraw'd.
457  ///
458  /// The `r#` is Rust's escape for a word that collides with its grammar and no part of the name, so
459  /// a variant called `r#type` is canonically `type` — which is what a schema and a hand-written row
460  /// would spell.
461  pub fn canonical(&self) -> String {
462    use syn::ext::IdentExt as _;
463
464    self
465      .rename
466      .clone()
467      .unwrap_or_else(|| self.ident.unraw().to_string())
468  }
469
470  /// The word one namespace spells this variant as: its own rename, else that namespace's default
471  /// over the canonical word.
472  pub fn name(&self, namespace: Namespace) -> String {
473    self
474      .names
475      .get(&namespace)
476      .cloned()
477      .unwrap_or_else(|| namespace.default_name(&self.canonical()))
478  }
479
480  /// The word an OPEN vocabulary spells this variant with: its `rename`, else the Rust name in the
481  /// framework's own lower-case household — `LeftShoulder` is `left_shoulder`.
482  ///
483  /// # Why an open vocabulary defaults DIFFERENTLY from a closed one
484  ///
485  /// A closed vocabulary's word is its variant's name verbatim, because the set IS the declaration
486  /// and a client reading an SDL `enum` sees exactly the members it publishes. An open one publishes
487  /// a SCALAR, so its words meet the outside world as text — from a producer's protobuf, a label
488  /// file, a Swift enum — and the house register's answer for text is lower case. Defaulting to the
489  /// Rust spelling would put a `Pascal` word in a position every other producer writes in snake.
490  ///
491  /// The default is what the five vocabularies this mode was measured against already spell by
492  /// hand: all forty-three of their words are `to_snake_case` of the variant name, exactly. `rename`
493  /// is the escape from the arithmetic, not a knob a declaration is expected to reach for.
494  pub fn folded(&self) -> String {
495    use syn::ext::IdentExt as _;
496
497    self
498      .rename
499      .clone()
500      .unwrap_or_else(|| self.ident.unraw().to_string().to_snake_case())
501  }
502
503  /// The predicate this variant gets — `is_low`, `is_h264`.
504  ///
505  /// Over the RUST spelling rather than the canonical word, because the method is Rust and its
506  /// reader is looking at the variant: a `#[ingraph(rename = "lo")]` moves what a database stores
507  /// and not what the enum is called.
508  pub fn predicate(&self) -> syn::Ident {
509    use syn::ext::IdentExt as _;
510
511    format_ident!("is_{}", self.ident.unraw().to_string().to_snake_case())
512  }
513
514  /// The UPSTREAM variant a mirror's variant restates — the declared `rename`, else its own name.
515  ///
516  /// The mirror's two `From` arms are written from this, so a name that answers to nothing upstream
517  /// is `E0599` at the arm naming it. That is the whole enforcement, and it is the compiler's: a
518  /// derive cannot see the upstream declaration, and a table of upstream names kept here would be a
519  /// second copy of somebody else's enum.
520  pub fn upstream(&self) -> syn::Ident {
521    self.upstream.clone().unwrap_or_else(|| self.ident.clone())
522  }
523}
524
525/// The UPSTREAM vocabulary a declaration mirrors, and what it asked to borrow from it.
526///
527/// A mirror RESTATES the upstream's variants — identifiers only — and delegates the whole slug
528/// grammar to the upstream's own [`FromStr`](core::str::FromStr) and [`Display`](core::fmt::Display).
529/// That is the single-source rule this mode is built on: there is no second table of words here for
530/// the upstream's to drift from.
531#[derive(Debug, Clone)]
532pub struct Remote {
533  /// The upstream type, as the declaration wrote it.
534  pub path: syn::Path,
535  /// The methods forwarded onto the materialized upstream value, each restated by the declaration.
536  ///
537  /// The signature is the DECLARATION'S because Rust has no `typeof`: a forwarding method needs a
538  /// written return type, and the one place that type is known is the declaration doing the asking.
539  pub delegates: Vec<Delegate>,
540}
541
542pub use crate::delegate::{Delegate, DelegateSkin};
543
544/// The field a PROMOTED mirror publishes its own word at.
545///
546/// The one thing an object face must still be able to answer that the scalar answered by BEING the
547/// word: `text` is the canonical slug, rendered exactly as the upstream renders it. Named here
548/// rather than spelled at each of the three sites that need it — the emitted registry entry, the
549/// emitted resolver arm, and the front end refusing a published method that would collide with it.
550pub const TEXT_FIELD: &str = "text";
551
552/// One vocabulary's declaration, validated.
553///
554/// Public fields for the reason [`RecordModel`](crate::model::RecordModel)'s are: nothing here
555/// parses, so a front end that is not the derive builds the same struct and reaches the same
556/// emitter.
557#[derive(Debug, Clone)]
558pub struct EnumModel {
559  /// Where `ingraph` lives, for the shelf every emitted path is rooted at.
560  pub krate: syn::Path,
561  /// The declaration's visibility, which every emitted item takes.
562  pub vis: syn::Visibility,
563  /// The declared enum's own name.
564  pub name: syn::Ident,
565  /// The integer `#[repr(…)]` the declaration carries, when it carries one.
566  pub width: Option<IntegerWidth>,
567  /// Its variants, in declaration order. Never empty — an enum with none has no value.
568  pub variants: Vec<EnumVariant>,
569  /// The per-namespace form OVERRIDES. A namespace with no entry takes
570  /// [`Namespace::default_form`].
571  pub forms: BTreeMap<Namespace, StorageForm>,
572  /// `graphql(rename = "…")` — what a SCHEMA calls this vocabulary, where the declaration moved it.
573  ///
574  /// `None` is the Rust name unraw'd, which is what [`EnumModel::sdl_name`] resolves.
575  ///
576  /// EMISSION-ONLY, and that is the whole of its reach: nothing in Rust and nothing in a database
577  /// reads this word, so a declaration writing one keeps every minted type name, every accessor and
578  /// every stored word it had. It is a `String` rather than a [`syn::Ident`] because nothing in Rust
579  /// is called this — see [`EnumModel::sdl_name`] for the grammar it is held to instead.
580  pub wire_name: Option<String>,
581  /// What the emitted REFUSAL type is called, when the declaration named it.
582  ///
583  /// `None` is `<Enum>ParseError`, which is what [`EnumModel::error`] resolves. The knob exists for
584  /// a COLLISION rather than for taste — see the module note — so the default is not a thing anyone
585  /// has to reach for, and a declaration that names nothing is unaffected by the knob's existence.
586  pub error: Option<syn::Ident>,
587  /// The UPSTREAM vocabulary this declaration mirrors, when it mirrors one.
588  ///
589  /// `None` is the whole of today's mode and nothing about it moves: a vocabulary that names no
590  /// upstream owns its own words, stores a discriminant and publishes a GraphQL `enum`. See
591  /// [`remote`](self::remote) for what the other mode is and why it is a different emission rather
592  /// than a flag through this one.
593  pub remote: Option<Remote>,
594}
595
596impl EnumModel {
597  /// The form one namespace takes: the declared override, else the namespace's own default.
598  #[must_use]
599  pub fn form(&self, namespace: Namespace) -> StorageForm {
600    self
601      .forms
602      .get(&namespace)
603      .copied()
604      .unwrap_or_else(|| namespace.default_form())
605  }
606
607  /// The width the discriminant is stored at: the declared `#[repr(…)]`, else
608  /// [`IntegerWidth::DEFAULT`].
609  #[must_use]
610  pub fn width(&self) -> IntegerWidth {
611    self.width.unwrap_or(IntegerWidth::DEFAULT)
612  }
613
614  /// The refusal type this declaration's parses answer with — the declared name, else
615  /// `GradeParseError`.
616  ///
617  /// The ONE authority on what that type is called: the emission writes this, and a front end's
618  /// collision check asks it rather than rebuilding the suffix convention on its own side.
619  #[must_use]
620  pub fn error(&self) -> syn::Ident {
621    self
622      .error
623      .clone()
624      .unwrap_or_else(|| format_ident!("{}ParseError", self.name))
625  }
626
627  /// The ESCAPE variant, on a vocabulary that has one.
628  ///
629  /// Its presence is what says the vocabulary is OPEN — the second axis of [`emit`](Self::emit)'s
630  /// four cells — and every fork in [`remote`]'s and [`own`]'s emissions reads it here rather than
631  /// re-deriving the question from the variant list.
632  #[must_use]
633  pub fn escape(&self) -> Option<&EnumVariant> {
634    self
635      .variants
636      .iter()
637      .find(|variant| variant.escape.is_some())
638  }
639
640  /// The escape's POSTURE — which of [`Escape`]'s three the declaration wrote.
641  ///
642  /// Asked here rather than unwrapped at each of the six sites that fork on it, for the reason
643  /// [`escape`](Self::escape) is: one question, one place it is answered.
644  #[must_use]
645  pub fn posture(&self) -> Option<&Escape> {
646    self.escape().and_then(|variant| variant.escape.as_ref())
647  }
648
649  /// Whether this vocabulary's own parse can REFUSE a word.
650  ///
651  /// True of anything CLOSED — a vocabulary this crate declares, whose variants ARE the set, and a
652  /// closed mirror, which reports its upstream's refusal as its own — and of a HALF-OPEN mirror,
653  /// whose gate can refuse. False of the two postures that promise every word parses, which is every
654  /// OPEN vocabulary this crate declares and the two total mirror postures. It is what decides
655  /// whether a refusal type is declared beside the enum at all, and therefore whether
656  /// `error(rename = "…")` has anything to move.
657  #[must_use]
658  pub fn refuses(&self) -> bool {
659    self.posture().is_none_or(Escape::refuses)
660  }
661
662  /// Every variant that NAMES a member — the whole list, minus the escape.
663  ///
664  /// On a mirror those are the upstream names it restates; on a vocabulary this crate declares they
665  /// are the roster's own. What they share is being the list a `&'static [Self]` can hold, the escape
666  /// carrying a runtime word and therefore being no constant.
667  pub fn restated(&self) -> impl Iterator<Item = &EnumVariant> {
668    self
669      .variants
670      .iter()
671      .filter(|variant| variant.escape.is_none())
672  }
673
674  /// The delegated methods PUBLISHED at one backend, in declaration order.
675  ///
676  /// The whole of the promotion law's antecedent: a mirror with none of these renders as a scalar in
677  /// both positions — today's shape, unmoved — and a mirror with one or more renders its OUTPUT seat
678  /// as an OBJECT and its input seat as a scalar called `<Enum>Input`. Asked HERE rather than
679  /// re-derived at each of the four sites that fork on it, so a mirror cannot be promoted in one and
680  /// not another.
681  ///
682  /// Empty for a DECLARED vocabulary, which delegates nothing: the accessor answers about the model
683  /// rather than about the mode, so a caller needs no second question first.
684  pub fn promoted(&self, kind: GraphqlKind) -> impl Iterator<Item = &Delegate> {
685    self
686      .remote
687      .iter()
688      .flat_map(|remote| remote.delegates.iter())
689      .filter(move |delegate| delegate.wire.iter().any(|skin| skin.kind == kind))
690  }
691
692  /// Every name a MIRROR's expansion puts in the enum's own value namespace, in emission order.
693  ///
694  /// # What it is FOR, and why it stops at the mirror
695  ///
696  /// A `delegate(fn …)` entry restates a method name the author chose, and a mirror's expansion
697  /// declares names of its own beside it — so the two can meet, and rustc reports the meeting as
698  /// `E0592` at the derive, a span the author cannot edit and a message that never names the entry.
699  /// This is the list a front end moves that report with, and the seat that makes it necessary is the
700  /// MIRROR's alone: a declared vocabulary has no `delegate(…)`, so nothing an author wrote is in its
701  /// namespace to collide with, and enumerating its names would be a model nothing spends.
702  ///
703  /// Empty for a declared vocabulary, therefore, and empty in the [`promoted`](Self::promoted) sense:
704  /// the accessor answers about the model rather than about the mode, so a caller needs no second
705  /// question first.
706  ///
707  /// # The list, and where each row comes from
708  ///
709  /// [`mirror_face`](remote) is the one inherent impl a mirror emits, and it declares four kinds of
710  /// name in this order:
711  ///
712  /// | row | [`Origin`] |
713  /// |---|---|
714  /// | `VARIANTS`, the restated roster | [`Origin::Roster`] |
715  /// | `remote()`, the materialization gate | [`Origin::Materialization`] |
716  /// | one `is_…` per variant, the ESCAPE included | [`Origin::Predicate`] |
717  /// | one forwarding method per MINTED delegate | [`Origin::Delegate`] |
718  ///
719  /// `VARIANTS` is an associated CONST and is here all the same: Rust's value namespace holds consts
720  /// and functions together, so a delegate spelled `VARIANTS` is a duplicate definition exactly as a
721  /// second `remote` would be.
722  ///
723  /// # A WAIVED entry is enumerated, and it is the one row the emission does not write
724  ///
725  /// `on = self` waives the forwarding mint, so nothing is emitted for that entry — but the word says
726  /// the method exists on this type, written by the author's own hand, and that method occupies the
727  /// namespace exactly as a mint would. The question this list answers is which names are TAKEN, not
728  /// which tokens this emitter wrote, so a waived entry is a row. It is the one asymmetry, and the
729  /// pin against the emission is stated over declarations that carry no waiver for that reason.
730  #[must_use]
731  pub fn emitted_methods(&self) -> Vec<Emitted> {
732    let Some(remote) = self.remote.as_ref() else {
733      return Vec::new();
734    };
735    let fixed = [
736      (format_ident!("VARIANTS"), Origin::Roster),
737      (format_ident!("remote"), Origin::Materialization),
738    ];
739    let predicates = self.variants.iter().map(|variant| {
740      (
741        variant.predicate(),
742        Origin::Predicate(variant.ident.clone()),
743      )
744    });
745    let delegated = remote.delegates.iter().map(|delegate| {
746      let method = delegate.signature.ident.clone();
747      (method.clone(), Origin::Delegate(method))
748    });
749    fixed
750      .into_iter()
751      .chain(predicates)
752      .chain(delegated)
753      .map(|(name, origin)| Emitted {
754        owner: Owner::Record,
755        owner_name: self.name.clone(),
756        name,
757        origin,
758      })
759      .collect()
760  }
761
762  /// The whole expansion: the refusal type, then the rows, the face and the wire.
763  ///
764  /// The impls sit in anonymous `const _: () = { … };` blocks, as a record's do — it changes nothing
765  /// about reaching them and it gives the per-backend mapping functions a scope where they can
766  /// collide with nothing the declaring module wrote. The refusal type cannot: it is named in
767  /// signatures a caller writes.
768  ///
769  /// The WIRE face is a second block rather than a member of this one, because the whole of it sits
770  /// behind the binding gate: a build without `async-graphql` expands the block's contents to
771  /// nothing, and keeping it separate is what lets that be true of a gate wrapping the block's whole
772  /// body rather than of a `cfg` sprinkled through this one.
773  ///
774  /// # FOUR CELLS, and the declaration's own SHAPE picks one
775  ///
776  /// There is no word for the mode. Two structural facts decide it — whether `remote = "…"` names an
777  /// upstream, and whether a variant wears `#[ingraph(other)]` — and the four combinations are the
778  /// whole grammar:
779  ///
780  /// | | no escape | an `#[ingraph(other)]` escape |
781  /// |---|---|---|
782  /// | **no `remote`** | a CLOSED vocabulary this crate declares — below | an OPEN one, [`own`] |
783  /// | **`remote = "…"`** | a closed MIRROR, [`remote`] | an open mirror, [`remote`] |
784  ///
785  /// The forks are not four emissions. A mirror's words are its upstream's, so its face, parses,
786  /// stored form and wire all differ and [`remote`] writes them; an open vocabulary this crate
787  /// declares owns its words like the closed one below and stores them like a mirror, so [`own`]
788  /// writes the half that is neither and shares the rest with both.
789  #[must_use]
790  pub fn emit(&self) -> proc_macro2::TokenStream {
791    if let Some(remote) = self.remote.as_ref() {
792      return self.emit_mirror(remote);
793    }
794    if let Some(escape) = self.escape() {
795      return self.emit_open(escape);
796    }
797    let error = self.refusal();
798    let reading = self.reading();
799    let face = self.face();
800    let parsing = self.parsing();
801    let key = self.key_delegation();
802    let storage = DatabaseKind::ALL
803      .into_iter()
804      .map(|database| self.storage_rows(database));
805    let width = self.width_row();
806    let read = self.read_row();
807    let wire = self.graphql_face();
808    quote! {
809      #error
810
811      const _: () = {
812        #reading
813        #face
814        #parsing
815        #key
816        #width
817        #read
818        #(#storage)*
819      };
820
821      #wire
822    }
823  }
824
825  /// KEY ADMISSION: the row that lets a column of this vocabulary be a record's `#[ingraph(id)]` or
826  /// an aggregate's group projection, and it costs a declaration NO word.
827  ///
828  /// The id vocabulary is sealed and admits a type from outside it on one law — TRANSPARENCY, stated
829  /// as `unsafe impl DelegatesId`. A closed vocabulary satisfies that law exactly: its value IS one
830  /// of a fixed set of words, the words are the declaration's own canonical spellings, and the front
831  /// end already refuses two variants that would share one — so the map from value to word is a
832  /// bijection. Writing the row here is what makes the ergonomics claim true: a declarer reaches for
833  /// `#[derive(ingraph::Enum)]` for the column faces and gets the KEY face in the same line.
834  ///
835  /// # An OPEN vocabulary gets the row too, and its `Inner` is the CARRIER the declaration wrote
836  ///
837  /// The first cut of this row stopped at the closed shape, on the argument that an escape carries a
838  /// RUNTIME word — no `&'static` for that arm, and no single `Inner` both arms could share. The
839  /// first half is true and the second is not, and the difference is one token: the escape's payload
840  /// TYPE is written at the declaration, so the emission can name it.
841  /// [`open_key_delegation`](Self::open_key_delegation) is what that buys — `Inner` is the carrier,
842  /// the named arms hold `static`s OF THE CARRIER, and the escape arm hands back the field it already
843  /// holds.
844  ///
845  /// Which matters because the escape is not an exotic corner: it is the vocab train's STANDARD
846  /// shape. Every mirrored household — `AudioCodec`, `PixelFormat`, `ColorPrimaries` — restates the
847  /// members it names and carries `Other(Utf8Bytes)` for the ones it does not, so a boundary drawn at
848  /// the escape would have excluded the common case and admitted the rare one.
849  ///
850  /// # `Utf8Bytes`, behind a `LazyLock`, and both halves are measured
851  ///
852  /// The CLOSED row's text member is `Utf8Bytes` because that is this house's text carrier wherever
853  /// one is reached for, and because a word that fits the inline capacity is held without allocating
854  /// at all — which every variant name does. An OPEN one takes the declaration's carrier instead, for
855  /// the reason above; nothing else about the row differs.
856  ///
857  /// The `LazyLock` is the dependency floor rather than a preference. The trait hands back a BORROW
858  /// and a unit variant holds no field, so the word has to live in a `static`; `from_static` became
859  /// `const fn` in `smol-bytes` 0.1.4, and this crate's floor is `0.1`, which a PATCH floor is not
860  /// written to raise. So the word is initialised once, on first use, and every call after that is a
861  /// load. Where the floor rises to a minor version carrying the `const` constructor, the `LazyLock`
862  /// becomes a plain `static` and nothing else here moves.
863  ///
864  /// # This word and the CURSOR's are both injective, and need not be the same word
865  ///
866  /// A declared vocabulary's cursor pages by `as_str`, which IS the canonical word, so those two
867  /// agree by construction. A MIRROR's cursor pages by the upstream's own `Display`, which is a call
868  /// rather than a constant and therefore cannot be a `static` — so its segment is the mirror's own
869  /// canonical word instead. Nothing requires the two to match: a `u64`'s cursor is eight big-endian
870  /// bytes and its segment is decimal, and what each duty owes is injectivity in ITS OWN form.
871  fn key_delegation(&self) -> proc_macro2::TokenStream {
872    if let Some(escape) = self.escape() {
873      return self.open_key_delegation(escape);
874    }
875    let name = &self.name;
876    let delegates = self.framework(&["id"], "DelegatesId");
877    let text = self.framework(&["smol_bytes"], "Utf8Bytes");
878    let arms = self.variants.iter().map(|variant| {
879      let ident = &variant.ident;
880      let word = variant.canonical();
881      quote! {
882        Self::#ident => {
883          static __INGRAPH_WORD: ::std::sync::LazyLock<#text> =
884            ::std::sync::LazyLock::new(|| <#text>::from_static(#word));
885          ::std::sync::LazyLock::force(&__INGRAPH_WORD)
886        }
887      }
888    });
889    quote! {
890      // SAFETY: a closed vocabulary IS its word. Every variant is a unit — no payload, no width and
891      // no second field a key would have to tell apart — and the canonical words are checked
892      // distinct at the declaration, so two values are equal exactly when their words are. The body
893      // is a match over `self` and nothing else, so it is pure and answers one word per value.
894      #[automatically_derived]
895      unsafe impl #delegates for #name {
896        type Inner = #text;
897
898        #[inline]
899        fn delegate(&self) -> &#text {
900          match self {
901            #(#arms)*
902          }
903        }
904      }
905    }
906  }
907
908  /// KEY ADMISSION for an OPEN vocabulary — the second arm of [`key_delegation`], in either mode.
909  ///
910  /// `Inner` is the CARRIER the declaration wrote on its escape, and the two kinds of arm meet in it:
911  /// a named member hands back a `static` holding its own word, and the escape hands back the word it
912  /// is already carrying. One `Inner`, one borrow per arm, and no allocation on either road.
913  ///
914  /// # A non-carrier payload fails at the DECLARATION, and this row is where the sentence lives
915  ///
916  /// This emission knows the payload's token and nothing else about it. It builds a word through
917  /// [`carrier_obligation`](Self::carrier_obligation) — `From<&'static str>` wearing a name, which is
918  /// half the pair `new` and the mirror's `From<Remote>` arm already build escapes with, so a type
919  /// that holds a word for this vocabulary at all satisfies it.
920  ///
921  /// The NAME is the point. A payload that is not a text carrier was already `E0277` at the
922  /// declaration, twice, and both reports landed on the DERIVE's own token and named `From<&str>` and
923  /// `AsRef<str>` with nothing to connect either to an escape. This row's is the third and the only
924  /// one that lands on the FIELD the author wrote — so the report naming the author's own token is
925  /// also the one that says what a carrier is.
926  ///
927  /// A payload that IS a text carrier but is not a member of the sealed id set compiles, says a true
928  /// thing about itself, and is refused at the KEY POSITION, which is the delegation law's own posture
929  /// for a chain that grounds in nothing.
930  ///
931  /// # What the named arm's WORD is, and why it is the face's rather than the model's
932  ///
933  /// It is the word this vocabulary's own face spells that variant with, wherever that word is a
934  /// constant:
935  ///
936  /// | mode | the named arm's word | and it is |
937  /// |---|---|---|
938  /// | a vocabulary this crate DECLARES | [`folded`](EnumVariant::folded) | exactly `as_str`, so the key word, the stored word and the cursor word are ONE word |
939  /// | a MIRROR | [`canonical`](EnumVariant::canonical) | the mirror's own name — its face word is the upstream's `Display`, which is a call and cannot be a `static` |
940  ///
941  /// # INJECTIVITY, and where each mode's is held
942  ///
943  /// A key's whole obligation is that two values equal exactly when their delegates are, so the two
944  /// KINDS of arm must not collide — an escape whose carried word is some member's word would put two
945  /// distinct values on one row.
946  ///
947  /// **A vocabulary this crate declares holds it by construction, through its own door.** `new`
948  /// walks the roster under `folds_to` BEFORE it builds an escape, so a word that folds to a member's
949  /// word reaches that member and never becomes an escape; and what the escape carries is
950  /// `name::folded` of the arriving spelling, which is separator-free lower-case, while a member's
951  /// word is its `folded` spelling. The two arms therefore cannot meet on a value the door built.
952  ///
953  /// **A mirror holds it the same way, one crate over.** The `From<Remote>` arm list routes every
954  /// upstream value this mirror RESTATES to its own named arm, and only what is left reaches the
955  /// wildcard that builds an escape — so an escape carries the rendering of an upstream value the
956  /// mirror does not name, and a named arm's word is a Rust identifier this declaration wrote. Two
957  /// named arms cannot collide either: they are distinct identifiers, and `rename` does not move a
958  /// mirror's canonical word.
959  ///
960  /// **A HAND-BUILT escape is the one shadowing, and it is not new.** Nothing stops a declaring crate
961  /// writing `Codec::Other("aac".into())` beside `Codec::Aac` in its own source, and such a value is
962  /// already indistinguishable from the member at the STORED COLUMN, at the CURSOR and on the WIRE —
963  /// an open vocabulary's `as_str` answers the carried word verbatim, and a mirror renders through
964  /// `remote()`, which parses the word straight back onto the member. So the key row inherits exactly
965  /// the invariant the rest of the vocabulary already rides on, adds no new hazard, and the door is
966  /// what upholds it — which is what the `unsafe` on the emitted impl asserts.
967  fn open_key_delegation(&self, escape: &EnumVariant) -> proc_macro2::TokenStream {
968    // A model that marked an escape and recorded no carrier has nothing to write `Inner` with. The
969    // derive always records one — the front end refuses an escape that is not exactly one unnamed
970    // field — so this is the OTHER front end's cell, and what it costs is the key row alone.
971    let Some(carrier) = escape.carrier.as_ref() else {
972      return quote!();
973    };
974    let name = &self.name;
975    let escaped = &escape.ident;
976    let delegates = self.framework(&["id"], "DelegatesId");
977    let mirrors = self.remote.is_some();
978    let arms = self
979      .restated()
980      .map(|variant| {
981        let ident = &variant.ident;
982        let word = if mirrors {
983          variant.canonical()
984        } else {
985          variant.folded()
986        };
987        quote! {
988          Self::#ident => {
989            static __INGRAPH_WORD: ::std::sync::LazyLock<#carrier> = ::std::sync::LazyLock::new(
990              || <#carrier as __IngraphCarriesAWord>::__ingraph_word(#word),
991            );
992            ::std::sync::LazyLock::force(&__INGRAPH_WORD)
993          }
994        }
995      })
996      .collect::<Vec<_>>();
997    let obligation = (!arms.is_empty()).then(|| self.carrier_obligation());
998    quote! {
999      #obligation
1000
1001      // SAFETY: an open vocabulary IS a word too — one of the roster's, or the one the escape
1002      // carries. Every named variant is a unit and the escape holds exactly one field, so there is
1003      // no second field, tag or width a key would have to tell apart, and the two kinds of arm
1004      // cannot collide on a value this vocabulary's own door built — see the method note for where
1005      // each mode's injectivity is held. The body is a match over `self` and nothing else, so it is
1006      // pure and answers one word per value.
1007      #[automatically_derived]
1008      unsafe impl #delegates for #name {
1009        type Inner = #carrier;
1010
1011        #[inline]
1012        fn delegate(&self) -> &#carrier {
1013          match self {
1014            #(#arms)*
1015            Self::#escaped(__ingraph_word) => __ingraph_word,
1016          }
1017        }
1018      }
1019    }
1020  }
1021
1022  /// What an escape's CARRIER has to be, declared BESIDE the key row so the refusal for a payload
1023  /// that is not one carries a sentence.
1024  ///
1025  /// The obligation itself is `From<&'static str>`, which is half the pair the door already spends —
1026  /// so this asks a declaration for nothing it was not already asked for, and a carrier that holds a
1027  /// word at all satisfies it. What the trait adds is a NAME for the obligation, and a name is what
1028  /// `#[diagnostic::on_unimplemented]` attaches to.
1029  ///
1030  /// # Declared in the EXPANSION rather than in the framework, and the reason is a golden
1031  ///
1032  /// A trait on this crate's own shelf would be reported at two different paths on two toolchains —
1033  /// stable names where it is DEFINED and nightly the re-export an expansion travels — which is the
1034  /// divergence class `ci/nightly-divergences.md` exists for, arriving in a lane that has none. A
1035  /// trait declared inside the expansion has one spelling everywhere, so the refusal's golden is the
1036  /// same text on both chains. It is also the device the mirror's totality claim already uses
1037  /// (`__IngraphTotalFromStr`), so this is the house's own shape rather than a second one.
1038  ///
1039  /// # [`do_not_recommend`](diagnostic::do_not_recommend) on the blanket, and it is load-bearing
1040  ///
1041  /// Unmarked, the refusal peels to the blanket's own `where` clause — *the trait bound
1042  /// `u32: From<&'static str>` is not satisfied* — and the sentence below becomes a *required for*
1043  /// note under it, which is the message buried rather than said. Marked, the report is the root
1044  /// bound and its own notes, which is the same reason `composed_slot_shape`'s second fixture reaches
1045  /// for the attribute.
1046  ///
1047  /// # Emitted only where there is a WORD to build
1048  ///
1049  /// A vocabulary whose only variant is the escape has no named arm, hence no `static`, hence nothing
1050  /// to spend the bound on — and an unspent obligation would be an unused trait in a declaring
1051  /// crate's own module, which is a `dead_code` warning somebody else has to silence.
1052  fn carrier_obligation(&self) -> proc_macro2::TokenStream {
1053    let name = &self.name;
1054    let message = "`{Self}` cannot carry an `#[ingraph(other)]` escape's word";
1055    let carrier = format!(
1056      "an escape holds a WORD, so its field's type has to be a TEXT CARRIER: buildable from one \
1057       (`From<&str>`) and readable back as one (`AsRef<str>`). `ingraph::Utf8Bytes` is the house's, \
1058       and `String` and `SmolStr` are carriers too — `{name}`'s escape is where the choice is \
1059       written, and it is the whole of what this vocabulary asks of it"
1060    );
1061    let key = "the bound is spent by the KEY row, which is what lets a vocabulary stand at an \
1062               `#[ingraph(id)]` or an aggregate's group column with no extra word: the named \
1063               members delegate to `static`s of the carrier and the escape delegates the word it \
1064               carries, so the carrier is also what such a key ADDRESSES by. A text carrier that is \
1065               not a member of the sealed id vocabulary compiles here and is refused at the KEY \
1066               POSITION instead — see `ingraph::Id`";
1067    quote! {
1068      #[diagnostic::on_unimplemented(
1069        message = #message,
1070        label = "not a text carrier",
1071        note = #carrier,
1072        note = #key,
1073      )]
1074      trait __IngraphCarriesAWord {
1075        fn __ingraph_word(word: &'static ::core::primitive::str) -> Self;
1076      }
1077
1078      #[diagnostic::do_not_recommend]
1079      impl<T: ::core::convert::From<&'static ::core::primitive::str>> __IngraphCarriesAWord for T {
1080        #[inline]
1081        fn __ingraph_word(word: &'static ::core::primitive::str) -> Self {
1082          ::core::convert::From::from(word)
1083        }
1084      }
1085    }
1086  }
1087
1088  /// The enum's COLUMN WIDTH: one, whichever form it stores as.
1089  ///
1090  /// Outside every gate and stated once, where the carrier rows are per backend and inside theirs.
1091  /// That is `ColumnKind` carrying no dialect: a declared enum is one column as text and one as an
1092  /// integer, so the fact has no backend to vary with — and a build compiling no SQL family still
1093  /// needs the row, because the trait it satisfies names no database either.
1094  ///
1095  /// It takes the DEFAULT and states nothing, which is the whole content of *this is one column*.
1096  fn width_row(&self) -> proc_macro2::TokenStream {
1097    let name = &self.name;
1098    let column_kind = self.framework(&["column"], "ColumnKind");
1099    let column_eq = self.framework(&["column"], "ColumnEq");
1100    quote! {
1101      #[automatically_derived]
1102      impl #column_kind for #name {}
1103
1104      // The SAMENESS row beside the width row, outside every gate for that row's reason: two words
1105      // of a vocabulary are one column value or they are not, and no dialect changes the answer.
1106      //
1107      // Its body is the enum's OWN `PartialEq`, which is the trait a stored vocabulary has always
1108      // owed — an emitted row derived `PartialEq` over its declared field types until this face
1109      // existed. What moved is where the demand is MADE: here, at the declaration that wrote the
1110      // enum, instead of inside a record's expansion the author cannot edit.
1111      #[automatically_derived]
1112      impl #column_eq for #name {
1113        #[inline]
1114        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
1115          ::core::cmp::PartialEq::eq(self, __ingraph_other)
1116        }
1117      }
1118    }
1119  }
1120
1121  /// How a holder's row READS one of these back: as the one column its width says it is.
1122  ///
1123  /// It is the third of the three facts a stored type states — the width above, this, and the per
1124  /// backend `Carrier` below — and a declared enum needs all three the moment a record stores one:
1125  /// an emitted decode writes ONE uniform spelling per field, because `codec: Codec` and
1126  /// `tb: Timebase` are the same tokens, so the type is what answers whether that spelling fetches
1127  /// one column or several.
1128  ///
1129  /// Generic over the ROW and stated once, where the carrier rows are per backend: what varies per
1130  /// dialect is the `Decode` this delegates to, and stating it as an obligation is what lets one impl
1131  /// serve every dialect the declaration's own rows cover.
1132  ///
1133  /// The FAMILY gate rather than a dialect's, and rather than none: the trait is `sqlx::Row`'s
1134  /// vocabulary, so a build with no SQL family has no trait for this to implement — while a build
1135  /// with two would get this impl twice if it rode the per-dialect gates the storage rows ride.
1136  fn read_row(&self) -> proc_macro2::TokenStream {
1137    let name = &self.name;
1138    let gate = self.framework(&["gate"], "if_sqlx");
1139    let assemble = self.framework(&["column"], "Assemble");
1140    let plain_column = self.framework(&["column"], "plain_column");
1141    let path = self.framework(&["comparison"], "Path");
1142    let row_trait = self.framework(&["sqlx"], "Row");
1143    let decode = self.framework(&["sqlx"], "Decode");
1144    let sqlx_type = self.framework(&["sqlx"], "Type");
1145    let column_index = self.framework(&["sqlx"], "ColumnIndex");
1146    let result = self.framework(&["sqlx"], "Result");
1147    let row = crate::emit::parameter("ROW");
1148    quote! {
1149      #gate! {
1150        #[automatically_derived]
1151        impl<'__ingraph, #row> #assemble<'__ingraph, #row> for #name
1152        where
1153          #row: #row_trait,
1154          #name: #decode<'__ingraph, <#row as #row_trait>::Database>
1155            + #sqlx_type<<#row as #row_trait>::Database>,
1156          for<'__ingraph_name> &'__ingraph_name ::core::primitive::str: #column_index<#row>,
1157        {
1158          #[inline]
1159          fn assemble(
1160            __row: &'__ingraph #row,
1161            __ingraph_under: ::core::option::Option<&#path<'_>>,
1162          ) -> #result<Self> {
1163            #plain_column(__row, __ingraph_under)
1164          }
1165        }
1166      }
1167    }
1168  }
1169
1170  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
1171  /// them — the same rule and the same shape [`RecordModel`](crate::model::RecordModel)'s emission
1172  /// obeys.
1173  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
1174    let krate = &self.krate;
1175    let module = module.iter().map(|segment| format_ident!("{segment}"));
1176    let name = format_ident!("{name}");
1177    quote!(#krate::__private #(:: #module)* :: #name)
1178  }
1179
1180  /// The name type one namespace's word is carried as.
1181  fn name_type(&self, namespace: Namespace) -> proc_macro2::TokenStream {
1182    self.framework(&["name"], namespace.name_type())
1183  }
1184
1185  /// The refusal every parse into this vocabulary answers with.
1186  ///
1187  /// OPAQUE — a private unit field, so nothing outside the declaring module constructs one and
1188  /// nothing anywhere reads a detail out of it. What went wrong is already known at the call site:
1189  /// the text handed in names no variant, and there is no second way to fail.
1190  fn refusal(&self) -> proc_macro2::TokenStream {
1191    let vis = &self.vis;
1192    let name = &self.name;
1193    let error = self.error();
1194    let sentence = format!("`{name}`: no variant answers to this name");
1195    let doc = format!(
1196      "The refusal a text that names no variant of [`{name}`] gets.\n\nOpaque: it carries no \
1197       detail, because there is only one way to fail — the word is not one of this vocabulary's."
1198    );
1199    // Every std name QUALIFIED, derive macros included — an expansion lands in a module the
1200    // framework does not control, and a bare `Debug` there resolves to whatever that module wrote.
1201    // This block was the one place in the emitter that still spelled them bare.
1202    quote! {
1203      #[doc = #doc]
1204      #[derive(
1205        ::core::fmt::Debug,
1206        ::core::clone::Clone,
1207        ::core::marker::Copy,
1208        ::core::cmp::PartialEq,
1209        ::core::cmp::Eq
1210      )]
1211      #vis struct #error(());
1212
1213      #[automatically_derived]
1214      impl ::core::fmt::Display for #error {
1215        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1216          ::core::fmt::Formatter::write_str(f, #sentence)
1217        }
1218      }
1219
1220      #[automatically_derived]
1221      impl ::core::error::Error for #error {}
1222    }
1223  }
1224
1225  /// The rows that say how a COLUMN of this type is READ: its filter, the interpretation a column
1226  /// inherits when it names no word, the interpretation a COLLECTION of it inherits, and the codec a
1227  /// keyset cursor pages past it with.
1228  ///
1229  /// All four are ungated framework rows. The first two are what makes a vocabulary filterable at
1230  /// all; the last is what the storability audit demands of every persisted column, since a page
1231  /// resumes by binding the last row's values back.
1232  ///
1233  /// # The `Vec` row, and the two positions it serves
1234  ///
1235  /// `DefaultVecMarker` is what every type the framework registers itself takes from `to_filter!`,
1236  /// and a declared vocabulary is as registerable as any of them — so a `Vec<TheirEnum>` naming no
1237  /// word had no default reading where a `Vec<i64>` had one. It is a LIST, which is `to_filter!`'s
1238  /// own default for every element that does not say otherwise, and a word on the field still beats
1239  /// it.
1240  ///
1241  /// It pays TWICE, and that is why it is emitted rather than left as a gap: the OUTPUT crossing
1242  /// reads its collection fork off this same row, so this one line is what gives a `Vec` of the
1243  /// vocabulary both a filter and a wire form. A second emitted row on an element-keyed output trait
1244  /// used to carry the output half; that trait is retired, and the fact it stated is this one.
1245  fn reading(&self) -> proc_macro2::TokenStream {
1246    let name = &self.name;
1247    let markers = self.markers();
1248    let cursor_value = self.framework(&["cursor"], "CursorValue");
1249    let canonical = self.canonical_map();
1250    quote! {
1251      #markers
1252
1253      // The CANONICAL word rather than the stored one, and it has to be: a cursor is minted by one
1254      // process and handed back to another, which may be talking to a different dialect — so the
1255      // codec belongs to the TYPE and cannot be per-backend, where a stored form now is. Its bytes
1256      // are checked coming back for the reason every row in that module checks its own: the bytes
1257      // are a client's.
1258      #[automatically_derived]
1259      impl #cursor_value for #name {
1260        fn write_cursor(&self, out: &mut ::std::vec::Vec<::core::primitive::u8>) {
1261          out.extend_from_slice(Self::as_str(self).as_bytes());
1262        }
1263
1264        fn read_cursor(bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
1265          match ::core::str::from_utf8(bytes) {
1266            ::core::result::Result::Ok(text) => #canonical(text),
1267            ::core::result::Result::Err(_) => ::core::option::Option::None,
1268          }
1269        }
1270      }
1271    }
1272  }
1273
1274  /// The three INTERPRETATION rows a vocabulary is filtered through, in either mode.
1275  ///
1276  /// What `to_filter!` writes for a type the framework itself registers, written here for a type it
1277  /// cannot see: the family the value is read under, the filter that family carries, and what a
1278  /// `Vec` of it means. A MIRROR earns them unchanged — its operand is a variant set whichever crate
1279  /// declared the vocabulary, so the reading is the same one and only the WORDS come from elsewhere.
1280  fn markers(&self) -> proc_macro2::TokenStream {
1281    let name = &self.name;
1282    let filter_marker = self.framework(&["marker"], "EnumFilterMarker");
1283    let filter = self.framework(&["graphql"], "EnumFilter");
1284    let default_marker = self.framework(&["marker"], "DefaultMarker");
1285    let default_vec_marker = self.framework(&["marker"], "DefaultVecMarker");
1286    let list_marker = self.framework(&["marker"], "ListMarker");
1287    let marker = self.framework(&["marker"], "EnumMarker");
1288    quote! {
1289      #[automatically_derived]
1290      impl #filter_marker for #name {
1291        type Filter = #filter<#name>;
1292      }
1293
1294      #[automatically_derived]
1295      impl #default_marker for #name {
1296        type Marker = #marker<#name>;
1297      }
1298
1299      #[automatically_derived]
1300      impl #default_vec_marker for #name {
1301        type Marker = #list_marker<::std::vec::Vec<#name>, #marker<#name>>;
1302      }
1303    }
1304  }
1305
1306  /// The METHOD face: the variant list, the predicates, the canonical word and one accessor per
1307  /// text namespace.
1308  ///
1309  /// Hand-emitted rather than derived. What a `derive_more` would bring is a foreign crate path in
1310  /// somebody's expanded code and a foreign error type in the signatures — and the vocabulary is the
1311  /// one kind whose whole content is its own names, so the family is written here and the paths are
1312  /// this emitter's.
1313  fn face(&self) -> proc_macro2::TokenStream {
1314    let vis = &self.vis;
1315    let name = &self.name;
1316    let variants = self.variants.iter().map(|variant| {
1317      let variant = &variant.ident;
1318      quote!(Self::#variant)
1319    });
1320    let predicates = self.variants.iter().map(|variant| {
1321      let ident = &variant.ident;
1322      let predicate = variant.predicate();
1323      let doc = format!("Whether this is [`{name}::{ident}`].");
1324      quote! {
1325        #[doc = #doc]
1326        #[inline]
1327        #[must_use]
1328        #vis const fn #predicate(&self) -> ::core::primitive::bool {
1329          ::core::matches!(self, Self::#ident)
1330        }
1331      }
1332    });
1333    let canonical = self.arms(|variant| {
1334      let word = variant.canonical();
1335      quote!(#word)
1336    });
1337    let accessors = Namespace::ALL
1338      .into_iter()
1339      .filter(|namespace| self.form(*namespace) == StorageForm::Text)
1340      .map(|namespace| self.accessor(namespace));
1341    let variants_doc = format!(
1342      "Every variant of [`{name}`], in DECLARATION order.\n\nThe order is the declaration's, so a \
1343       schema rendered from this reads as the enum does."
1344    );
1345    let canonical_doc = format!(
1346      "This variant's CANONICAL word — its global `rename`, else the name [`{name}`] spells it \
1347       with.\n\nThe namespace [`FromStr`](core::str::FromStr) parses, and the one every face \
1348       defaults from."
1349    );
1350    quote! {
1351      #[automatically_derived]
1352      impl #name {
1353        #[doc = #variants_doc]
1354        #vis const VARIANTS: &'static [Self] = &[#(#variants),*];
1355
1356        #[doc = #canonical_doc]
1357        #[inline]
1358        #[must_use]
1359        #vis const fn as_str(&self) -> &'static ::core::primitive::str {
1360          match self { #canonical }
1361        }
1362
1363        #(#accessors)*
1364
1365        #(#predicates)*
1366      }
1367    }
1368  }
1369
1370  /// One namespace's accessor, handing back ITS name type.
1371  ///
1372  /// A TEXT face only. An integer face has no word for a name type to hold, so the method is absent
1373  /// rather than answering with the discriminant's rendering — the form decides the face, and a
1374  /// caller asking a machine-facing backend for a name is asking for something that is not there.
1375  fn accessor(&self, namespace: Namespace) -> proc_macro2::TokenStream {
1376    let vis = &self.vis;
1377    let accessor = namespace.accessor();
1378    let name_type = self.name_type(namespace);
1379    let arms = self.arms(|variant| {
1380      let word = variant.name(namespace);
1381      quote!(#word)
1382    });
1383    let doc = format!(
1384      "This variant's word in the `{}` namespace.\n\nPresent because that face takes the TEXT \
1385       form; a face storing the discriminant has none.",
1386      namespace.as_str()
1387    );
1388    quote! {
1389      #[doc = #doc]
1390      #[inline]
1391      #[must_use]
1392      #vis const fn #accessor(&self) -> &'static #name_type {
1393        #name_type::new(match self { #arms })
1394      }
1395    }
1396  }
1397
1398  /// The PARSING half of the face: `FromStr` over the canonical namespace, and one
1399  /// `TryFrom<&…Name>` per text namespace.
1400  ///
1401  /// One impl per namespace and no coherence collision between them, which is the whole reason the
1402  /// names are types: `TryFrom<&str>` could be written once and would have to pick a face.
1403  fn parsing(&self) -> proc_macro2::TokenStream {
1404    let name = &self.name;
1405    let error = self.error();
1406    let canonical = self.canonical_map();
1407    let canonical_map = self.reverse_map(&canonical, EnumVariant::canonical);
1408    let texts: Vec<Namespace> = Namespace::ALL
1409      .into_iter()
1410      .filter(|namespace| self.form(*namespace) == StorageForm::Text)
1411      .collect();
1412    let maps = texts.iter().map(|namespace| {
1413      self.reverse_map(&self.reader(*namespace), |variant| variant.name(*namespace))
1414    });
1415    let conversions = texts.iter().map(|namespace| self.conversion(*namespace));
1416    quote! {
1417      #canonical_map
1418      #(#maps)*
1419
1420      #[automatically_derived]
1421      impl ::core::str::FromStr for #name {
1422        type Err = #error;
1423
1424        fn from_str(text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
1425          match #canonical(text) {
1426            ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
1427            ::core::option::Option::None => ::core::result::Result::Err(#error(())),
1428          }
1429        }
1430      }
1431
1432      #(#conversions)*
1433    }
1434  }
1435
1436  /// One namespace's conversion, over a BORROW of its name type.
1437  ///
1438  /// The reference is not a choice: a name type is a `#[repr(transparent)]` view of a `str` and
1439  /// therefore unsized, where `TryFrom`'s type parameter carries an implicit `Sized` bound. It also
1440  /// costs nothing — every reader of one of these already holds a borrow, `new` handing back a
1441  /// `&Self` and the accessor above a `&'static Self`.
1442  ///
1443  /// The word reaches the map through the `Deref` coercion, at an argument position whose type is
1444  /// known — which is how every reader of one of these takes it.
1445  fn conversion(&self, namespace: Namespace) -> proc_macro2::TokenStream {
1446    let name = &self.name;
1447    let error = self.error();
1448    let name_type = self.name_type(namespace);
1449    let reader = self.reader(namespace);
1450    quote! {
1451      #[automatically_derived]
1452      impl ::core::convert::TryFrom<&#name_type> for #name {
1453        type Error = #error;
1454
1455        fn try_from(name: &#name_type) -> ::core::result::Result<Self, Self::Error> {
1456          match #reader(name) {
1457            ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
1458            ::core::option::Option::None => ::core::result::Result::Err(#error(())),
1459          }
1460        }
1461      }
1462    }
1463  }
1464
1465  /// The reverse map for the CANONICAL namespace — what `FromStr` and the cursor both read through.
1466  fn canonical_map(&self) -> syn::Ident {
1467    format_ident!("__ingraph_of_canonical")
1468  }
1469
1470  /// The reverse map for ONE namespace — what its conversion and, where that namespace stores text,
1471  /// its `Decode` both read through.
1472  fn reader(&self, namespace: Namespace) -> syn::Ident {
1473    format_ident!("__ingraph_of_{}", namespace.as_str())
1474  }
1475
1476  /// One word-to-variant map, written ONCE per namespace and called from every reader of it.
1477  ///
1478  /// Two readers of one namespace with a `match` each is two tables that can come to disagree, and
1479  /// the disagreement is invisible: each is correct in isolation, and what breaks is only the pair.
1480  ///
1481  /// A `match` on the words rather than a chain of comparisons, so two variants sharing a word in
1482  /// one namespace would be an `unreachable_patterns` warning at the declaration — the parser
1483  /// refuses that case outright, and this is what would catch a front end that did not.
1484  fn reverse_map(
1485    &self,
1486    reader: &syn::Ident,
1487    of: impl Fn(&EnumVariant) -> String,
1488  ) -> proc_macro2::TokenStream {
1489    let name = &self.name;
1490    let arms = self.variants.iter().map(|variant| {
1491      let ident = &variant.ident;
1492      let word = of(variant);
1493      quote!(#word => ::core::option::Option::Some(#name::#ident),)
1494    });
1495    quote! {
1496      fn #reader(text: &::core::primitive::str) -> ::core::option::Option<#name> {
1497        match text {
1498          #(#arms)*
1499          _ => ::core::option::Option::None,
1500        }
1501      }
1502    }
1503  }
1504
1505  /// One arm per variant, `Self::V => <what>`.
1506  fn arms(
1507    &self,
1508    of: impl Fn(&EnumVariant) -> proc_macro2::TokenStream,
1509  ) -> proc_macro2::TokenStream {
1510    let arms = self.variants.iter().map(|variant| {
1511      let ident = &variant.ident;
1512      let value = of(variant);
1513      quote!(Self::#ident => #value,)
1514    });
1515    quote!(#(#arms)*)
1516  }
1517
1518  /// One backend's four storage rows, behind its gate — or nothing, where the backend stores no
1519  /// vocabulary yet.
1520  fn storage_rows(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
1521    let Some(namespace) = Namespace::ALL
1522      .into_iter()
1523      .find(|namespace| namespace.database() == Some(database))
1524    else {
1525      return quote!();
1526    };
1527    if !database.is_sql() {
1528      // MongoDB, whose row has a design and no lane — see the module note. Its NAMESPACE is emitted
1529      // above with the others, which is what a hand-written `MongoCarrier` is written in terms of.
1530      return quote!();
1531    }
1532
1533    let name = &self.name;
1534    let gate = self.framework(&["gate"], &database.gate().to_string());
1535    let backend = self.backend(database);
1536    let carrier = self.framework(&["comparison", "sql"], "Carrier");
1537    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
1538    let sqlx_type = self.framework(&["sqlx"], "Type");
1539    let encode = self.framework(&["sqlx"], "Encode");
1540    let decode = self.framework(&["sqlx"], "Decode");
1541    let database_trait = self.framework(&["sqlx"], "Database");
1542    let is_null = self.framework(&["sqlx", "encode"], "IsNull");
1543    let error = self.framework(&["sqlx", "error"], "BoxDynError");
1544
1545    // The WORD a `CREATE TABLE` declares this column with, asked of the form this backend stores —
1546    // one road for both forms and no word spelled here. `String` rather than `str` for the text
1547    // arm: `str` answers a WIDTH and nothing else and has no `StoredAs` row by design, where the
1548    // owned form is what every dialect's text column is declared as. See `StoredAs`, where the
1549    // spelling law is.
1550    let stored_as = self.framework(&["column"], "StoredAs");
1551    let (stored, borrowed, maps, bind, of_stored, refused, declared) = match self.form(namespace) {
1552      StorageForm::Text => {
1553        let accessor = namespace.accessor();
1554        let reader = self.reader(namespace);
1555        (
1556          quote!(::core::primitive::str),
1557          // The bind is the BORROWED view of a `&'static str`, never an owned copy: `push_bind`
1558          // takes its lifetime free, so a static needs no allocation to reach a query. It is the
1559          // bargain `borrowed_carriers!` already makes for `String`.
1560          quote!(&'__ingraph ::core::primitive::str),
1561          quote!(),
1562          // Both directions reach the FACE's own tables rather than a second pair written here: the
1563          // word this backend stores IS the word its accessor hands out and its conversion reads,
1564          // and two matches over one namespace are two things that can come to disagree.
1565          //
1566          // The typed `let` is what takes the accessor's `&'static <Face>Name` down to the `&str`
1567          // sqlx binds — a name is a `#[repr(transparent)]` view, so this is the `Deref` coercion
1568          // and not a conversion. It is written out because `push_bind` INFERS its parameter, which
1569          // is the one position on this path where a coercion has no expected type to fire against.
1570          quote!({
1571            let stored: &'static ::core::primitive::str = #name::#accessor(self);
1572            stored
1573          }),
1574          quote!(#reader(stored)),
1575          format!("{name}: the stored text names no variant of this enum"),
1576          quote!(::std::string::String),
1577        )
1578      }
1579      StorageForm::Integer => {
1580        let width = self.width().wire(database);
1581        let primitive = format_ident!("{}", width.as_str());
1582        let stored_fn = format_ident!("__ingraph_{}_stored", namespace.as_str());
1583        let of_stored_fn = format_ident!("__ingraph_{}_of_stored", namespace.as_str());
1584        (
1585          quote!(::core::primitive::#primitive),
1586          quote!(::core::primitive::#primitive),
1587          self.integer_maps(&stored_fn, &of_stored_fn, &primitive),
1588          quote!(#stored_fn(self)),
1589          quote!(#of_stored_fn(stored)),
1590          format!("{name}: the stored discriminant names no variant of this enum"),
1591          quote!(::core::primitive::#primitive),
1592        )
1593      }
1594    };
1595
1596    quote! {
1597      #gate! {
1598        #maps
1599
1600        #[automatically_derived]
1601        impl #sqlx_type<#backend> for #name {
1602          fn type_info() -> <#backend as #database_trait>::TypeInfo {
1603            <#stored as #sqlx_type<#backend>>::type_info()
1604          }
1605
1606          fn compatible(ty: &<#backend as #database_trait>::TypeInfo) -> ::core::primitive::bool {
1607            <#stored as #sqlx_type<#backend>>::compatible(ty)
1608          }
1609        }
1610
1611        // Only `encode_by_ref` is written. `produces` is the per-VALUE type override and
1612        // `size_hint` the buffer estimate, and the stored form answers both from its own impl
1613        // already — there is no vocabulary-level answer either could carry that would differ.
1614        #[automatically_derived]
1615        impl<'__ingraph> #encode<'__ingraph, #backend> for #name {
1616          fn encode_by_ref(
1617            &self,
1618            buf: &mut <#backend as #database_trait>::ArgumentBuffer,
1619          ) -> ::core::result::Result<#is_null, #error> {
1620            <#borrowed as #encode<'__ingraph, #backend>>::encode(#bind, buf)
1621          }
1622        }
1623
1624        #[automatically_derived]
1625        impl<'__ingraph> #decode<'__ingraph, #backend> for #name {
1626          fn decode(
1627            value: <#backend as #database_trait>::ValueRef<'__ingraph>,
1628          ) -> ::core::result::Result<Self, #error> {
1629            let stored = <#borrowed as #decode<'__ingraph, #backend>>::decode(value)?;
1630            match #of_stored {
1631              ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
1632              // A static message rather than one quoting the stored value: the row that would
1633              // interpolate it is the one holding a value the schema says should not be there, and
1634              // this crate has no format machinery on the shelf to render it with.
1635              ::core::option::Option::None => ::core::result::Result::Err(#error::from(#refused)),
1636            }
1637          }
1638        }
1639
1640        // The FOURTH face, beside the width above and the three crossings here: what a
1641        // `CREATE TABLE` declares this column as. It is the STORED FORM's own word rather than one
1642        // chosen here — a text-stored enum is declared exactly as a `String` column and an
1643        // integer-stored one exactly as its width — so a vocabulary that changes form changes its
1644        // declaration with it and neither can be moved alone.
1645        //
1646        // Per DATABASE and inside this gate, where the width row above is one impl over every
1647        // dialect: a width is not a dialect's fact and a WORD is nothing else.
1648        #[automatically_derived]
1649        impl #stored_as<#backend> for #name {
1650          const WORDS: &'static [&'static ::core::primitive::str] =
1651            <#declared as #stored_as<#backend>>::WORDS;
1652        }
1653
1654        #[automatically_derived]
1655        impl #carrier<#backend> for #name {
1656          fn push_bind(&self, qb: &mut #query_builder<#backend>) {
1657            qb.push_bind(#bind);
1658          }
1659        }
1660      }
1661    }
1662  }
1663
1664  /// The CONCRETE backend type one database is.
1665  ///
1666  /// The one place a vocabulary's emission names a backend, and what buys the exception is the gate
1667  /// around it — the same trade [`DatabaseBackend::vocabulary`](crate::emit) makes for a record's
1668  /// storability audit, and for the same reason: a concrete impl is where a column's crossing is
1669  /// actually checked.
1670  fn backend(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
1671    match database {
1672      DatabaseKind::Sqlite => self.framework(&["sqlx"], "Sqlite"),
1673      DatabaseKind::Postgres => self.framework(&["sqlx"], "Postgres"),
1674      DatabaseKind::Mysql => self.framework(&["sqlx"], "MySql"),
1675      DatabaseKind::Mongo => self.framework(&["comparison", "mongo"], "Mongo"),
1676    }
1677  }
1678
1679  /// Both directions of the INTEGER form, at the width this backend binds.
1680  ///
1681  /// Every arm casts the VARIANT rather than the matched value, which is what keeps the
1682  /// declaration's own `= 9` authoritative: `Grade::High as u8` is the discriminant the declaration
1683  /// wrote, where a literal written here would be a second numbering free to disagree with it.
1684  /// Casting the variant PATH rather than `*value` is also what keeps the emission from requiring
1685  /// [`Copy`]. The cast is exact by construction — the width is the declaration's `#[repr(…)]`, or
1686  /// wider where the dialect has no such type.
1687  ///
1688  /// The reverse uses guards rather than patterns, because `Grade::High as u8` is a constant
1689  /// EXPRESSION and not a pattern. Nothing is lost to first-wins: rustc already refuses an enum
1690  /// whose two variants share a discriminant.
1691  fn integer_maps(
1692    &self,
1693    stored: &syn::Ident,
1694    of_stored: &syn::Ident,
1695    primitive: &syn::Ident,
1696  ) -> proc_macro2::TokenStream {
1697    let name = &self.name;
1698    let forward = self.variants.iter().map(|variant| {
1699      let ident = &variant.ident;
1700      quote!(#name::#ident => #name::#ident as ::core::primitive::#primitive)
1701    });
1702    let reverse = self.variants.iter().map(|variant| {
1703      let ident = &variant.ident;
1704      quote! {
1705        value if value == #name::#ident as ::core::primitive::#primitive => {
1706          ::core::option::Option::Some(#name::#ident)
1707        }
1708      }
1709    });
1710    quote! {
1711      fn #stored(value: &#name) -> ::core::primitive::#primitive {
1712        match value {
1713          #(#forward,)*
1714        }
1715      }
1716
1717      fn #of_stored(
1718        value: ::core::primitive::#primitive,
1719      ) -> ::core::option::Option<#name> {
1720        match value {
1721          #(#reverse,)*
1722          _ => ::core::option::Option::None,
1723        }
1724      }
1725    }
1726  }
1727}