Skip to main content

ingraph_codegen/
flags.rs

1//! The FLAGS face: what a `#[ingraph::flags(u32)]` declaration expands into.
2//!
3//! A flags set is the VOCABULARY's sister and not a new universe. Both are a closed set of names a
4//! declaration writes down; what differs is the arity of an answer — an enum column holds one of the
5//! names and a flags column holds a subset. So the two share a shape at every layer, and where this
6//! module departs from [`enumeration`](crate::enumeration) it is because that arity forced it.
7//!
8//! # The declaration is an ENUM and the expansion is a STRUCT, and that is a REWRITE
9//!
10//! ```ignore
11//! #[ingraph::flags(u32)]
12//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13//! pub enum TrackDisposition {
14//!   /// The default track for its kind.
15//!   Default = 0x1,
16//!   Forced = 0x2,
17//!   HearingImpaired = 0x4,
18//! }
19//! ```
20//!
21//! becomes a `bitflags!` struct with `TrackDisposition::DEFAULT`, `::FORCED` and
22//! `::HEARING_IMPAIRED` on it. Three things are being asserted there and each was chosen against an
23//! alternative:
24//!
25//! - **An ATTRIBUTE and not a derive.** A derive may only APPEND, and the flags type is MINTED by
26//!   `bitflags!` rather than written by the author — so nothing but an attribute can be the door.
27//!   That is the same rewrite criterion the tree already applies elsewhere.
28//! - **The manifest is an `enum`**, because a declaration face is a set of NAMES with values and
29//!   Rust has exactly one item that spells that. A struct body cannot hold `NAME = 0x1`, and a unit
30//!   struct with the bits in the attribute would put the vocabulary somewhere a doc comment cannot
31//!   reach. Writing the vocabulary as an enum is also what makes the two kinds READ as sisters: the
32//!   word above the declaration is the whole difference between *one of these* and *a set of these*.
33//! - **The bits are the DISCRIMINANTS**, explicit and never inferred. A flags value is somebody's
34//!   stored integer, so an automatic numbering would mean that reordering the declaration rewrites
35//!   every row — and reordering a list of names is the most ordinary edit there is. Auto-numbering
36//!   is therefore refused rather than defaulted, which is the one place this kind is STRICTER than
37//!   the vocabulary it mirrors.
38//!
39//! The manifest's own lints never fire, because the manifest does not survive: an attribute macro
40//! replaces the item, so `Default` and `HearingImpaired` are read as bit NAMES here and are gone
41//! before rustc has an enum to have an opinion about.
42//!
43//! # `#[ingraph::flags(…)]` GOES ABOVE THE DERIVES, and the order is load-bearing
44//!
45//! ```ignore
46//! #[ingraph::flags(u32)]
47//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48//! pub enum TrackDisposition { … }
49//! ```
50//!
51//! rustc expands the TOPMOST attribute on an item first, and `derive` takes its turn in that same
52//! order. A derive written above this word therefore expands against the MANIFEST — the enum that is
53//! about to stop existing — and lands a `Debug` impl matching on `TrackDisposition::Default`, a
54//! variant the expansion replaced with a const. The error a reader gets says *no associated
55//! function or constant named `Default` found for struct*, which is true and unhelpful.
56//!
57//! Written above, this word expands first, and the derives it forwards land on the type
58//! `bitflags!` mints. It is the ordinary hazard of every rewriting attribute and it cannot be
59//! detected here: by the time this door runs, a derive that already expanded is gone from the
60//! item's attributes and is indistinguishable from one nobody wrote.
61//!
62//! # One word, three casings, one table
63//!
64//! `HearingImpaired` in the manifest gives the const `HEARING_IMPAIRED`, the wire word
65//! `HEARING_IMPAIRED`, and the GraphQL field `hearingImpaired`. The const and the word are the SAME
66//! string — which is what lets the strict text form be `bitflags::parser::to_writer` itself rather
67//! than a renderer written here that could come to disagree with it — and the field is that word
68//! under the one casing GraphQL's own convention asks for. `#[ingraph(rename = "…")]` moves the
69//! word, and the field follows it, because they are two readings of one declaration rather than two
70//! declarations.
71//!
72//! # Storage is the BACKING INTEGER, always
73//!
74//! There is no `text`/`integer` fork here and no per-face block, where a vocabulary has both. A
75//! flags column is stored as its bit pattern because the mask questions are ARITHMETIC on that
76//! pattern: `hasAll` is `(col & m) = m`, which a text column cannot answer at all. So the only face
77//! with words is the wire, one `rename` covers it, and the whole namespace apparatus a vocabulary
78//! needs is absent rather than defaulted.
79//!
80//! The width is the DECLARATION's — `flags(u32)` is a `u32` column — through the same house carrier
81//! table a vocabulary's `#[repr(…)]` goes through, so a Postgres column widens to `BIGINT` exactly
82//! as an enum's `u32` discriminant does.
83//!
84//! # The set of rows
85//!
86//! | impl | who demands it | gated |
87//! |---|---|---|
88//! | `FlagsValue` | every wire face — it carries the SDL name and the bit table | no |
89//! | `FlagsFilterMarker` | the column's FILTER — `FlagsMarker<T>` resolves through it | no |
90//! | `DefaultMarker`, `DefaultVecMarker` | the INFERENCE, so a column needs no word to be read | no |
91//! | `CursorValue` | the KEYSET cursor, which every persisted column is audited for | no |
92//! | `ColumnKind`, `Assemble` | the column's width and how a row reads one back | the family |
93//! | `sqlx::Type`/`Decode`/`Encode`, `Carrier` | the storage binding and the lowering's operand | per backend |
94//! | `ToGraphqlOutput`, `ToGraphqlInput` | the two wire SEATS | the binding |
95//!
96//! The wire face itself is NOT here, and that is the biggest saving over the vocabulary kind: an
97//! enum's `InputType`/`OutputType` are emitted per declaration because a GraphQL enum's values are
98//! its own, where a flags type's whole face is generic over `FlagsValue` in `ingraph` and reads the
99//! bit table at runtime. So a declaration emits two crossing rows and the framework does the rest.
100
101use heck::{ToLowerCamelCase as _, ToShoutySnakeCase as _};
102use quote::{format_ident, quote};
103use syn::ext::IdentExt as _;
104
105use crate::{enumeration::IntegerWidth, model::DatabaseKind};
106
107mod remote;
108#[cfg(test)]
109mod tests;
110
111/// The widths a flags set may be declared at.
112///
113/// UNSIGNED ONLY, and the exclusion is two arguments rather than a preference.
114///
115/// - The 64-bit and 128-bit widths are absent for the house carrier table's reason, which
116///   [`IntegerWidth`] already states: MySQL alone has a native `u64`, no dialect carries a 128-bit
117///   integer, and a column has to be storable in every dialect a declaration might reach.
118/// - The SIGNED widths are absent because a flag is a BIT and a sign bit is not one. `i8`'s top bit
119///   is `-128`, which no declaration would write as an explicit positive value, so the widths that
120///   admit it would admit exactly one bit nobody can spell — and the arithmetic every mask word
121///   rests on is defined on the unsigned reading.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
123pub enum BitWidth {
124  /// `u8` — eight flags.
125  U8,
126  /// `u16` — sixteen.
127  U16,
128  /// `u32` — thirty-two.
129  U32,
130}
131
132impl BitWidth {
133  /// Every width, in the order a refusal lists them.
134  pub const ALL: [Self; 3] = [Self::U8, Self::U16, Self::U32];
135
136  /// The primitive this width is.
137  pub const fn as_str(self) -> &'static str {
138    match self {
139      Self::U8 => "u8",
140      Self::U16 => "u16",
141      Self::U32 => "u32",
142    }
143  }
144
145  /// The width this word names, when it is one this kind carries.
146  pub fn named(word: &str) -> Option<Self> {
147    Self::ALL.into_iter().find(|width| width.as_str() == word)
148  }
149
150  /// How many bits a declaration may number, which is also one past the highest legal one.
151  pub const fn count(self) -> u32 {
152    match self {
153      Self::U8 => 8,
154      Self::U16 => 16,
155      Self::U32 => 32,
156    }
157  }
158
159  /// The largest value this width holds.
160  pub const fn ceiling(self) -> u128 {
161    (1u128 << self.count()) - 1
162  }
163
164  /// This width on the framework's own carrier table, which is where the per-dialect widening
165  /// lives.
166  ///
167  /// The vocabulary kind's table, spent unchanged: a flags column and an enum column storing the
168  /// same width are the same column, so a second widening rule here would be a second answer to a
169  /// question already settled.
170  pub const fn carried(self) -> IntegerWidth {
171    match self {
172      Self::U8 => IntegerWidth::U8,
173      Self::U16 => IntegerWidth::U16,
174      Self::U32 => IntegerWidth::U32,
175    }
176  }
177
178  /// The primitive one database actually binds — this width, widened where that dialect has no such
179  /// type.
180  pub const fn stored(self, database: DatabaseKind) -> IntegerWidth {
181    self.carried().wire(database)
182  }
183}
184
185/// One declared bit.
186#[derive(Debug, Clone)]
187pub struct FlagBit {
188  /// The bit as the MANIFEST spells it — the enum variant's own identifier.
189  pub ident: syn::Ident,
190  /// `rename = "…"` in the DECLARED mode, which moves the word every face spells this bit with.
191  ///
192  /// A mirror's `rename` fills [`upstream`](Self::upstream) instead, the two knobs being one word
193  /// reading two ways: see that field for why a restatement has no word of its own to move.
194  pub rename: Option<String>,
195  /// `rename = "…"` in the MIRROR mode — the upstream `const` this bit restates.
196  ///
197  /// A mirror's words are its OWN, where a mirrored vocabulary's are the upstream's, and the
198  /// asymmetry is the arity again: a flags set stores a bit PATTERN, so the mirrored type's text
199  /// form is read off this crate's bit table and never off the upstream's. What a restatement can
200  /// get wrong is therefore not a word but a NUMBER, and the upstream `const` is what the drift pin
201  /// compares against.
202  pub upstream: Option<syn::Ident>,
203  /// The bit's value, evaluated.
204  pub value: u128,
205  /// The declaration's own non-`ingraph` attributes, forwarded onto the emitted `const` in order —
206  /// which is what carries a bit's doc comment into the expansion.
207  pub attrs: Vec<syn::Attribute>,
208}
209
210impl FlagBit {
211  /// The WORD this bit is spelled with: its `rename`, else its identifier SHOUTED.
212  ///
213  /// One string serving three seats — the emitted `const`'s name, the strict text form's token, and
214  /// the wire's name-list entry — which is what keeps `bitflags::parser::to_writer` usable as the
215  /// text renderer instead of a second one written here.
216  ///
217  /// The shout is a Rust CONVENTION rather than a stored-word decision, which is why this kind cases
218  /// where a vocabulary's stored word is verbatim: an associated const is `SCREAMING_SNAKE_CASE`
219  /// everywhere in the ecosystem, and a flags column stores no word at all for a casing rule to
220  /// rewrite.
221  pub fn word(&self) -> String {
222    self
223      .rename
224      .clone()
225      .unwrap_or_else(|| self.ident.unraw().to_string().to_shouty_snake_case())
226  }
227
228  /// The wire FIELD this bit takes — its word, under GraphQL's own casing.
229  ///
230  /// Derived from [`word`](Self::word) rather than from the identifier, so a `rename` moves both and
231  /// they stay two readings of one declaration.
232  pub fn field(&self) -> String {
233    self.word().to_lower_camel_case()
234  }
235
236  /// The `const`'s name in the expansion — [`word`](Self::word) as an identifier.
237  pub fn constant(&self) -> syn::Ident {
238    format_ident!("{}", self.word())
239  }
240
241  /// The UPSTREAM `const` a mirror's bit restates — the declared `rename`, else this bit's own
242  /// [`constant`](Self::constant).
243  ///
244  /// The drift pin is written from this, so a name that answers to nothing upstream is `E0599` at
245  /// the token that named it. That is the whole enforcement and it is the compiler's: this side
246  /// cannot see the upstream declaration, and a table of upstream names kept here would be a second
247  /// copy of somebody else's `bitflags!`.
248  pub fn upstream(&self) -> syn::Ident {
249    self.upstream.clone().unwrap_or_else(|| self.constant())
250  }
251}
252
253/// One flags declaration, validated.
254///
255/// Public fields for [`EnumModel`](crate::enumeration::EnumModel)'s reason: nothing here parses, so
256/// a front end that is not the attribute builds the same struct and reaches the same emitter.
257#[derive(Debug, Clone)]
258pub struct FlagsModel {
259  /// Where `ingraph` lives, for the shelf every emitted path is rooted at.
260  pub krate: syn::Path,
261  /// The declaration's visibility, which the emitted struct takes.
262  pub vis: syn::Visibility,
263  /// The declared type's own name.
264  pub name: syn::Ident,
265  /// The width the bits are stored at.
266  pub width: BitWidth,
267  /// The bits, in declaration order. Never empty.
268  pub bits: Vec<FlagBit>,
269  /// The declaration's own non-`ingraph` attributes, forwarded onto the emitted struct in order.
270  ///
271  /// This is how `#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]` reaches the type `bitflags!`
272  /// mints. It is not added for the author, for the vocabulary kind's reason: a derive this door
273  /// injected would collide with one the author wrote, and the bound that actually needs it reports
274  /// `E0277` naming the trait at the type.
275  pub attrs: Vec<syn::Attribute>,
276  /// `remote = "…"` — the upstream flags set this declaration RESTATES, where it restates one.
277  ///
278  /// `None` is the ordinary declaration and the emission is untouched by this axis, down to the
279  /// token: the mirror is written last and adds to what a declared set already emits rather than
280  /// forking it. See [`remote`](self::remote) for the whole of what the word buys.
281  pub remote: Option<syn::Path>,
282  /// `graphql(rename = "…")` — what a SCHEMA calls this flags set, where the declaration moved it.
283  ///
284  /// `None` is the Rust name unraw'd, which is what [`FlagsModel::sdl_name`] resolves. EMISSION-ONLY,
285  /// for [`EnumModel`](crate::enumeration::EnumModel)'s reason: the `bitflags!` type keeps its name,
286  /// every bit keeps its `const`, and a stored bit pattern has no word for this to move.
287  pub wire_name: Option<String>,
288}
289
290impl FlagsModel {
291  /// The name a SCHEMA publishes this type under — the declaration's
292  /// [`wire_name`](Self::wire_name), else the Rust name unraw'd.
293  ///
294  /// **THE ONE HOME OF THIS KIND'S WHOLE SDL FAMILY.** Three published names are built off this
295  /// string and none of them is spelled twice: the OBJECT face takes it verbatim, the operand SCALAR
296  /// is `<it>Input` and the filter input object is `<it>Filter`, each composed where it is registered
297  /// rather than here. So one word moves the family and the three cannot come to disagree — which is
298  /// the same property the derivation was built for before there was a word to move it.
299  ///
300  /// The knob arrived with the rename-parity ruling, replacing this function's own
301  /// *no rename knob, for `EnumModel`'s reason* — and the two names moved together, as the sentence
302  /// promised they would.
303  #[must_use]
304  pub fn sdl_name(&self) -> String {
305    self
306      .wire_name
307      .clone()
308      .unwrap_or_else(|| self.name.unraw().to_string())
309  }
310
311  /// The whole expansion: the `bitflags!` type, then the rows, then the two wire seats — and, for a
312  /// MIRROR, the crossing to its upstream behind all of it.
313  ///
314  /// # The mirror is an ADDITION and never a fork
315  ///
316  /// A mirrored flags set is a flags set: it mints its own `bitflags!` type, stores its own bit
317  /// pattern, publishes its own object face and reads its own bit table. So `remote = "…"` buys
318  /// [one more block](self::remote) at the END of the expansion and moves nothing in front of it —
319  /// which is what makes a declaration naming no upstream emit exactly what it emitted before the
320  /// axis existed, token for token, and is why there is no second emitter to keep in step with this
321  /// one.
322  ///
323  /// That is the whole of where this kind departs from the vocabulary's mirror mode, and the arity
324  /// is the reason: an enum mirror DELEGATES its words to the upstream's `Display`, so its emission
325  /// really is a second one; a flags mirror delegates nothing, because a bit pattern is the same
326  /// number on both sides of the crossing.
327  #[must_use]
328  pub fn emit(&self) -> proc_macro2::TokenStream {
329    let declaration = self.declaration();
330    let vocabulary = self.vocabulary();
331    let reading = self.reading();
332    let width = self.width_row();
333    let read = self.read_row();
334    let storage = DatabaseKind::ALL
335      .into_iter()
336      .map(|database| self.storage_rows(database));
337    let wire = self.wire_seats();
338    let mirror = self.remote.as_ref().map(|path| self.mirror(path));
339    quote! {
340      #declaration
341
342      const _: () = {
343        #vocabulary
344        #reading
345        #width
346        #read
347        #(#storage)*
348      };
349
350      #wire
351
352      #mirror
353    }
354  }
355
356  /// The TYPE — one `bitflags!` invocation, reached through the shelf.
357  ///
358  /// The author's own attributes ride in front of it in the order they were written, which is the
359  /// attribute family's forwarding law: what an author wrote about their type stays true of the type
360  /// the door mints. `bitflags!` passes them through to the public struct verbatim.
361  fn declaration(&self) -> proc_macro2::TokenStream {
362    let krate = &self.krate;
363    let vis = &self.vis;
364    let name = &self.name;
365    let attrs = &self.attrs;
366    let primitive = format_ident!("{}", self.width.as_str());
367    let bits = self.bits.iter().map(|bit| {
368      let attrs = &bit.attrs;
369      let constant = bit.constant();
370      // The bit as a SUFFIXED HEX literal — hex because that is how a bit is written, and
371      // suffixed so the `const` takes the declared width rather than an inferred one.
372      let value = syn::LitInt::new(
373        &format!("0x{:x}{}", bit.value, self.width.as_str()),
374        proc_macro2::Span::call_site(),
375      );
376      quote! {
377        #(#attrs)*
378        const #constant = #value;
379      }
380    });
381    quote! {
382      #krate::__private::bitflags::bitflags! {
383        #(#attrs)*
384        #vis struct #name: ::core::primitive::#primitive {
385          #(#bits)*
386        }
387      }
388    }
389  }
390
391  /// The VOCABULARY row — the SDL name and the wire field per bit, which is the whole of what the
392  /// generic faces need that `bitflags::Flags` does not already carry.
393  ///
394  /// The field list is emitted PARALLEL to the bit list rather than as pairs, because the first of
395  /// the two lives in the vendored trait and this crate cannot add a column to it. Both come off one
396  /// loop over one declaration, which is what makes the parallelism structural rather than a
397  /// convention two emissions have to keep.
398  fn vocabulary(&self) -> proc_macro2::TokenStream {
399    let name = &self.name;
400    let trait_path = self.framework(&["flags"], "FlagsValue");
401    let sdl = self.sdl_name();
402    let fields = self.bits.iter().map(FlagBit::field);
403    quote! {
404      #[automatically_derived]
405      impl #trait_path for #name {
406        const GRAPHQL_NAME: &'static ::core::primitive::str = #sdl;
407        const FIELDS: &'static [&'static ::core::primitive::str] = &[#(#fields),*];
408      }
409    }
410  }
411
412  /// The rows that say how a COLUMN of this type is READ: its filter, the interpretation a column
413  /// and a collection of it inherit, and the codec a keyset cursor pages past it with.
414  ///
415  /// # The cursor carries the BITS, where a vocabulary's carries its word
416  ///
417  /// A cursor is minted by one process and handed back to another that may be talking to a different
418  /// dialect, so its codec belongs to the TYPE and cannot be per-backend. For a vocabulary that
419  /// forced the canonical WORD, because its stored form varies by face. A flags set stores the bit
420  /// pattern in every face, so the pattern IS the type's own form and there is nothing to choose.
421  ///
422  /// Big-endian, which is this crate's byte order for every durable number, and the width is CHECKED
423  /// coming back: a client's bytes are a client's, so four of them are not a `u32` unless they are
424  /// exactly four, and the value they hold is refused unless every bit of it was declared.
425  fn reading(&self) -> proc_macro2::TokenStream {
426    let name = &self.name;
427    let filter_marker = self.framework(&["marker"], "FlagsFilterMarker");
428    let filter = self.framework(&["graphql"], "FlagsFilter");
429    let default_marker = self.framework(&["marker"], "DefaultMarker");
430    let default_vec_marker = self.framework(&["marker"], "DefaultVecMarker");
431    let list_marker = self.framework(&["marker"], "ListMarker");
432    let marker = self.framework(&["marker"], "FlagsMarker");
433    let cursor_value = self.framework(&["cursor"], "CursorValue");
434    let primitive = format_ident!("{}", self.width.as_str());
435    let bytes = (self.width.count() / 8) as usize;
436    quote! {
437      #[automatically_derived]
438      impl #filter_marker for #name {
439        type Filter = #filter<#name>;
440      }
441
442      #[automatically_derived]
443      impl #default_marker for #name {
444        type Marker = #marker<#name>;
445      }
446
447      #[automatically_derived]
448      impl #default_vec_marker for #name {
449        type Marker = #list_marker<::std::vec::Vec<#name>, #marker<#name>>;
450      }
451
452      #[automatically_derived]
453      impl #cursor_value for #name {
454        fn write_cursor(&self, out: &mut ::std::vec::Vec<::core::primitive::u8>) {
455          out.extend_from_slice(&::core::primitive::#primitive::to_be_bytes(
456            #name::bits(self),
457          ));
458        }
459
460        fn read_cursor(bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
461          match <[::core::primitive::u8; #bytes] as ::core::convert::TryFrom<&[
462            ::core::primitive::u8
463          ]>>::try_from(bytes) {
464            ::core::result::Result::Ok(fixed) => {
465              #name::from_bits(::core::primitive::#primitive::from_be_bytes(fixed))
466            }
467            ::core::result::Result::Err(_) => ::core::option::Option::None,
468          }
469        }
470      }
471    }
472  }
473
474  /// This type's COLUMN WIDTH: one, whatever the dialect widens it to — and its SAMENESS, which is
475  /// its bits'.
476  fn width_row(&self) -> proc_macro2::TokenStream {
477    let name = &self.name;
478    let column_kind = self.framework(&["column"], "ColumnKind");
479    let column_eq = self.framework(&["column"], "ColumnEq");
480    quote! {
481      #[automatically_derived]
482      impl #column_kind for #name {}
483
484      // Two flag sets are one column value when their BITS are, which is what the `PartialEq` this
485      // device already puts on the type says — see the `bitflags!` derive list. The row exists
486      // because an emitted record row folds this face where it used to derive `PartialEq` over its
487      // declared field types.
488      #[automatically_derived]
489      impl #column_eq for #name {
490        #[inline]
491        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
492          ::core::cmp::PartialEq::eq(self, __ingraph_other)
493        }
494      }
495    }
496  }
497
498  /// How a holder's row READS one of these back — [`EnumModel::read_row`]'s emission, unchanged,
499  /// because what it states is a fact about being ONE column and a flags set is one.
500  fn read_row(&self) -> proc_macro2::TokenStream {
501    let name = &self.name;
502    let gate = self.framework(&["gate"], "if_sqlx");
503    let assemble = self.framework(&["column"], "Assemble");
504    let plain_column = self.framework(&["column"], "plain_column");
505    let path = self.framework(&["comparison"], "Path");
506    let row_trait = self.framework(&["sqlx"], "Row");
507    let decode = self.framework(&["sqlx"], "Decode");
508    let sqlx_type = self.framework(&["sqlx"], "Type");
509    let column_index = self.framework(&["sqlx"], "ColumnIndex");
510    let result = self.framework(&["sqlx"], "Result");
511    let row = crate::emit::parameter("ROW");
512    quote! {
513      #gate! {
514        #[automatically_derived]
515        impl<'__ingraph, #row> #assemble<'__ingraph, #row> for #name
516        where
517          #row: #row_trait,
518          #name: #decode<'__ingraph, <#row as #row_trait>::Database>
519            + #sqlx_type<<#row as #row_trait>::Database>,
520          for<'__ingraph_name> &'__ingraph_name ::core::primitive::str: #column_index<#row>,
521        {
522          #[inline]
523          fn assemble(
524            __row: &'__ingraph #row,
525            __ingraph_under: ::core::option::Option<&#path<'_>>,
526          ) -> #result<Self> {
527            #plain_column(__row, __ingraph_under)
528          }
529        }
530      }
531    }
532  }
533
534  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
535  /// them.
536  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
537    let krate = &self.krate;
538    let module = module.iter().map(|segment| format_ident!("{segment}"));
539    let name = format_ident!("{name}");
540    quote!(#krate::__private #(:: #module)* :: #name)
541  }
542
543  /// One backend's four storage rows, behind its gate — or nothing, where the backend stores no
544  /// flags column yet.
545  ///
546  /// MongoDB is absent for the reason the vocabulary kind's Mongo row is absent: the design exists —
547  /// `MongoFlagsComparison` is written and its three mask words are the server's own — and what is
548  /// missing is a lane in this workspace that could compile the carrier.
549  fn storage_rows(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
550    if !database.is_sql() {
551      return quote!();
552    }
553
554    let name = &self.name;
555    let gate = self.framework(&["gate"], &database.gate().to_string());
556    let backend = self.backend(database);
557    let carrier = self.framework(&["comparison", "sql"], "Carrier");
558    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
559    let sqlx_type = self.framework(&["sqlx"], "Type");
560    let encode = self.framework(&["sqlx"], "Encode");
561    let decode = self.framework(&["sqlx"], "Decode");
562    let database_trait = self.framework(&["sqlx"], "Database");
563    let is_null = self.framework(&["sqlx", "encode"], "IsNull");
564    let error = self.framework(&["sqlx", "error"], "BoxDynError");
565
566    let declared = format_ident!("{}", self.width.as_str());
567    let stored = format_ident!("{}", self.width.stored(database).as_str());
568    let too_wide =
569      format!("{name}: the stored number does not fit the width this declaration is declared at");
570    let undeclared = format!("{name}: the stored bits name a flag this declaration never declared");
571
572    let stored_as = self.framework(&["column"], "StoredAs");
573
574    quote! {
575      #gate! {
576        // The WORD this column is declared with — the STORED width's own, which is the width this
577        // dialect actually holds the bits at rather than the one the declaration wrote. That is the
578        // same table every crossing here reads: a `u32` set on a dialect with no unsigned type is
579        // stored, encoded, decoded and DECLARED at the wider signed one, so all four move together.
580        #[automatically_derived]
581        impl #stored_as<#backend> for #name {
582          const WORDS: &'static [&'static ::core::primitive::str] =
583            <::core::primitive::#stored as #stored_as<#backend>>::WORDS;
584        }
585
586        #[automatically_derived]
587        impl #sqlx_type<#backend> for #name {
588          fn type_info() -> <#backend as #database_trait>::TypeInfo {
589            <::core::primitive::#stored as #sqlx_type<#backend>>::type_info()
590          }
591
592          fn compatible(ty: &<#backend as #database_trait>::TypeInfo) -> ::core::primitive::bool {
593            <::core::primitive::#stored as #sqlx_type<#backend>>::compatible(ty)
594          }
595        }
596
597        #[automatically_derived]
598        impl<'__ingraph> #encode<'__ingraph, #backend> for #name {
599          fn encode_by_ref(
600            &self,
601            buf: &mut <#backend as #database_trait>::ArgumentBuffer,
602          ) -> ::core::result::Result<#is_null, #error> {
603            // The cast is EXACT by construction: the target is this width or the wider one the
604            // dialect has instead, and every widening in that table holds the source's whole range.
605            <::core::primitive::#stored as #encode<'__ingraph, #backend>>::encode(
606              #name::bits(self) as ::core::primitive::#stored,
607              buf,
608            )
609          }
610        }
611
612        #[automatically_derived]
613        impl<'__ingraph> #decode<'__ingraph, #backend> for #name {
614          fn decode(
615            value: <#backend as #database_trait>::ValueRef<'__ingraph>,
616          ) -> ::core::result::Result<Self, #error> {
617            let stored =
618              <::core::primitive::#stored as #decode<'__ingraph, #backend>>::decode(value)?;
619            // TWO refusals and not one, because a schema drift produces two different faults and a
620            // reader fixes them differently. A dialect that widened the column can hand back a
621            // number OUTSIDE the declared width — a negative `BIGINT` where a `u32` was written —
622            // and a number inside the width can still carry a BIT nobody declared. Collapsing both
623            // into one sentence would point the second diagnosis at the first drift.
624            let bits = match <::core::primitive::#declared as ::core::convert::TryFrom<
625              ::core::primitive::#stored
626            >>::try_from(stored) {
627              ::core::result::Result::Ok(bits) => bits,
628              ::core::result::Result::Err(_) => {
629                return ::core::result::Result::Err(#error::from(#too_wide));
630              }
631            };
632            match #name::from_bits(bits) {
633              ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
634              ::core::option::Option::None => {
635                ::core::result::Result::Err(#error::from(#undeclared))
636              }
637            }
638          }
639        }
640
641        #[automatically_derived]
642        impl #carrier<#backend> for #name {
643          fn push_bind(&self, qb: &mut #query_builder<#backend>) {
644            qb.push_bind(#name::bits(self) as ::core::primitive::#stored);
645          }
646        }
647      }
648    }
649  }
650
651  /// The CONCRETE backend type one database is.
652  fn backend(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
653    match database {
654      DatabaseKind::Sqlite => self.framework(&["sqlx"], "Sqlite"),
655      DatabaseKind::Postgres => self.framework(&["sqlx"], "Postgres"),
656      DatabaseKind::Mysql => self.framework(&["sqlx"], "MySql"),
657      DatabaseKind::Mongo => self.framework(&["comparison", "mongo"], "Mongo"),
658    }
659  }
660
661  /// The two CROSSING rows, behind the binding gate — and the whole of what this declaration owes
662  /// the wire.
663  ///
664  /// A vocabulary emits its `EnumType`, `InputType` and `OutputType` here, because a GraphQL enum's
665  /// values are the declaration's own and only the declaring crate can write them. A flags type owes
666  /// none of the three: both of its seats are generic in `ingraph` over `FlagsValue` and read the
667  /// bit table at runtime, so what is left is saying WHICH seat each direction takes.
668  ///
669  /// The two seats are DIFFERENT types, where a vocabulary crosses as itself in both directions.
670  /// That asymmetry is the kind's: a flags value has a dozen readings worth publishing and one worth
671  /// accepting, so the output is an object and the input is a scalar — and an object and a scalar
672  /// under one name is a registry collision, which is why they are two.
673  fn wire_seats(&self) -> proc_macro2::TokenStream {
674    let name = &self.name;
675    let gate = self.framework(&["gate"], "if_async_graphql");
676    let output = self.framework(&["graphql"], "ToGraphqlOutput");
677    let input = self.framework(&["graphql"], "ToGraphqlInput");
678    let view = self.framework(&["graphql"], "FlagsView");
679    let operand = self.framework(&["graphql"], "FlagsInput");
680    quote! {
681      const _: () = {
682        #gate! {
683          #[automatically_derived]
684          impl #output for #name {
685            type Output<'__ingraph> = #view<Self>;
686
687            #[inline]
688            fn to_graphql_output(__ingraph_value: &Self) -> #view<Self> {
689              #view::new(*__ingraph_value)
690            }
691          }
692
693          #[automatically_derived]
694          impl #input for #name {
695            type Input = #operand<Self>;
696            type Error = ::core::convert::Infallible;
697
698            #[inline]
699            fn cross(
700              __ingraph_value: #operand<Self>,
701            ) -> ::core::result::Result<Self, ::core::convert::Infallible> {
702              ::core::result::Result::Ok(#operand::into_inner(__ingraph_value))
703            }
704
705            #[inline]
706            fn carry(__ingraph_value: &Self) -> #operand<Self> {
707              #operand::new(*__ingraph_value)
708            }
709          }
710        }
711      };
712    }
713  }
714}