Skip to main content

ingraph_codegen/
union.rs

1//! The UNION face: what an enum whose variants CARRY their members expands into.
2//!
3//! A union is not a node and not a value a column holds. It is a CHOICE — one of several member
4//! types, named by the variant that carries it — and the whole of what this half writes is the way
5//! Rust asks that choice: which member is held, and how to get at it.
6//!
7//! # Which unions this derive is for
8//!
9//! The DECLARED ones. A schema's `union SearchResult = Media | Video` and its input-position twin
10//! are both a payload-carrying enum somebody WROTE, and this derive equips it — the same direction
11//! [`crate::enumeration`] takes with a vocabulary. The other payload enums in this framework are
12//! the FAN-IN ones a node with several upstreams gets, and those are the node macros' own emission:
13//! nobody writes them, so there is nothing for a derive to be applied to.
14//!
15//! # The shape, and the law it comes from
16//!
17//! Every variant carries exactly ONE unnamed payload, and that payload's type is the member. The
18//! shape is not this crate's taste — it is what a declared union renders as at both positions a
19//! schema has for one, and the input position is the tighter of the two: an `@oneOf` input object
20//! is an enum of single-value TUPLE variants and nothing else.
21//!
22//! GraphQL's own type validation is where the rest of the refusals come from, quoted rather than
23//! paraphrased: *A Union type must include one or more unique member types.* That one sentence is
24//! the empty union's refusal and the duplicated member's both.
25//!
26//! # The face is a SEAM, because a union is not the only member set
27//!
28//! [`Equipped`] is the emission, and [`UnionModel::emit`] is one caller of it. An INTERFACE is a
29//! member set too — one with a contract over it — so it declares the same Rust shape and wants the
30//! same question asked: which member is held, and how to get at it. Written once, the second caller
31//! inherits the emission rather than a copy of it, and the two cannot come to spell one method
32//! differently.
33//!
34//! # The face is HAND-EMITTED, and it is the whole of what this half writes
35//!
36//! `is_<member>`, `unwrap_<member>` and `try_unwrap_<member>`, the latter two in all three
37//! receivers — owned, `_ref`, `_mut`. The suffix spelling is `derive_more`'s `#[unwrap(ref,
38//! ref_mut)]` semantics restated as OURS, and `derive_more` itself is not a dependency of THIS
39//! emission: its `TryUnwrapError` would put a foreign path in every consumer's expanded code and a
40//! foreign type in the signatures a caller writes. (The framework crate does depend on it, for its
41//! own `Emission<Out>` — an enum of this exact shape carrying those exact attributes. That is a
42//! foreign path in `ingraph`'s own source, which is nobody else's expansion.)
43//!
44//! The two agree on the SUFFIXES and part company on the WORD, and the divergence is deliberate.
45//! `derive_more` cases a variant through `convert_case`, whose default boundaries include
46//! `LOWER_DIGIT` and `UPPER_DIGIT`, so a variant `Vp9` reaches it as `vp_9`. This framework cases
47//! through `heck`, where the same variant is `vp9` — which is what the vocabulary derive already
48//! emits and what its collision refusal already names. A variant spelled one way in Rust must
49//! derive ONE word in this framework, whether it is a vocabulary's member or a union's, so the word
50//! is the house's and only the suffixes are borrowed.
51//!
52//! Only `is_<member>` is `const`. The unwrap family cannot be: a receiver that takes `self` DROPS
53//! the payload it did not match, and a `const fn` may not drop a value whose type could implement
54//! [`Drop`] — so the owned pair is out on its own terms, and a family whose three receivers
55//! differed in constness would read as an accident rather than a rule.
56//!
57//! # The refusal carries the pair, and its construction is SEALED
58//!
59//! `<Union>UnwrapError` holds the variant ASKED for and the variant HELD, as `&'static str` the
60//! expansion mints. Not the empty payload a vocabulary's parse refusal takes: there the caller
61//! already holds the word that failed, and here the two names are the whole content of what went
62//! wrong. The fields are private, so nothing outside the declaring module builds one; the pair is
63//! read back through the emitted `asked()` and `held()`, and the
64//! [`Display`](core::fmt::Display) sentence is written from them once. The framework's `name` shelf
65//! offers nothing that fits: its five name types spell what ONE NAMESPACE calls a vocabulary's
66//! member — a stored word or a wire word — and a Rust variant's own spelling is neither.
67//!
68//! One refusal serves all three receivers, and that is what settles the question of handing the
69//! held value back: a borrowing receiver has nothing owned to return, so an error carrying the
70//! union would have to be a different type per receiver. The owned `try_unwrap_<member>` therefore
71//! DROPS what it did not match, which is the trade written into the emitted `# Errors` note.
72//!
73//! # The REFUSAL is the ONE name this expansion puts in the declaring scope
74//!
75//! Everything else sits inside an anonymous `const`, where it collides with nothing anybody wrote.
76//! The refusal cannot: it is named in signatures a caller writes. `unwrap_error(rename = "…")` is
77//! the escape, read through the same shared block reader `Record`'s `key(…)` and the vocabulary's
78//! own `error(…)` go through — one grammar, so a third derive invents no wording for a rule the
79//! first two already have. The word is `unwrap_error` and not `error` because `error` names the
80//! CONVERSION CELLS, one per leg inside a database's block: what a fallible crossing refuses with is
81//! not what a wrong-variant unwrap answers with.
82//!
83//! # The WIRE ROUND arrived, and it is what bought `crate = "…"`
84//!
85//! The method face above is `core` and nothing else, and while it was the whole emission there was
86//! nothing for a `crate` option to move. [`wire`] changed that: a declared union's backend
87//! implementations are HAND-EMITTED off [`UnionModel`] (their derive does not ride a model slot,
88//! unlike the order-by's — the ruling of 2026-08-05), every name in them is reached through
89//! `#krate::__private`, and the gate they ride is reached the same way. So [`UnionModel::krate`] is
90//! the path this expansion is rooted at, exactly as [`crate::enumeration`]'s is.
91//!
92//! There is still no `wire_derive`, and now for a stronger reason than *not yet*: a DERIVE may only
93//! append, so nothing here can put `#[derive(async_graphql::Union)]` on an enum somebody else wrote
94//! — the same wall `crate::index`'s own union face states. Both faces are written out.
95//!
96//! # The two faces are IMPLS ON THE DECLARED ENUM, and that decides the naming law
97//!
98//! `output` is the schema's `union X = A | B`; `input` is its `@oneOf` input object. Both are
99//! written onto the type the declaration already named, so a union that declares both puts TWO
100//! schema types on ONE Rust type — and a schema has one namespace for type names. Hence the law
101//! [`UnionSkin::input_sdl`] carries: a single face takes the union's own name, and where both are
102//! rendered the output keeps it and the input derives `<Union>Input`.
103//!
104//! **Both faces are movable**, and the rename-parity ruling is what made the pair symmetric:
105//! `input(rename = "…")` names the twin, `output(rename = "…")` names the union itself and carries
106//! the derived twin with it. The law above is untouched by either — it decides which face keeps the
107//! DEFAULT, which is a different question from whether an author may name one.
108//!
109//! # A union is not a column
110//!
111//! No storage rows, at any backend. No scenario stores one: both declared positions are wire
112//! shapes, and fan-in addresses its upstreams by `(tag, id)` rather than by a stored payload. Were
113//! one ever to persist, the shape is already ruled — a discriminant column beside one side table
114//! per member — and it is a design round that starts there rather than at a tagged blob.
115
116use heck::ToSnakeCase as _;
117use quote::{format_ident, quote};
118use syn::ext::IdentExt as _;
119
120use crate::model::GraphqlKind;
121
122#[cfg(test)]
123mod tests;
124mod wire;
125
126/// One method the face declares for one member.
127///
128/// The whole vocabulary of derived names, for the reason [`Member`](crate::method::Member) is a
129/// vocabulary rather than five `format_ident!` calls: a suffix written twice is a suffix that can
130/// come to be written differently, and a front end refusing a collision has to spell exactly the
131/// names the emitter writes.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
133pub enum Face {
134  /// `is_x` — whether this member is the one held.
135  Predicate,
136  /// `unwrap_x` — the payload, or a panic.
137  Unwrap,
138  /// `unwrap_x_ref` — a borrow of it, or a panic.
139  UnwrapRef,
140  /// `unwrap_x_mut` — an exclusive borrow of it, or a panic.
141  UnwrapMut,
142  /// `try_unwrap_x` — the payload, or the refusal.
143  TryUnwrap,
144  /// `try_unwrap_x_ref` — a borrow of it, or the refusal.
145  TryUnwrapRef,
146  /// `try_unwrap_x_mut` — an exclusive borrow of it, or the refusal.
147  TryUnwrapMut,
148}
149
150impl Face {
151  /// Every method a member gets, in the order the emission declares them.
152  pub const ALL: [Self; 7] = [
153    Self::Predicate,
154    Self::Unwrap,
155    Self::UnwrapRef,
156    Self::UnwrapMut,
157    Self::TryUnwrap,
158    Self::TryUnwrapRef,
159    Self::TryUnwrapMut,
160  ];
161
162  /// What this method is called over a member whose word is `word`.
163  #[must_use]
164  pub fn name(self, word: &syn::Ident) -> syn::Ident {
165    match self {
166      Self::Predicate => format_ident!("is_{word}"),
167      Self::Unwrap => format_ident!("unwrap_{word}"),
168      Self::UnwrapRef => format_ident!("unwrap_{word}_ref"),
169      Self::UnwrapMut => format_ident!("unwrap_{word}_mut"),
170      Self::TryUnwrap => format_ident!("try_unwrap_{word}"),
171      Self::TryUnwrapRef => format_ident!("try_unwrap_{word}_ref"),
172      Self::TryUnwrapMut => format_ident!("try_unwrap_{word}_mut"),
173    }
174  }
175}
176
177/// The word a variant's methods are built on — `media` for `Media`, `type` for `r#type`.
178///
179/// Free rather than only a method on [`UnionMember`], because a front end refusing a variant it did
180/// NOT accept as a member still has to name the method that variant would have had: a refusal
181/// spelling that word itself would be a second copy of this rule.
182///
183/// Over the RUST spelling, because the methods are Rust and their reader is looking at the variant.
184#[must_use]
185pub fn word(ident: &syn::Ident) -> syn::Ident {
186  use syn::ext::IdentExt as _;
187
188  format_ident!("{}", ident.unraw().to_string().to_snake_case())
189}
190
191/// What the refusal a wrong-variant unwrap answers with is called when nothing renamed it:
192/// `<Enum>UnwrapError`.
193///
194/// The convention's ONE home, for the reason [`crate::model`]'s defaulted names are theirs: a
195/// second member set equipped through the same seam takes the same suffix, and a suffix written
196/// twice is a suffix that can come to be written differently.
197#[must_use]
198pub fn default_unwrap_error_name(base: &syn::Ident) -> syn::Ident {
199  format_ident!("{base}UnwrapError")
200}
201
202/// What a SCHEMA calls a union's input object where the output face already holds the union's own
203/// name: `<Union>Input`.
204///
205/// The convention's ONE home, beside [`default_unwrap_error_name`] and for its reason. It answers a
206/// `String` rather than an `Ident` because the name it derives is a SCHEMA entity's — nothing in
207/// Rust is called this, both faces being impls on the enum the declaration already named — so the
208/// `r#` a raw enum carries is dropped here as it is everywhere a word leaves Rust.
209#[must_use]
210pub fn default_input_sdl_name(base: &syn::Ident) -> String {
211  input_sdl_name(&base.unraw().to_string())
212}
213
214/// The same convention over a base that is already a SCHEMA word — what a renamed face composes its
215/// input twin's name from.
216///
217/// The two entries exist because the base arrives two ways and the suffix must not: a declaration
218/// that renamed nothing has an `Ident` to unraw, one that wrote `rename = "…"` has a literal that was
219/// never Rust. Both reach this line, which is the ONE blessed derivation the rename laws name —
220/// `key(rename = "Address")` publishing `Address` and `AddressInput` is the same composition one
221/// grammar over.
222#[must_use]
223pub fn input_sdl_name(base: &str) -> String {
224  format!("{base}Input")
225}
226
227/// The SEAT one member takes in the `@oneOf` input object — `media` for `Media`, `videoClip` for
228/// `VideoClip`.
229///
230/// async-graphql's own `OneofObject` default (`rename_fields = "camelCase"` over the variant), spelled
231/// here because no derive of that library's can be reached: the face is hand-emitted, so the word it
232/// publishes has to be written.
233///
234/// Free rather than a method on [`UnionMember`], for the reason [`word`] is: a front end refusing a
235/// variant it did not accept still has to be able to name the seat that variant would have had.
236///
237/// **Two variants cannot collide here without colliding at [`word`] first.** Both are joins of the
238/// same case-split word list, so one snake spelling is one lower-camel spelling, and the METHOD
239/// collision the shared member walk already refuses covers this face too.
240#[must_use]
241pub fn seat(ident: &syn::Ident) -> String {
242  use heck::ToLowerCamelCase as _;
243
244  ident.unraw().to_string().to_lower_camel_case()
245}
246
247/// One member: the variant that names it and the type it is.
248#[derive(Debug, Clone)]
249pub struct UnionMember {
250  /// The variant as Rust spells it, `r#` and all.
251  pub ident: syn::Ident,
252  /// The single unnamed payload the variant carries — the member type itself.
253  pub ty: syn::Type,
254}
255
256impl UnionMember {
257  /// The variant's own name, unraw'd — what a message and the refusal's payload spell it as.
258  ///
259  /// The `r#` is Rust's escape for a word that collides with its grammar and no part of the name,
260  /// so a variant called `r#type` is `type` in a sentence about it.
261  #[must_use]
262  pub fn name(&self) -> String {
263    use syn::ext::IdentExt as _;
264
265    self.ident.unraw().to_string()
266  }
267
268  /// The word every method of this member is built on — `media` for `Media`.
269  #[must_use]
270  pub fn word(&self) -> syn::Ident {
271    word(&self.ident)
272  }
273}
274
275/// The INPUT face's declaration: that a backend renders one, and what a schema calls it.
276///
277/// A struct where a `bool` would do, because the presence and the NAME are one decision and the
278/// name is the half a declaration can move: `input` alone is the derived name, `input(rename = "…")`
279/// is the same face under a word the declaration chose.
280#[derive(Debug, Clone, Default)]
281pub struct UnionInput {
282  /// `input(rename = "…")` — what a client calls this input object, where the declaration moved it.
283  ///
284  /// `None` is [`UnionSkin::input_sdl`]'s law: the union's own name where nothing else claims it,
285  /// and the `Input` suffix over the OUTPUT's word where the output face claims it.
286  pub rename: Option<syn::LitStr>,
287}
288
289/// The OUTPUT face's declaration: that a backend renders one, and what a schema calls it.
290///
291/// [`UnionInput`]'s twin, one position over and the same shape for the same reason. It arrived with
292/// the rename-parity ruling, replacing a bare `bool` and the sentence *no rename knob, and the
293/// absence is the ruling rather than an omission* that stood on
294/// [`output_sdl`](UnionSkin::output_sdl).
295///
296/// **What that sentence was actually right about was the DEFAULT, not the knob.** The naming law it
297/// pointed at decides which face keeps the union's own name when both are rendered — the output,
298/// because that is the one a client writes in a selection set — and it still does. What it does not
299/// decide is whether an author whose scope already holds a `Frame` may publish this union as
300/// something else, and the answer to that had been *no word for it*.
301#[derive(Debug, Clone, Default)]
302pub struct UnionOutput {
303  /// `output(rename = "…")` — what a client calls this union, where the declaration moved it.
304  ///
305  /// `None` is the enum's own name unraw'd. Where it is written it re-bases the input twin too —
306  /// see [`UnionSkin::input_sdl`], where the one blessed derivation is spent.
307  pub rename: Option<syn::LitStr>,
308}
309
310/// ONE GraphQL backend's rendering of a declared union — which of the two schema positions it is
311/// dressed for.
312///
313/// The pair is the whole vocabulary and neither is implied by the other: a union declared for input
314/// alone is an `@oneOf` argument object nothing returns, and one declared for output alone is a
315/// result type no argument takes. A backend named with NEITHER word is refused at the declaration —
316/// a block that dresses no position dresses nothing.
317#[derive(Debug, Clone)]
318pub struct UnionSkin {
319  /// Which backend this is.
320  pub kind: GraphqlKind,
321  /// `output` — the schema's `union X = A | B`, in a RETURN position.
322  pub output: Option<UnionOutput>,
323  /// `input` — the schema's `@oneOf` input object, in an ARGUMENT position.
324  pub input: Option<UnionInput>,
325}
326
327impl UnionSkin {
328  /// What a schema calls this union's OUTPUT face — `output(rename = "…")`, else the enum's own name
329  /// unraw'd.
330  ///
331  /// The default is [`input_sdl`](Self::input_sdl)'s law read from the other side: where both faces
332  /// are rendered the output is the one that keeps the union's own word, because it is the one a
333  /// client names in a selection set. The knob moves that word without touching the law — and it
334  /// moves the twin with it.
335  #[must_use]
336  pub fn output_sdl(&self, base: &syn::Ident) -> String {
337    match self
338      .output
339      .as_ref()
340      .and_then(|output| output.rename.as_ref())
341    {
342      Some(declared) => declared.value(),
343      None => base.unraw().to_string(),
344    }
345  }
346
347  /// What a schema calls this union's INPUT face.
348  ///
349  /// # The naming law, whole
350  ///
351  /// Both faces are impls on ONE Rust type, and a GraphQL schema has ONE namespace for type names.
352  /// So:
353  ///
354  /// * a union rendering ONE face — either one — publishes it under the union's own name, there
355  ///   being nothing else to collide with;
356  /// * a union rendering BOTH gives the union's own name to the OUTPUT and derives the input's by
357  ///   suffixing it, because the output type is the one a client names in a selection set and an
358  ///   argument object is the derived twin of it.
359  ///
360  /// `input(rename = "…")` moves this word and only this word, at either arity: a declaration whose
361  /// scope already publishes a `<Union>Input` needs the escape as much as one that simply prefers
362  /// another name.
363  ///
364  /// # The derived twin follows the OUTPUT's word, not the Rust ident
365  ///
366  /// `output(rename = "Sighting")` on a both-faces union publishes `Sighting` and `SightingInput`,
367  /// which is the ONE BLESSED DERIVATION the rename laws name — the same composition
368  /// `key(rename = "Address")` spends to publish `Address` and `AddressInput`. Composing off the Rust
369  /// ident instead would publish the renamed union beside an input object still wearing the old
370  /// stem: a rename that moved one face and not the other, which the naming law calls worse than
371  /// none.
372  #[must_use]
373  pub fn input_sdl(&self, base: &syn::Ident) -> String {
374    match self.input.as_ref().and_then(|input| input.rename.as_ref()) {
375      Some(declared) => declared.value(),
376      None if self.output.is_some() => input_sdl_name(&self.output_sdl(base)),
377      None => base.unraw().to_string(),
378    }
379  }
380}
381
382/// One union's declaration, validated.
383///
384/// Public fields for the reason [`RecordModel`](crate::model::RecordModel)'s are: nothing here
385/// parses, so a front end that is not the derive builds the same struct and reaches the same
386/// emitter.
387#[derive(Debug, Clone)]
388pub struct UnionModel {
389  /// Where `ingraph` lives, for every path the WIRE half emits. The method face names none.
390  pub krate: syn::Path,
391  /// The declaration's visibility, which every emitted item takes.
392  pub vis: syn::Visibility,
393  /// The declared enum's own name.
394  pub name: syn::Ident,
395  /// Its members, in declaration order. Never empty, and never two of one type.
396  pub members: Vec<UnionMember>,
397  /// What the emitted REFUSAL type is called, when the declaration named it.
398  ///
399  /// `None` is `<Union>UnwrapError`, which is what [`UnionModel::error`] resolves.
400  pub error: Option<syn::Ident>,
401  /// The backends this union is dressed for, in declaration order. EMPTY is a union with no wire
402  /// face at all, which is what a declaration writing no `graphql(…)` block keeps.
403  pub graphql: Vec<UnionSkin>,
404}
405
406impl UnionModel {
407  /// The refusal type a wrong-variant unwrap answers with — the declared name, else
408  /// `FoundUnwrapError`.
409  ///
410  /// The ONE authority on what that type is called: the emission writes this, and a front end's
411  /// collision check asks it rather than rebuilding the suffix convention on its own side.
412  #[must_use]
413  pub fn error(&self) -> syn::Ident {
414    self
415      .error
416      .clone()
417      .unwrap_or_else(|| default_unwrap_error_name(&self.name))
418  }
419
420  /// The whole expansion: the refusal type, the method face, and the wire faces a declaration asked
421  /// for.
422  ///
423  /// The WIRE half is a block of its own rather than a member of the seam's, for the reason
424  /// [`EnumModel::emit`](crate::enumeration::EnumModel::emit) keeps its own separate: the whole of
425  /// it sits behind the binding gate, and a gate wrapping one block's entire body is what lets a
426  /// build without `async-graphql` expand it to nothing at all.
427  ///
428  /// It is also what keeps the SEAM untouched. [`Equipped`] is shared with the interface derive,
429  /// which has a wire face of its own and no use for this one — so the union's backend impls hang
430  /// off the MODEL, one layer above the emission both member sets reach.
431  #[must_use]
432  pub fn emit(&self) -> proc_macro2::TokenStream {
433    let equipped = self.equipped().emit();
434    let wire = self.graphql_faces();
435    quote! {
436      #equipped
437      #wire
438    }
439  }
440
441  /// This union as the SEAM sees it — a payload-carrying enum, its members, and what its refusal is
442  /// called.
443  fn equipped(&self) -> Equipped<'_> {
444    Equipped {
445      vis: &self.vis,
446      name: &self.name,
447      members: &self.members,
448      error: self.error(),
449    }
450  }
451}
452
453/// A payload-carrying enum, equipped — the face and the refusal, independent of what the enum
454/// MEANS.
455///
456/// The seam two derives reach. A union IS its member set and an INTERFACE is a member set with a
457/// contract over it, so both declare the same Rust shape and both want the same question asked of
458/// it: which member is held, and how to get at it. Written once here, so the second derive to want
459/// it inherits the emission rather than a copy of it — and so the two cannot come to spell one
460/// method differently.
461///
462/// Borrows rather than owns, and takes the refusal's name RESOLVED: whichever model built one has
463/// already settled what its own defaults are, and a seam that re-derived a name would be the second
464/// copy of the convention this shape exists to avoid.
465pub(crate) struct Equipped<'a> {
466  /// The declaration's visibility, which every emitted item takes.
467  pub(crate) vis: &'a syn::Visibility,
468  /// The declared enum's own name.
469  pub(crate) name: &'a syn::Ident,
470  /// Its members, in declaration order.
471  pub(crate) members: &'a [UnionMember],
472  /// What the emitted REFUSAL type is called, already resolved.
473  pub(crate) error: syn::Ident,
474}
475
476impl Equipped<'_> {
477  /// The whole expansion: the refusal type, then the face.
478  pub(crate) fn emit(&self) -> proc_macro2::TokenStream {
479    let error = self.refusal();
480    let held = self.held();
481    let face = self.face();
482    quote! {
483      #error
484
485      const _: () = {
486        #held
487        #face
488      };
489    }
490  }
491
492  /// The refusal a wrong-variant unwrap answers with, and the two names it carries.
493  fn refusal(&self) -> proc_macro2::TokenStream {
494    let vis = self.vis;
495    let name = self.name;
496    let error = &self.error;
497    let sentence = format!("`{name}`: asked for `{{}}`, held `{{}}`");
498    let doc = format!(
499      "The refusal an unwrap into a variant a [`{name}`] is not holding answers with.\n\nSealed \
500       rather than empty: its fields are private, so nothing outside this module builds one, and it \
501       carries the pair that says what went wrong — the variant asked for and the variant held."
502    );
503    let asked = format!("The variant the call asked [`{name}`] for.");
504    let held = format!("The variant that [`{name}`] was holding instead.");
505    quote! {
506      #[doc = #doc]
507      #[derive(Debug, Clone, Copy, PartialEq, Eq)]
508      #vis struct #error {
509        asked: &'static ::core::primitive::str,
510        held: &'static ::core::primitive::str,
511      }
512
513      #[automatically_derived]
514      impl #error {
515        #[doc = #asked]
516        #[inline]
517        #[must_use]
518        #vis const fn asked(&self) -> &'static ::core::primitive::str {
519          self.asked
520        }
521
522        #[doc = #held]
523        #[inline]
524        #[must_use]
525        #vis const fn held(&self) -> &'static ::core::primitive::str {
526          self.held
527        }
528      }
529
530      #[automatically_derived]
531      impl ::core::fmt::Display for #error {
532        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
533          ::core::write!(f, #sentence, self.asked, self.held)
534        }
535      }
536
537      #[automatically_derived]
538      impl ::core::error::Error for #error {}
539    }
540  }
541
542  /// Whether this union has a WRONG variant at all.
543  ///
544  /// One member is a legal declaration — GraphQL's law is *one or more* — and it is the shape where
545  /// every unwrap succeeds: there is no other variant to be holding, so the refusal is a type in
546  /// the signatures and nothing the expansion can build.
547  fn has_a_wrong_variant(&self) -> bool {
548    self.members.len() > 1
549  }
550
551  /// The one table saying which variant a union is holding, called by every refusal the face
552  /// builds.
553  ///
554  /// One table rather than an arm written into each method, for the reason a vocabulary's reverse
555  /// map is written once: several copies of one mapping are several things that can come to
556  /// disagree, and the disagreement is invisible — each is right in isolation and only the set is
557  /// wrong.
558  ///
559  /// Absent from a ONE-MEMBER union, where it would have no caller: its single pattern is
560  /// irrefutable, so the methods below match it and stop.
561  fn held(&self) -> proc_macro2::TokenStream {
562    if !self.has_a_wrong_variant() {
563      return quote!();
564    }
565    let name = self.name;
566    let held = self.held_fn();
567    let arms = self.members.iter().map(|member| {
568      let ident = &member.ident;
569      let word = member.name();
570      quote!(#name::#ident(_) => #word,)
571    });
572    quote! {
573      fn #held(value: &#name) -> &'static ::core::primitive::str {
574        match value { #(#arms)* }
575      }
576    }
577  }
578
579  /// What that table is called. Inside the anonymous `const`, so it collides with nothing.
580  fn held_fn(&self) -> syn::Ident {
581    format_ident!("__ingraph_held")
582  }
583
584  /// The METHOD face, one block per member in declaration order.
585  fn face(&self) -> proc_macro2::TokenStream {
586    let name = self.name;
587    let members = self.members.iter().map(|member| self.member(member));
588    quote! {
589      #[automatically_derived]
590      impl #name {
591        #(#members)*
592      }
593    }
594  }
595
596  /// One member's seven methods.
597  fn member(&self, member: &UnionMember) -> proc_macro2::TokenStream {
598    let vis = self.vis;
599    let name = self.name;
600    let error = &self.error;
601    let held = self.held_fn();
602    let ident = &member.ident;
603    let ty = &member.ty;
604    let word = member.word();
605    let asked = member.name();
606
607    let predicate = Face::Predicate.name(&word);
608    let unwrap = Face::Unwrap.name(&word);
609    let unwrap_ref = Face::UnwrapRef.name(&word);
610    let unwrap_mut = Face::UnwrapMut.name(&word);
611    let try_unwrap = Face::TryUnwrap.name(&word);
612    let try_unwrap_ref = Face::TryUnwrapRef.name(&word);
613    let try_unwrap_mut = Face::TryUnwrapMut.name(&word);
614
615    let is_doc = format!("Whether this is [`{name}::{ident}`].");
616    let owned_doc = format!("The member [`{name}::{ident}`] carries.");
617    let borrow_doc = format!("A borrow of the member [`{name}::{ident}`] carries.");
618    let exclusive_doc = format!("An exclusive borrow of the member [`{name}::{ident}`] carries.");
619    let panics = format!(
620      "# Panics\nWhen another variant is held. The message names the variant asked for and the one \
621       held, which is [`{error}`]'s own sentence."
622    );
623    let refuses = format!(
624      "# Errors\n[`{error}`] when another variant is held, naming both. The value this was called \
625       on is DROPPED: one refusal serves all three receivers, and a receiver that only borrows has \
626       nothing owned to hand back."
627    );
628    let borrowed_refuses =
629      format!("# Errors\n[`{error}`] when another variant is held, naming both.");
630
631    // A ONE-MEMBER union has no wrong variant: its single pattern is irrefutable, so a fallback arm
632    // beside it would be `unreachable_patterns` in the declaring crate — a warning at a span its
633    // author cannot edit, over an arm nothing could ever take.
634    let (owned_held, borrowed_held, refused) = if self.has_a_wrong_variant() {
635      (
636        quote!(let held = #held(&self);),
637        quote!(let held = #held(self);),
638        quote!(_ => ::core::result::Result::Err(#error { asked: #asked, held }),),
639      )
640    } else {
641      (quote!(), quote!(), quote!())
642    };
643
644    quote! {
645      #[doc = #is_doc]
646      #[inline]
647      #[must_use]
648      #vis const fn #predicate(&self) -> ::core::primitive::bool {
649        ::core::matches!(self, Self::#ident(_))
650      }
651
652      #[doc = #owned_doc]
653      #[doc = ""]
654      #[doc = #panics]
655      #[inline]
656      #[must_use]
657      #vis fn #unwrap(self) -> #ty {
658        match self.#try_unwrap() {
659          ::core::result::Result::Ok(member) => member,
660          ::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
661        }
662      }
663
664      #[doc = #borrow_doc]
665      #[doc = ""]
666      #[doc = #panics]
667      #[inline]
668      #[must_use]
669      #vis fn #unwrap_ref(&self) -> &#ty {
670        match self.#try_unwrap_ref() {
671          ::core::result::Result::Ok(member) => member,
672          ::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
673        }
674      }
675
676      #[doc = #exclusive_doc]
677      #[doc = ""]
678      #[doc = #panics]
679      #[inline]
680      #[must_use]
681      #vis fn #unwrap_mut(&mut self) -> &mut #ty {
682        match self.#try_unwrap_mut() {
683          ::core::result::Result::Ok(member) => member,
684          ::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
685        }
686      }
687
688      #[doc = #owned_doc]
689      #[doc = ""]
690      #[doc = #refuses]
691      #[inline]
692      #vis fn #try_unwrap(self) -> ::core::result::Result<#ty, #error> {
693        // The held name is read BEFORE the match, so all three receivers are one shape: the
694        // exclusive one cannot ask afterwards without borrowing what it is about to hand out.
695        #owned_held
696        match self {
697          Self::#ident(member) => ::core::result::Result::Ok(member),
698          #refused
699        }
700      }
701
702      #[doc = #borrow_doc]
703      #[doc = ""]
704      #[doc = #borrowed_refuses]
705      #[inline]
706      #vis fn #try_unwrap_ref(&self) -> ::core::result::Result<&#ty, #error> {
707        #borrowed_held
708        match self {
709          Self::#ident(member) => ::core::result::Result::Ok(member),
710          #refused
711        }
712      }
713
714      #[doc = #exclusive_doc]
715      #[doc = ""]
716      #[doc = #borrowed_refuses]
717      #[inline]
718      #vis fn #try_unwrap_mut(&mut self) -> ::core::result::Result<&mut #ty, #error> {
719        #borrowed_held
720        match self {
721          Self::#ident(member) => ::core::result::Result::Ok(member),
722          #refused
723        }
724      }
725    }
726  }
727}