ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! The FLAGS face: what a `#[ingraph::flags(u32)]` declaration expands into.
//!
//! A flags set is the VOCABULARY's sister and not a new universe. Both are a closed set of names a
//! declaration writes down; what differs is the arity of an answer — an enum column holds one of the
//! names and a flags column holds a subset. So the two share a shape at every layer, and where this
//! module departs from [`enumeration`](crate::enumeration) it is because that arity forced it.
//!
//! # The declaration is an ENUM and the expansion is a STRUCT, and that is a REWRITE
//!
//! ```ignore
//! #[ingraph::flags(u32)]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum TrackDisposition {
//!   /// The default track for its kind.
//!   Default = 0x1,
//!   Forced = 0x2,
//!   HearingImpaired = 0x4,
//! }
//! ```
//!
//! becomes a `bitflags!` struct with `TrackDisposition::DEFAULT`, `::FORCED` and
//! `::HEARING_IMPAIRED` on it. Three things are being asserted there and each was chosen against an
//! alternative:
//!
//! - **An ATTRIBUTE and not a derive.** A derive may only APPEND, and the flags type is MINTED by
//!   `bitflags!` rather than written by the author — so nothing but an attribute can be the door.
//!   That is the same rewrite criterion the tree already applies elsewhere.
//! - **The manifest is an `enum`**, because a declaration face is a set of NAMES with values and
//!   Rust has exactly one item that spells that. A struct body cannot hold `NAME = 0x1`, and a unit
//!   struct with the bits in the attribute would put the vocabulary somewhere a doc comment cannot
//!   reach. Writing the vocabulary as an enum is also what makes the two kinds READ as sisters: the
//!   word above the declaration is the whole difference between *one of these* and *a set of these*.
//! - **The bits are the DISCRIMINANTS**, explicit and never inferred. A flags value is somebody's
//!   stored integer, so an automatic numbering would mean that reordering the declaration rewrites
//!   every row — and reordering a list of names is the most ordinary edit there is. Auto-numbering
//!   is therefore refused rather than defaulted, which is the one place this kind is STRICTER than
//!   the vocabulary it mirrors.
//!
//! The manifest's own lints never fire, because the manifest does not survive: an attribute macro
//! replaces the item, so `Default` and `HearingImpaired` are read as bit NAMES here and are gone
//! before rustc has an enum to have an opinion about.
//!
//! # `#[ingraph::flags(…)]` GOES ABOVE THE DERIVES, and the order is load-bearing
//!
//! ```ignore
//! #[ingraph::flags(u32)]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum TrackDisposition { … }
//! ```
//!
//! rustc expands the TOPMOST attribute on an item first, and `derive` takes its turn in that same
//! order. A derive written above this word therefore expands against the MANIFEST — the enum that is
//! about to stop existing — and lands a `Debug` impl matching on `TrackDisposition::Default`, a
//! variant the expansion replaced with a const. The error a reader gets says *no associated
//! function or constant named `Default` found for struct*, which is true and unhelpful.
//!
//! Written above, this word expands first, and the derives it forwards land on the type
//! `bitflags!` mints. It is the ordinary hazard of every rewriting attribute and it cannot be
//! detected here: by the time this door runs, a derive that already expanded is gone from the
//! item's attributes and is indistinguishable from one nobody wrote.
//!
//! # One word, three casings, one table
//!
//! `HearingImpaired` in the manifest gives the const `HEARING_IMPAIRED`, the wire word
//! `HEARING_IMPAIRED`, and the GraphQL field `hearingImpaired`. The const and the word are the SAME
//! string — which is what lets the strict text form be `bitflags::parser::to_writer` itself rather
//! than a renderer written here that could come to disagree with it — and the field is that word
//! under the one casing GraphQL's own convention asks for. `#[ingraph(rename = "…")]` moves the
//! word, and the field follows it, because they are two readings of one declaration rather than two
//! declarations.
//!
//! # Storage is the BACKING INTEGER, always
//!
//! There is no `text`/`integer` fork here and no per-face block, where a vocabulary has both. A
//! flags column is stored as its bit pattern because the mask questions are ARITHMETIC on that
//! pattern: `hasAll` is `(col & m) = m`, which a text column cannot answer at all. So the only face
//! with words is the wire, one `rename` covers it, and the whole namespace apparatus a vocabulary
//! needs is absent rather than defaulted.
//!
//! The width is the DECLARATION's — `flags(u32)` is a `u32` column — through the same house carrier
//! table a vocabulary's `#[repr(…)]` goes through, so a Postgres column widens to `BIGINT` exactly
//! as an enum's `u32` discriminant does.
//!
//! # The set of rows
//!
//! | impl | who demands it | gated |
//! |---|---|---|
//! | `FlagsValue` | every wire face — it carries the SDL name and the bit table | no |
//! | `FlagsFilterMarker` | the column's FILTER — `FlagsMarker<T>` resolves through it | no |
//! | `DefaultMarker`, `DefaultVecMarker` | the INFERENCE, so a column needs no word to be read | no |
//! | `CursorValue` | the KEYSET cursor, which every persisted column is audited for | no |
//! | `ColumnKind`, `Assemble` | the column's width and how a row reads one back | the family |
//! | `sqlx::Type`/`Decode`/`Encode`, `Carrier` | the storage binding and the lowering's operand | per backend |
//! | `ToGraphqlOutput`, `ToGraphqlInput` | the two wire SEATS | the binding |
//!
//! The wire face itself is NOT here, and that is the biggest saving over the vocabulary kind: an
//! enum's `InputType`/`OutputType` are emitted per declaration because a GraphQL enum's values are
//! its own, where a flags type's whole face is generic over `FlagsValue` in `ingraph` and reads the
//! bit table at runtime. So a declaration emits two crossing rows and the framework does the rest.

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

use crate::{enumeration::IntegerWidth, model::DatabaseKind};

mod remote;
#[cfg(test)]
mod tests;

/// The widths a flags set may be declared at.
///
/// UNSIGNED ONLY, and the exclusion is two arguments rather than a preference.
///
/// - The 64-bit and 128-bit widths are absent for the house carrier table's reason, which
///   [`IntegerWidth`] already states: MySQL alone has a native `u64`, no dialect carries a 128-bit
///   integer, and a column has to be storable in every dialect a declaration might reach.
/// - The SIGNED widths are absent because a flag is a BIT and a sign bit is not one. `i8`'s top bit
///   is `-128`, which no declaration would write as an explicit positive value, so the widths that
///   admit it would admit exactly one bit nobody can spell — and the arithmetic every mask word
///   rests on is defined on the unsigned reading.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BitWidth {
  /// `u8` — eight flags.
  U8,
  /// `u16` — sixteen.
  U16,
  /// `u32` — thirty-two.
  U32,
}

impl BitWidth {
  /// Every width, in the order a refusal lists them.
  pub const ALL: [Self; 3] = [Self::U8, Self::U16, Self::U32];

  /// The primitive this width is.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::U8 => "u8",
      Self::U16 => "u16",
      Self::U32 => "u32",
    }
  }

  /// The width this word names, when it is one this kind carries.
  pub fn named(word: &str) -> Option<Self> {
    Self::ALL.into_iter().find(|width| width.as_str() == word)
  }

  /// How many bits a declaration may number, which is also one past the highest legal one.
  pub const fn count(self) -> u32 {
    match self {
      Self::U8 => 8,
      Self::U16 => 16,
      Self::U32 => 32,
    }
  }

  /// The largest value this width holds.
  pub const fn ceiling(self) -> u128 {
    (1u128 << self.count()) - 1
  }

  /// This width on the framework's own carrier table, which is where the per-dialect widening
  /// lives.
  ///
  /// The vocabulary kind's table, spent unchanged: a flags column and an enum column storing the
  /// same width are the same column, so a second widening rule here would be a second answer to a
  /// question already settled.
  pub const fn carried(self) -> IntegerWidth {
    match self {
      Self::U8 => IntegerWidth::U8,
      Self::U16 => IntegerWidth::U16,
      Self::U32 => IntegerWidth::U32,
    }
  }

  /// The primitive one database actually binds — this width, widened where that dialect has no such
  /// type.
  pub const fn stored(self, database: DatabaseKind) -> IntegerWidth {
    self.carried().wire(database)
  }
}

/// One declared bit.
#[derive(Debug, Clone)]
pub struct FlagBit {
  /// The bit as the MANIFEST spells it — the enum variant's own identifier.
  pub ident: syn::Ident,
  /// `rename = "…"` in the DECLARED mode, which moves the word every face spells this bit with.
  ///
  /// A mirror's `rename` fills [`upstream`](Self::upstream) instead, the two knobs being one word
  /// reading two ways: see that field for why a restatement has no word of its own to move.
  pub rename: Option<String>,
  /// `rename = "…"` in the MIRROR mode — the upstream `const` this bit restates.
  ///
  /// A mirror's words are its OWN, where a mirrored vocabulary's are the upstream's, and the
  /// asymmetry is the arity again: a flags set stores a bit PATTERN, so the mirrored type's text
  /// form is read off this crate's bit table and never off the upstream's. What a restatement can
  /// get wrong is therefore not a word but a NUMBER, and the upstream `const` is what the drift pin
  /// compares against.
  pub upstream: Option<syn::Ident>,
  /// The bit's value, evaluated.
  pub value: u128,
  /// The declaration's own non-`ingraph` attributes, forwarded onto the emitted `const` in order —
  /// which is what carries a bit's doc comment into the expansion.
  pub attrs: Vec<syn::Attribute>,
}

impl FlagBit {
  /// The WORD this bit is spelled with: its `rename`, else its identifier SHOUTED.
  ///
  /// One string serving three seats — the emitted `const`'s name, the strict text form's token, and
  /// the wire's name-list entry — which is what keeps `bitflags::parser::to_writer` usable as the
  /// text renderer instead of a second one written here.
  ///
  /// The shout is a Rust CONVENTION rather than a stored-word decision, which is why this kind cases
  /// where a vocabulary's stored word is verbatim: an associated const is `SCREAMING_SNAKE_CASE`
  /// everywhere in the ecosystem, and a flags column stores no word at all for a casing rule to
  /// rewrite.
  pub fn word(&self) -> String {
    self
      .rename
      .clone()
      .unwrap_or_else(|| self.ident.unraw().to_string().to_shouty_snake_case())
  }

  /// The wire FIELD this bit takes — its word, under GraphQL's own casing.
  ///
  /// Derived from [`word`](Self::word) rather than from the identifier, so a `rename` moves both and
  /// they stay two readings of one declaration.
  pub fn field(&self) -> String {
    self.word().to_lower_camel_case()
  }

  /// The `const`'s name in the expansion — [`word`](Self::word) as an identifier.
  pub fn constant(&self) -> syn::Ident {
    format_ident!("{}", self.word())
  }

  /// The UPSTREAM `const` a mirror's bit restates — the declared `rename`, else this bit's own
  /// [`constant`](Self::constant).
  ///
  /// The drift pin is written from this, so a name that answers to nothing upstream is `E0599` at
  /// the token that named it. That is the whole enforcement and it is the compiler's: this side
  /// cannot see the upstream declaration, and a table of upstream names kept here would be a second
  /// copy of somebody else's `bitflags!`.
  pub fn upstream(&self) -> syn::Ident {
    self.upstream.clone().unwrap_or_else(|| self.constant())
  }
}

/// One flags declaration, validated.
///
/// Public fields for [`EnumModel`](crate::enumeration::EnumModel)'s reason: nothing here parses, so
/// a front end that is not the attribute builds the same struct and reaches the same emitter.
#[derive(Debug, Clone)]
pub struct FlagsModel {
  /// Where `ingraph` lives, for the shelf every emitted path is rooted at.
  pub krate: syn::Path,
  /// The declaration's visibility, which the emitted struct takes.
  pub vis: syn::Visibility,
  /// The declared type's own name.
  pub name: syn::Ident,
  /// The width the bits are stored at.
  pub width: BitWidth,
  /// The bits, in declaration order. Never empty.
  pub bits: Vec<FlagBit>,
  /// The declaration's own non-`ingraph` attributes, forwarded onto the emitted struct in order.
  ///
  /// This is how `#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]` reaches the type `bitflags!`
  /// mints. It is not added for the author, for the vocabulary kind's reason: a derive this door
  /// injected would collide with one the author wrote, and the bound that actually needs it reports
  /// `E0277` naming the trait at the type.
  pub attrs: Vec<syn::Attribute>,
  /// `remote = "…"` — the upstream flags set this declaration RESTATES, where it restates one.
  ///
  /// `None` is the ordinary declaration and the emission is untouched by this axis, down to the
  /// token: the mirror is written last and adds to what a declared set already emits rather than
  /// forking it. See [`remote`](self::remote) for the whole of what the word buys.
  pub remote: Option<syn::Path>,
  /// `graphql(rename = "…")` — what a SCHEMA calls this flags set, where the declaration moved it.
  ///
  /// `None` is the Rust name unraw'd, which is what [`FlagsModel::sdl_name`] resolves. EMISSION-ONLY,
  /// for [`EnumModel`](crate::enumeration::EnumModel)'s reason: the `bitflags!` type keeps its name,
  /// every bit keeps its `const`, and a stored bit pattern has no word for this to move.
  pub wire_name: Option<String>,
}

impl FlagsModel {
  /// The name a SCHEMA publishes this type under — the declaration's
  /// [`wire_name`](Self::wire_name), else the Rust name unraw'd.
  ///
  /// **THE ONE HOME OF THIS KIND'S WHOLE SDL FAMILY.** Three published names are built off this
  /// string and none of them is spelled twice: the OBJECT face takes it verbatim, the operand SCALAR
  /// is `<it>Input` and the filter input object is `<it>Filter`, each composed where it is registered
  /// rather than here. So one word moves the family and the three cannot come to disagree — which is
  /// the same property the derivation was built for before there was a word to move it.
  ///
  /// The knob arrived with the rename-parity ruling, replacing this function's own
  /// *no rename knob, for `EnumModel`'s reason* — and the two names moved together, as the sentence
  /// promised they would.
  #[must_use]
  pub fn sdl_name(&self) -> String {
    self
      .wire_name
      .clone()
      .unwrap_or_else(|| self.name.unraw().to_string())
  }

  /// The whole expansion: the `bitflags!` type, then the rows, then the two wire seats — and, for a
  /// MIRROR, the crossing to its upstream behind all of it.
  ///
  /// # The mirror is an ADDITION and never a fork
  ///
  /// A mirrored flags set is a flags set: it mints its own `bitflags!` type, stores its own bit
  /// pattern, publishes its own object face and reads its own bit table. So `remote = "…"` buys
  /// [one more block](self::remote) at the END of the expansion and moves nothing in front of it —
  /// which is what makes a declaration naming no upstream emit exactly what it emitted before the
  /// axis existed, token for token, and is why there is no second emitter to keep in step with this
  /// one.
  ///
  /// That is the whole of where this kind departs from the vocabulary's mirror mode, and the arity
  /// is the reason: an enum mirror DELEGATES its words to the upstream's `Display`, so its emission
  /// really is a second one; a flags mirror delegates nothing, because a bit pattern is the same
  /// number on both sides of the crossing.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let declaration = self.declaration();
    let vocabulary = self.vocabulary();
    let reading = self.reading();
    let width = self.width_row();
    let read = self.read_row();
    let storage = DatabaseKind::ALL
      .into_iter()
      .map(|database| self.storage_rows(database));
    let wire = self.wire_seats();
    let mirror = self.remote.as_ref().map(|path| self.mirror(path));
    quote! {
      #declaration

      const _: () = {
        #vocabulary
        #reading
        #width
        #read
        #(#storage)*
      };

      #wire

      #mirror
    }
  }

  /// The TYPE — one `bitflags!` invocation, reached through the shelf.
  ///
  /// The author's own attributes ride in front of it in the order they were written, which is the
  /// attribute family's forwarding law: what an author wrote about their type stays true of the type
  /// the door mints. `bitflags!` passes them through to the public struct verbatim.
  fn declaration(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let vis = &self.vis;
    let name = &self.name;
    let attrs = &self.attrs;
    let primitive = format_ident!("{}", self.width.as_str());
    let bits = self.bits.iter().map(|bit| {
      let attrs = &bit.attrs;
      let constant = bit.constant();
      // The bit as a SUFFIXED HEX literal — hex because that is how a bit is written, and
      // suffixed so the `const` takes the declared width rather than an inferred one.
      let value = syn::LitInt::new(
        &format!("0x{:x}{}", bit.value, self.width.as_str()),
        proc_macro2::Span::call_site(),
      );
      quote! {
        #(#attrs)*
        const #constant = #value;
      }
    });
    quote! {
      #krate::__private::bitflags::bitflags! {
        #(#attrs)*
        #vis struct #name: ::core::primitive::#primitive {
          #(#bits)*
        }
      }
    }
  }

  /// The VOCABULARY row — the SDL name and the wire field per bit, which is the whole of what the
  /// generic faces need that `bitflags::Flags` does not already carry.
  ///
  /// The field list is emitted PARALLEL to the bit list rather than as pairs, because the first of
  /// the two lives in the vendored trait and this crate cannot add a column to it. Both come off one
  /// loop over one declaration, which is what makes the parallelism structural rather than a
  /// convention two emissions have to keep.
  fn vocabulary(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let trait_path = self.framework(&["flags"], "FlagsValue");
    let sdl = self.sdl_name();
    let fields = self.bits.iter().map(FlagBit::field);
    quote! {
      #[automatically_derived]
      impl #trait_path for #name {
        const GRAPHQL_NAME: &'static ::core::primitive::str = #sdl;
        const FIELDS: &'static [&'static ::core::primitive::str] = &[#(#fields),*];
      }
    }
  }

  /// The rows that say how a COLUMN of this type is READ: its filter, the interpretation a column
  /// and a collection of it inherit, and the codec a keyset cursor pages past it with.
  ///
  /// # The cursor carries the BITS, where a vocabulary's carries its word
  ///
  /// A cursor is minted by one process and handed back to another that may be talking to a different
  /// dialect, so its codec belongs to the TYPE and cannot be per-backend. For a vocabulary that
  /// forced the canonical WORD, because its stored form varies by face. A flags set stores the bit
  /// pattern in every face, so the pattern IS the type's own form and there is nothing to choose.
  ///
  /// Big-endian, which is this crate's byte order for every durable number, and the width is CHECKED
  /// coming back: a client's bytes are a client's, so four of them are not a `u32` unless they are
  /// exactly four, and the value they hold is refused unless every bit of it was declared.
  fn reading(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let filter_marker = self.framework(&["marker"], "FlagsFilterMarker");
    let filter = self.framework(&["graphql"], "FlagsFilter");
    let default_marker = self.framework(&["marker"], "DefaultMarker");
    let default_vec_marker = self.framework(&["marker"], "DefaultVecMarker");
    let list_marker = self.framework(&["marker"], "ListMarker");
    let marker = self.framework(&["marker"], "FlagsMarker");
    let cursor_value = self.framework(&["cursor"], "CursorValue");
    let primitive = format_ident!("{}", self.width.as_str());
    let bytes = (self.width.count() / 8) as usize;
    quote! {
      #[automatically_derived]
      impl #filter_marker for #name {
        type Filter = #filter<#name>;
      }

      #[automatically_derived]
      impl #default_marker for #name {
        type Marker = #marker<#name>;
      }

      #[automatically_derived]
      impl #default_vec_marker for #name {
        type Marker = #list_marker<::std::vec::Vec<#name>, #marker<#name>>;
      }

      #[automatically_derived]
      impl #cursor_value for #name {
        fn write_cursor(&self, out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          out.extend_from_slice(&::core::primitive::#primitive::to_be_bytes(
            #name::bits(self),
          ));
        }

        fn read_cursor(bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
          match <[::core::primitive::u8; #bytes] as ::core::convert::TryFrom<&[
            ::core::primitive::u8
          ]>>::try_from(bytes) {
            ::core::result::Result::Ok(fixed) => {
              #name::from_bits(::core::primitive::#primitive::from_be_bytes(fixed))
            }
            ::core::result::Result::Err(_) => ::core::option::Option::None,
          }
        }
      }
    }
  }

  /// This type's COLUMN WIDTH: one, whatever the dialect widens it to — and its SAMENESS, which is
  /// its bits'.
  fn width_row(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let column_kind = self.framework(&["column"], "ColumnKind");
    let column_eq = self.framework(&["column"], "ColumnEq");
    quote! {
      #[automatically_derived]
      impl #column_kind for #name {}

      // Two flag sets are one column value when their BITS are, which is what the `PartialEq` this
      // device already puts on the type says — see the `bitflags!` derive list. The row exists
      // because an emitted record row folds this face where it used to derive `PartialEq` over its
      // declared field types.
      #[automatically_derived]
      impl #column_eq for #name {
        #[inline]
        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
          ::core::cmp::PartialEq::eq(self, __ingraph_other)
        }
      }
    }
  }

  /// How a holder's row READS one of these back — [`EnumModel::read_row`]'s emission, unchanged,
  /// because what it states is a fact about being ONE column and a flags set is one.
  fn read_row(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let gate = self.framework(&["gate"], "if_sqlx");
    let assemble = self.framework(&["column"], "Assemble");
    let plain_column = self.framework(&["column"], "plain_column");
    let path = self.framework(&["comparison"], "Path");
    let row_trait = self.framework(&["sqlx"], "Row");
    let decode = self.framework(&["sqlx"], "Decode");
    let sqlx_type = self.framework(&["sqlx"], "Type");
    let column_index = self.framework(&["sqlx"], "ColumnIndex");
    let result = self.framework(&["sqlx"], "Result");
    let row = crate::emit::parameter("ROW");
    quote! {
      #gate! {
        #[automatically_derived]
        impl<'__ingraph, #row> #assemble<'__ingraph, #row> for #name
        where
          #row: #row_trait,
          #name: #decode<'__ingraph, <#row as #row_trait>::Database>
            + #sqlx_type<<#row as #row_trait>::Database>,
          for<'__ingraph_name> &'__ingraph_name ::core::primitive::str: #column_index<#row>,
        {
          #[inline]
          fn assemble(
            __row: &'__ingraph #row,
            __ingraph_under: ::core::option::Option<&#path<'_>>,
          ) -> #result<Self> {
            #plain_column(__row, __ingraph_under)
          }
        }
      }
    }
  }

  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
  /// them.
  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let module = module.iter().map(|segment| format_ident!("{segment}"));
    let name = format_ident!("{name}");
    quote!(#krate::__private #(:: #module)* :: #name)
  }

  /// One backend's four storage rows, behind its gate — or nothing, where the backend stores no
  /// flags column yet.
  ///
  /// MongoDB is absent for the reason the vocabulary kind's Mongo row is absent: the design exists —
  /// `MongoFlagsComparison` is written and its three mask words are the server's own — and what is
  /// missing is a lane in this workspace that could compile the carrier.
  fn storage_rows(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
    if !database.is_sql() {
      return quote!();
    }

    let name = &self.name;
    let gate = self.framework(&["gate"], &database.gate().to_string());
    let backend = self.backend(database);
    let carrier = self.framework(&["comparison", "sql"], "Carrier");
    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
    let sqlx_type = self.framework(&["sqlx"], "Type");
    let encode = self.framework(&["sqlx"], "Encode");
    let decode = self.framework(&["sqlx"], "Decode");
    let database_trait = self.framework(&["sqlx"], "Database");
    let is_null = self.framework(&["sqlx", "encode"], "IsNull");
    let error = self.framework(&["sqlx", "error"], "BoxDynError");

    let declared = format_ident!("{}", self.width.as_str());
    let stored = format_ident!("{}", self.width.stored(database).as_str());
    let too_wide =
      format!("{name}: the stored number does not fit the width this declaration is declared at");
    let undeclared = format!("{name}: the stored bits name a flag this declaration never declared");

    let stored_as = self.framework(&["column"], "StoredAs");

    quote! {
      #gate! {
        // The WORD this column is declared with — the STORED width's own, which is the width this
        // dialect actually holds the bits at rather than the one the declaration wrote. That is the
        // same table every crossing here reads: a `u32` set on a dialect with no unsigned type is
        // stored, encoded, decoded and DECLARED at the wider signed one, so all four move together.
        #[automatically_derived]
        impl #stored_as<#backend> for #name {
          const WORDS: &'static [&'static ::core::primitive::str] =
            <::core::primitive::#stored as #stored_as<#backend>>::WORDS;
        }

        #[automatically_derived]
        impl #sqlx_type<#backend> for #name {
          fn type_info() -> <#backend as #database_trait>::TypeInfo {
            <::core::primitive::#stored as #sqlx_type<#backend>>::type_info()
          }

          fn compatible(ty: &<#backend as #database_trait>::TypeInfo) -> ::core::primitive::bool {
            <::core::primitive::#stored as #sqlx_type<#backend>>::compatible(ty)
          }
        }

        #[automatically_derived]
        impl<'__ingraph> #encode<'__ingraph, #backend> for #name {
          fn encode_by_ref(
            &self,
            buf: &mut <#backend as #database_trait>::ArgumentBuffer,
          ) -> ::core::result::Result<#is_null, #error> {
            // The cast is EXACT by construction: the target is this width or the wider one the
            // dialect has instead, and every widening in that table holds the source's whole range.
            <::core::primitive::#stored as #encode<'__ingraph, #backend>>::encode(
              #name::bits(self) as ::core::primitive::#stored,
              buf,
            )
          }
        }

        #[automatically_derived]
        impl<'__ingraph> #decode<'__ingraph, #backend> for #name {
          fn decode(
            value: <#backend as #database_trait>::ValueRef<'__ingraph>,
          ) -> ::core::result::Result<Self, #error> {
            let stored =
              <::core::primitive::#stored as #decode<'__ingraph, #backend>>::decode(value)?;
            // TWO refusals and not one, because a schema drift produces two different faults and a
            // reader fixes them differently. A dialect that widened the column can hand back a
            // number OUTSIDE the declared width — a negative `BIGINT` where a `u32` was written —
            // and a number inside the width can still carry a BIT nobody declared. Collapsing both
            // into one sentence would point the second diagnosis at the first drift.
            let bits = match <::core::primitive::#declared as ::core::convert::TryFrom<
              ::core::primitive::#stored
            >>::try_from(stored) {
              ::core::result::Result::Ok(bits) => bits,
              ::core::result::Result::Err(_) => {
                return ::core::result::Result::Err(#error::from(#too_wide));
              }
            };
            match #name::from_bits(bits) {
              ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
              ::core::option::Option::None => {
                ::core::result::Result::Err(#error::from(#undeclared))
              }
            }
          }
        }

        #[automatically_derived]
        impl #carrier<#backend> for #name {
          fn push_bind(&self, qb: &mut #query_builder<#backend>) {
            qb.push_bind(#name::bits(self) as ::core::primitive::#stored);
          }
        }
      }
    }
  }

  /// The CONCRETE backend type one database is.
  fn backend(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
    match database {
      DatabaseKind::Sqlite => self.framework(&["sqlx"], "Sqlite"),
      DatabaseKind::Postgres => self.framework(&["sqlx"], "Postgres"),
      DatabaseKind::Mysql => self.framework(&["sqlx"], "MySql"),
      DatabaseKind::Mongo => self.framework(&["comparison", "mongo"], "Mongo"),
    }
  }

  /// The two CROSSING rows, behind the binding gate — and the whole of what this declaration owes
  /// the wire.
  ///
  /// A vocabulary emits its `EnumType`, `InputType` and `OutputType` here, because a GraphQL enum's
  /// values are the declaration's own and only the declaring crate can write them. A flags type owes
  /// none of the three: both of its seats are generic in `ingraph` over `FlagsValue` and read the
  /// bit table at runtime, so what is left is saying WHICH seat each direction takes.
  ///
  /// The two seats are DIFFERENT types, where a vocabulary crosses as itself in both directions.
  /// That asymmetry is the kind's: a flags value has a dozen readings worth publishing and one worth
  /// accepting, so the output is an object and the input is a scalar — and an object and a scalar
  /// under one name is a registry collision, which is why they are two.
  fn wire_seats(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let gate = self.framework(&["gate"], "if_async_graphql");
    let output = self.framework(&["graphql"], "ToGraphqlOutput");
    let input = self.framework(&["graphql"], "ToGraphqlInput");
    let view = self.framework(&["graphql"], "FlagsView");
    let operand = self.framework(&["graphql"], "FlagsInput");
    quote! {
      const _: () = {
        #gate! {
          #[automatically_derived]
          impl #output for #name {
            type Output<'__ingraph> = #view<Self>;

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

          #[automatically_derived]
          impl #input for #name {
            type Input = #operand<Self>;
            type Error = ::core::convert::Infallible;

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

            #[inline]
            fn carry(__ingraph_value: &Self) -> #operand<Self> {
              #operand::new(*__ingraph_value)
            }
          }
        }
      };
    }
  }
}