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
715
716
717
718
719
720
721
722
723
724
725
726
727
//! The UNION face: what an enum whose variants CARRY their members expands into.
//!
//! A union is not a node and not a value a column holds. It is a CHOICE — one of several member
//! types, named by the variant that carries it — and the whole of what this half writes is the way
//! Rust asks that choice: which member is held, and how to get at it.
//!
//! # Which unions this derive is for
//!
//! The DECLARED ones. A schema's `union SearchResult = Media | Video` and its input-position twin
//! are both a payload-carrying enum somebody WROTE, and this derive equips it — the same direction
//! [`crate::enumeration`] takes with a vocabulary. The other payload enums in this framework are
//! the FAN-IN ones a node with several upstreams gets, and those are the node macros' own emission:
//! nobody writes them, so there is nothing for a derive to be applied to.
//!
//! # The shape, and the law it comes from
//!
//! Every variant carries exactly ONE unnamed payload, and that payload's type is the member. The
//! shape is not this crate's taste — it is what a declared union renders as at both positions a
//! schema has for one, and the input position is the tighter of the two: an `@oneOf` input object
//! is an enum of single-value TUPLE variants and nothing else.
//!
//! GraphQL's own type validation is where the rest of the refusals come from, quoted rather than
//! paraphrased: *A Union type must include one or more unique member types.* That one sentence is
//! the empty union's refusal and the duplicated member's both.
//!
//! # The face is a SEAM, because a union is not the only member set
//!
//! [`Equipped`] is the emission, and [`UnionModel::emit`] is one caller of it. An INTERFACE is a
//! member set too — one with a contract over it — so it declares the same Rust shape and wants the
//! same question asked: which member is held, and how to get at it. Written once, the second caller
//! inherits the emission rather than a copy of it, and the two cannot come to spell one method
//! differently.
//!
//! # The face is HAND-EMITTED, and it is the whole of what this half writes
//!
//! `is_<member>`, `unwrap_<member>` and `try_unwrap_<member>`, the latter two in all three
//! receivers — owned, `_ref`, `_mut`. The suffix spelling is `derive_more`'s `#[unwrap(ref,
//! ref_mut)]` semantics restated as OURS, and `derive_more` itself is not a dependency of THIS
//! emission: its `TryUnwrapError` would put a foreign path in every consumer's expanded code and a
//! foreign type in the signatures a caller writes. (The framework crate does depend on it, for its
//! own `Emission<Out>` — an enum of this exact shape carrying those exact attributes. That is a
//! foreign path in `ingraph`'s own source, which is nobody else's expansion.)
//!
//! The two agree on the SUFFIXES and part company on the WORD, and the divergence is deliberate.
//! `derive_more` cases a variant through `convert_case`, whose default boundaries include
//! `LOWER_DIGIT` and `UPPER_DIGIT`, so a variant `Vp9` reaches it as `vp_9`. This framework cases
//! through `heck`, where the same variant is `vp9` — which is what the vocabulary derive already
//! emits and what its collision refusal already names. A variant spelled one way in Rust must
//! derive ONE word in this framework, whether it is a vocabulary's member or a union's, so the word
//! is the house's and only the suffixes are borrowed.
//!
//! Only `is_<member>` is `const`. The unwrap family cannot be: a receiver that takes `self` DROPS
//! the payload it did not match, and a `const fn` may not drop a value whose type could implement
//! [`Drop`] — so the owned pair is out on its own terms, and a family whose three receivers
//! differed in constness would read as an accident rather than a rule.
//!
//! # The refusal carries the pair, and its construction is SEALED
//!
//! `<Union>UnwrapError` holds the variant ASKED for and the variant HELD, as `&'static str` the
//! expansion mints. Not the empty payload a vocabulary's parse refusal takes: there the caller
//! already holds the word that failed, and here the two names are the whole content of what went
//! wrong. The fields are private, so nothing outside the declaring module builds one; the pair is
//! read back through the emitted `asked()` and `held()`, and the
//! [`Display`](core::fmt::Display) sentence is written from them once. The framework's `name` shelf
//! offers nothing that fits: its five name types spell what ONE NAMESPACE calls a vocabulary's
//! member — a stored word or a wire word — and a Rust variant's own spelling is neither.
//!
//! One refusal serves all three receivers, and that is what settles the question of handing the
//! held value back: a borrowing receiver has nothing owned to return, so an error carrying the
//! union would have to be a different type per receiver. The owned `try_unwrap_<member>` therefore
//! DROPS what it did not match, which is the trade written into the emitted `# Errors` note.
//!
//! # The REFUSAL is the ONE name this expansion puts in the declaring scope
//!
//! Everything else sits inside an anonymous `const`, where it collides with nothing anybody wrote.
//! The refusal cannot: it is named in signatures a caller writes. `unwrap_error(rename = "…")` is
//! the escape, read through the same shared block reader `Record`'s `key(…)` and the vocabulary's
//! own `error(…)` go through — one grammar, so a third derive invents no wording for a rule the
//! first two already have. The word is `unwrap_error` and not `error` because `error` names the
//! CONVERSION CELLS, one per leg inside a database's block: what a fallible crossing refuses with is
//! not what a wrong-variant unwrap answers with.
//!
//! # The WIRE ROUND arrived, and it is what bought `crate = "…"`
//!
//! The method face above is `core` and nothing else, and while it was the whole emission there was
//! nothing for a `crate` option to move. [`wire`] changed that: a declared union's backend
//! implementations are HAND-EMITTED off [`UnionModel`] (their derive does not ride a model slot,
//! unlike the order-by's — the ruling of 2026-08-05), every name in them is reached through
//! `#krate::__private`, and the gate they ride is reached the same way. So [`UnionModel::krate`] is
//! the path this expansion is rooted at, exactly as [`crate::enumeration`]'s is.
//!
//! There is still no `wire_derive`, and now for a stronger reason than *not yet*: a DERIVE may only
//! append, so nothing here can put `#[derive(async_graphql::Union)]` on an enum somebody else wrote
//! — the same wall `crate::index`'s own union face states. Both faces are written out.
//!
//! # The two faces are IMPLS ON THE DECLARED ENUM, and that decides the naming law
//!
//! `output` is the schema's `union X = A | B`; `input` is its `@oneOf` input object. Both are
//! written onto the type the declaration already named, so a union that declares both puts TWO
//! schema types on ONE Rust type — and a schema has one namespace for type names. Hence the law
//! [`UnionSkin::input_sdl`] carries: a single face takes the union's own name, and where both are
//! rendered the output keeps it and the input derives `<Union>Input`.
//!
//! **Both faces are movable**, and the rename-parity ruling is what made the pair symmetric:
//! `input(rename = "…")` names the twin, `output(rename = "…")` names the union itself and carries
//! the derived twin with it. The law above is untouched by either — it decides which face keeps the
//! DEFAULT, which is a different question from whether an author may name one.
//!
//! # A union is not a column
//!
//! No storage rows, at any backend. No scenario stores one: both declared positions are wire
//! shapes, and fan-in addresses its upstreams by `(tag, id)` rather than by a stored payload. Were
//! one ever to persist, the shape is already ruled — a discriminant column beside one side table
//! per member — and it is a design round that starts there rather than at a tagged blob.

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

use crate::model::GraphqlKind;

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

/// One method the face declares for one member.
///
/// The whole vocabulary of derived names, for the reason [`Member`](crate::method::Member) is a
/// vocabulary rather than five `format_ident!` calls: a suffix written twice is a suffix that can
/// come to be written differently, and a front end refusing a collision has to spell exactly the
/// names the emitter writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Face {
  /// `is_x` — whether this member is the one held.
  Predicate,
  /// `unwrap_x` — the payload, or a panic.
  Unwrap,
  /// `unwrap_x_ref` — a borrow of it, or a panic.
  UnwrapRef,
  /// `unwrap_x_mut` — an exclusive borrow of it, or a panic.
  UnwrapMut,
  /// `try_unwrap_x` — the payload, or the refusal.
  TryUnwrap,
  /// `try_unwrap_x_ref` — a borrow of it, or the refusal.
  TryUnwrapRef,
  /// `try_unwrap_x_mut` — an exclusive borrow of it, or the refusal.
  TryUnwrapMut,
}

impl Face {
  /// Every method a member gets, in the order the emission declares them.
  pub const ALL: [Self; 7] = [
    Self::Predicate,
    Self::Unwrap,
    Self::UnwrapRef,
    Self::UnwrapMut,
    Self::TryUnwrap,
    Self::TryUnwrapRef,
    Self::TryUnwrapMut,
  ];

  /// What this method is called over a member whose word is `word`.
  #[must_use]
  pub fn name(self, word: &syn::Ident) -> syn::Ident {
    match self {
      Self::Predicate => format_ident!("is_{word}"),
      Self::Unwrap => format_ident!("unwrap_{word}"),
      Self::UnwrapRef => format_ident!("unwrap_{word}_ref"),
      Self::UnwrapMut => format_ident!("unwrap_{word}_mut"),
      Self::TryUnwrap => format_ident!("try_unwrap_{word}"),
      Self::TryUnwrapRef => format_ident!("try_unwrap_{word}_ref"),
      Self::TryUnwrapMut => format_ident!("try_unwrap_{word}_mut"),
    }
  }
}

/// The word a variant's methods are built on — `media` for `Media`, `type` for `r#type`.
///
/// Free rather than only a method on [`UnionMember`], because a front end refusing a variant it did
/// NOT accept as a member still has to name the method that variant would have had: a refusal
/// spelling that word itself would be a second copy of this rule.
///
/// Over the RUST spelling, because the methods are Rust and their reader is looking at the variant.
#[must_use]
pub fn word(ident: &syn::Ident) -> syn::Ident {
  use syn::ext::IdentExt as _;

  format_ident!("{}", ident.unraw().to_string().to_snake_case())
}

/// What the refusal a wrong-variant unwrap answers with is called when nothing renamed it:
/// `<Enum>UnwrapError`.
///
/// The convention's ONE home, for the reason [`crate::model`]'s defaulted names are theirs: a
/// second member set equipped through the same seam takes the same suffix, and a suffix written
/// twice is a suffix that can come to be written differently.
#[must_use]
pub fn default_unwrap_error_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}UnwrapError")
}

/// What a SCHEMA calls a union's input object where the output face already holds the union's own
/// name: `<Union>Input`.
///
/// The convention's ONE home, beside [`default_unwrap_error_name`] and for its reason. It answers a
/// `String` rather than an `Ident` because the name it derives is a SCHEMA entity's — nothing in
/// Rust is called this, both faces being impls on the enum the declaration already named — so the
/// `r#` a raw enum carries is dropped here as it is everywhere a word leaves Rust.
#[must_use]
pub fn default_input_sdl_name(base: &syn::Ident) -> String {
  input_sdl_name(&base.unraw().to_string())
}

/// The same convention over a base that is already a SCHEMA word — what a renamed face composes its
/// input twin's name from.
///
/// The two entries exist because the base arrives two ways and the suffix must not: a declaration
/// that renamed nothing has an `Ident` to unraw, one that wrote `rename = "…"` has a literal that was
/// never Rust. Both reach this line, which is the ONE blessed derivation the rename laws name —
/// `key(rename = "Address")` publishing `Address` and `AddressInput` is the same composition one
/// grammar over.
#[must_use]
pub fn input_sdl_name(base: &str) -> String {
  format!("{base}Input")
}

/// The SEAT one member takes in the `@oneOf` input object — `media` for `Media`, `videoClip` for
/// `VideoClip`.
///
/// async-graphql's own `OneofObject` default (`rename_fields = "camelCase"` over the variant), spelled
/// here because no derive of that library's can be reached: the face is hand-emitted, so the word it
/// publishes has to be written.
///
/// Free rather than a method on [`UnionMember`], for the reason [`word`] is: a front end refusing a
/// variant it did not accept still has to be able to name the seat that variant would have had.
///
/// **Two variants cannot collide here without colliding at [`word`] first.** Both are joins of the
/// same case-split word list, so one snake spelling is one lower-camel spelling, and the METHOD
/// collision the shared member walk already refuses covers this face too.
#[must_use]
pub fn seat(ident: &syn::Ident) -> String {
  use heck::ToLowerCamelCase as _;

  ident.unraw().to_string().to_lower_camel_case()
}

/// One member: the variant that names it and the type it is.
#[derive(Debug, Clone)]
pub struct UnionMember {
  /// The variant as Rust spells it, `r#` and all.
  pub ident: syn::Ident,
  /// The single unnamed payload the variant carries — the member type itself.
  pub ty: syn::Type,
}

impl UnionMember {
  /// The variant's own name, unraw'd — what a message and the refusal's payload spell it as.
  ///
  /// The `r#` is Rust's escape for a word that collides with its grammar and no part of the name,
  /// so a variant called `r#type` is `type` in a sentence about it.
  #[must_use]
  pub fn name(&self) -> String {
    use syn::ext::IdentExt as _;

    self.ident.unraw().to_string()
  }

  /// The word every method of this member is built on — `media` for `Media`.
  #[must_use]
  pub fn word(&self) -> syn::Ident {
    word(&self.ident)
  }
}

/// The INPUT face's declaration: that a backend renders one, and what a schema calls it.
///
/// A struct where a `bool` would do, because the presence and the NAME are one decision and the
/// name is the half a declaration can move: `input` alone is the derived name, `input(rename = "…")`
/// is the same face under a word the declaration chose.
#[derive(Debug, Clone, Default)]
pub struct UnionInput {
  /// `input(rename = "…")` — what a client calls this input object, where the declaration moved it.
  ///
  /// `None` is [`UnionSkin::input_sdl`]'s law: the union's own name where nothing else claims it,
  /// and the `Input` suffix over the OUTPUT's word where the output face claims it.
  pub rename: Option<syn::LitStr>,
}

/// The OUTPUT face's declaration: that a backend renders one, and what a schema calls it.
///
/// [`UnionInput`]'s twin, one position over and the same shape for the same reason. It arrived with
/// the rename-parity ruling, replacing a bare `bool` and the sentence *no rename knob, and the
/// absence is the ruling rather than an omission* that stood on
/// [`output_sdl`](UnionSkin::output_sdl).
///
/// **What that sentence was actually right about was the DEFAULT, not the knob.** The naming law it
/// pointed at decides which face keeps the union's own name when both are rendered — the output,
/// because that is the one a client writes in a selection set — and it still does. What it does not
/// decide is whether an author whose scope already holds a `Frame` may publish this union as
/// something else, and the answer to that had been *no word for it*.
#[derive(Debug, Clone, Default)]
pub struct UnionOutput {
  /// `output(rename = "…")` — what a client calls this union, where the declaration moved it.
  ///
  /// `None` is the enum's own name unraw'd. Where it is written it re-bases the input twin too —
  /// see [`UnionSkin::input_sdl`], where the one blessed derivation is spent.
  pub rename: Option<syn::LitStr>,
}

/// ONE GraphQL backend's rendering of a declared union — which of the two schema positions it is
/// dressed for.
///
/// The pair is the whole vocabulary and neither is implied by the other: a union declared for input
/// alone is an `@oneOf` argument object nothing returns, and one declared for output alone is a
/// result type no argument takes. A backend named with NEITHER word is refused at the declaration —
/// a block that dresses no position dresses nothing.
#[derive(Debug, Clone)]
pub struct UnionSkin {
  /// Which backend this is.
  pub kind: GraphqlKind,
  /// `output` — the schema's `union X = A | B`, in a RETURN position.
  pub output: Option<UnionOutput>,
  /// `input` — the schema's `@oneOf` input object, in an ARGUMENT position.
  pub input: Option<UnionInput>,
}

impl UnionSkin {
  /// What a schema calls this union's OUTPUT face — `output(rename = "…")`, else the enum's own name
  /// unraw'd.
  ///
  /// The default is [`input_sdl`](Self::input_sdl)'s law read from the other side: where both faces
  /// are rendered the output is the one that keeps the union's own word, because it is the one a
  /// client names in a selection set. The knob moves that word without touching the law — and it
  /// moves the twin with it.
  #[must_use]
  pub fn output_sdl(&self, base: &syn::Ident) -> String {
    match self
      .output
      .as_ref()
      .and_then(|output| output.rename.as_ref())
    {
      Some(declared) => declared.value(),
      None => base.unraw().to_string(),
    }
  }

  /// What a schema calls this union's INPUT face.
  ///
  /// # The naming law, whole
  ///
  /// Both faces are impls on ONE Rust type, and a GraphQL schema has ONE namespace for type names.
  /// So:
  ///
  /// * a union rendering ONE face — either one — publishes it under the union's own name, there
  ///   being nothing else to collide with;
  /// * a union rendering BOTH gives the union's own name to the OUTPUT and derives the input's by
  ///   suffixing it, because the output type is the one a client names in a selection set and an
  ///   argument object is the derived twin of it.
  ///
  /// `input(rename = "…")` moves this word and only this word, at either arity: a declaration whose
  /// scope already publishes a `<Union>Input` needs the escape as much as one that simply prefers
  /// another name.
  ///
  /// # The derived twin follows the OUTPUT's word, not the Rust ident
  ///
  /// `output(rename = "Sighting")` on a both-faces union publishes `Sighting` and `SightingInput`,
  /// which is the ONE BLESSED DERIVATION the rename laws name — the same composition
  /// `key(rename = "Address")` spends to publish `Address` and `AddressInput`. Composing off the Rust
  /// ident instead would publish the renamed union beside an input object still wearing the old
  /// stem: a rename that moved one face and not the other, which the naming law calls worse than
  /// none.
  #[must_use]
  pub fn input_sdl(&self, base: &syn::Ident) -> String {
    match self.input.as_ref().and_then(|input| input.rename.as_ref()) {
      Some(declared) => declared.value(),
      None if self.output.is_some() => input_sdl_name(&self.output_sdl(base)),
      None => base.unraw().to_string(),
    }
  }
}

/// One union's declaration, validated.
///
/// Public fields for the reason [`RecordModel`](crate::model::RecordModel)'s are: nothing here
/// parses, so a front end that is not the derive builds the same struct and reaches the same
/// emitter.
#[derive(Debug, Clone)]
pub struct UnionModel {
  /// Where `ingraph` lives, for every path the WIRE half emits. The method face names none.
  pub krate: syn::Path,
  /// The declaration's visibility, which every emitted item takes.
  pub vis: syn::Visibility,
  /// The declared enum's own name.
  pub name: syn::Ident,
  /// Its members, in declaration order. Never empty, and never two of one type.
  pub members: Vec<UnionMember>,
  /// What the emitted REFUSAL type is called, when the declaration named it.
  ///
  /// `None` is `<Union>UnwrapError`, which is what [`UnionModel::error`] resolves.
  pub error: Option<syn::Ident>,
  /// The backends this union is dressed for, in declaration order. EMPTY is a union with no wire
  /// face at all, which is what a declaration writing no `graphql(…)` block keeps.
  pub graphql: Vec<UnionSkin>,
}

impl UnionModel {
  /// The refusal type a wrong-variant unwrap answers with — the declared name, else
  /// `FoundUnwrapError`.
  ///
  /// The ONE authority on what that type is called: the emission writes this, and a front end's
  /// collision check asks it rather than rebuilding the suffix convention on its own side.
  #[must_use]
  pub fn error(&self) -> syn::Ident {
    self
      .error
      .clone()
      .unwrap_or_else(|| default_unwrap_error_name(&self.name))
  }

  /// The whole expansion: the refusal type, the method face, and the wire faces a declaration asked
  /// for.
  ///
  /// The WIRE half is a block of its own rather than a member of the seam's, for the reason
  /// [`EnumModel::emit`](crate::enumeration::EnumModel::emit) keeps its own separate: the whole of
  /// it sits behind the binding gate, and a gate wrapping one block's entire body is what lets a
  /// build without `async-graphql` expand it to nothing at all.
  ///
  /// It is also what keeps the SEAM untouched. [`Equipped`] is shared with the interface derive,
  /// which has a wire face of its own and no use for this one — so the union's backend impls hang
  /// off the MODEL, one layer above the emission both member sets reach.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let equipped = self.equipped().emit();
    let wire = self.graphql_faces();
    quote! {
      #equipped
      #wire
    }
  }

  /// This union as the SEAM sees it — a payload-carrying enum, its members, and what its refusal is
  /// called.
  fn equipped(&self) -> Equipped<'_> {
    Equipped {
      vis: &self.vis,
      name: &self.name,
      members: &self.members,
      error: self.error(),
    }
  }
}

/// A payload-carrying enum, equipped — the face and the refusal, independent of what the enum
/// MEANS.
///
/// The seam two derives reach. A union IS its member set and an INTERFACE is a member set with a
/// contract over it, so both declare the same Rust shape and both want the same question asked of
/// it: which member is held, and how to get at it. Written once here, so the second derive to want
/// it inherits the emission rather than a copy of it — and so the two cannot come to spell one
/// method differently.
///
/// Borrows rather than owns, and takes the refusal's name RESOLVED: whichever model built one has
/// already settled what its own defaults are, and a seam that re-derived a name would be the second
/// copy of the convention this shape exists to avoid.
pub(crate) struct Equipped<'a> {
  /// The declaration's visibility, which every emitted item takes.
  pub(crate) vis: &'a syn::Visibility,
  /// The declared enum's own name.
  pub(crate) name: &'a syn::Ident,
  /// Its members, in declaration order.
  pub(crate) members: &'a [UnionMember],
  /// What the emitted REFUSAL type is called, already resolved.
  pub(crate) error: syn::Ident,
}

impl Equipped<'_> {
  /// The whole expansion: the refusal type, then the face.
  pub(crate) fn emit(&self) -> proc_macro2::TokenStream {
    let error = self.refusal();
    let held = self.held();
    let face = self.face();
    quote! {
      #error

      const _: () = {
        #held
        #face
      };
    }
  }

  /// The refusal a wrong-variant unwrap answers with, and the two names it carries.
  fn refusal(&self) -> proc_macro2::TokenStream {
    let vis = self.vis;
    let name = self.name;
    let error = &self.error;
    let sentence = format!("`{name}`: asked for `{{}}`, held `{{}}`");
    let doc = format!(
      "The refusal an unwrap into a variant a [`{name}`] is not holding answers with.\n\nSealed \
       rather than empty: its fields are private, so nothing outside this module builds one, and it \
       carries the pair that says what went wrong — the variant asked for and the variant held."
    );
    let asked = format!("The variant the call asked [`{name}`] for.");
    let held = format!("The variant that [`{name}`] was holding instead.");
    quote! {
      #[doc = #doc]
      #[derive(Debug, Clone, Copy, PartialEq, Eq)]
      #vis struct #error {
        asked: &'static ::core::primitive::str,
        held: &'static ::core::primitive::str,
      }

      #[automatically_derived]
      impl #error {
        #[doc = #asked]
        #[inline]
        #[must_use]
        #vis const fn asked(&self) -> &'static ::core::primitive::str {
          self.asked
        }

        #[doc = #held]
        #[inline]
        #[must_use]
        #vis const fn held(&self) -> &'static ::core::primitive::str {
          self.held
        }
      }

      #[automatically_derived]
      impl ::core::fmt::Display for #error {
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          ::core::write!(f, #sentence, self.asked, self.held)
        }
      }

      #[automatically_derived]
      impl ::core::error::Error for #error {}
    }
  }

  /// Whether this union has a WRONG variant at all.
  ///
  /// One member is a legal declaration — GraphQL's law is *one or more* — and it is the shape where
  /// every unwrap succeeds: there is no other variant to be holding, so the refusal is a type in
  /// the signatures and nothing the expansion can build.
  fn has_a_wrong_variant(&self) -> bool {
    self.members.len() > 1
  }

  /// The one table saying which variant a union is holding, called by every refusal the face
  /// builds.
  ///
  /// One table rather than an arm written into each method, for the reason a vocabulary's reverse
  /// map is written once: several copies of one mapping are several things that can come to
  /// disagree, and the disagreement is invisible — each is right in isolation and only the set is
  /// wrong.
  ///
  /// Absent from a ONE-MEMBER union, where it would have no caller: its single pattern is
  /// irrefutable, so the methods below match it and stop.
  fn held(&self) -> proc_macro2::TokenStream {
    if !self.has_a_wrong_variant() {
      return quote!();
    }
    let name = self.name;
    let held = self.held_fn();
    let arms = self.members.iter().map(|member| {
      let ident = &member.ident;
      let word = member.name();
      quote!(#name::#ident(_) => #word,)
    });
    quote! {
      fn #held(value: &#name) -> &'static ::core::primitive::str {
        match value { #(#arms)* }
      }
    }
  }

  /// What that table is called. Inside the anonymous `const`, so it collides with nothing.
  fn held_fn(&self) -> syn::Ident {
    format_ident!("__ingraph_held")
  }

  /// The METHOD face, one block per member in declaration order.
  fn face(&self) -> proc_macro2::TokenStream {
    let name = self.name;
    let members = self.members.iter().map(|member| self.member(member));
    quote! {
      #[automatically_derived]
      impl #name {
        #(#members)*
      }
    }
  }

  /// One member's seven methods.
  fn member(&self, member: &UnionMember) -> proc_macro2::TokenStream {
    let vis = self.vis;
    let name = self.name;
    let error = &self.error;
    let held = self.held_fn();
    let ident = &member.ident;
    let ty = &member.ty;
    let word = member.word();
    let asked = member.name();

    let predicate = Face::Predicate.name(&word);
    let unwrap = Face::Unwrap.name(&word);
    let unwrap_ref = Face::UnwrapRef.name(&word);
    let unwrap_mut = Face::UnwrapMut.name(&word);
    let try_unwrap = Face::TryUnwrap.name(&word);
    let try_unwrap_ref = Face::TryUnwrapRef.name(&word);
    let try_unwrap_mut = Face::TryUnwrapMut.name(&word);

    let is_doc = format!("Whether this is [`{name}::{ident}`].");
    let owned_doc = format!("The member [`{name}::{ident}`] carries.");
    let borrow_doc = format!("A borrow of the member [`{name}::{ident}`] carries.");
    let exclusive_doc = format!("An exclusive borrow of the member [`{name}::{ident}`] carries.");
    let panics = format!(
      "# Panics\nWhen another variant is held. The message names the variant asked for and the one \
       held, which is [`{error}`]'s own sentence."
    );
    let refuses = format!(
      "# Errors\n[`{error}`] when another variant is held, naming both. The value this was called \
       on is DROPPED: one refusal serves all three receivers, and a receiver that only borrows has \
       nothing owned to hand back."
    );
    let borrowed_refuses =
      format!("# Errors\n[`{error}`] when another variant is held, naming both.");

    // A ONE-MEMBER union has no wrong variant: its single pattern is irrefutable, so a fallback arm
    // beside it would be `unreachable_patterns` in the declaring crate — a warning at a span its
    // author cannot edit, over an arm nothing could ever take.
    let (owned_held, borrowed_held, refused) = if self.has_a_wrong_variant() {
      (
        quote!(let held = #held(&self);),
        quote!(let held = #held(self);),
        quote!(_ => ::core::result::Result::Err(#error { asked: #asked, held }),),
      )
    } else {
      (quote!(), quote!(), quote!())
    };

    quote! {
      #[doc = #is_doc]
      #[inline]
      #[must_use]
      #vis const fn #predicate(&self) -> ::core::primitive::bool {
        ::core::matches!(self, Self::#ident(_))
      }

      #[doc = #owned_doc]
      #[doc = ""]
      #[doc = #panics]
      #[inline]
      #[must_use]
      #vis fn #unwrap(self) -> #ty {
        match self.#try_unwrap() {
          ::core::result::Result::Ok(member) => member,
          ::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
        }
      }

      #[doc = #borrow_doc]
      #[doc = ""]
      #[doc = #panics]
      #[inline]
      #[must_use]
      #vis fn #unwrap_ref(&self) -> &#ty {
        match self.#try_unwrap_ref() {
          ::core::result::Result::Ok(member) => member,
          ::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
        }
      }

      #[doc = #exclusive_doc]
      #[doc = ""]
      #[doc = #panics]
      #[inline]
      #[must_use]
      #vis fn #unwrap_mut(&mut self) -> &mut #ty {
        match self.#try_unwrap_mut() {
          ::core::result::Result::Ok(member) => member,
          ::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
        }
      }

      #[doc = #owned_doc]
      #[doc = ""]
      #[doc = #refuses]
      #[inline]
      #vis fn #try_unwrap(self) -> ::core::result::Result<#ty, #error> {
        // The held name is read BEFORE the match, so all three receivers are one shape: the
        // exclusive one cannot ask afterwards without borrowing what it is about to hand out.
        #owned_held
        match self {
          Self::#ident(member) => ::core::result::Result::Ok(member),
          #refused
        }
      }

      #[doc = #borrow_doc]
      #[doc = ""]
      #[doc = #borrowed_refuses]
      #[inline]
      #vis fn #try_unwrap_ref(&self) -> ::core::result::Result<&#ty, #error> {
        #borrowed_held
        match self {
          Self::#ident(member) => ::core::result::Result::Ok(member),
          #refused
        }
      }

      #[doc = #exclusive_doc]
      #[doc = ""]
      #[doc = #borrowed_refuses]
      #[inline]
      #vis fn #try_unwrap_mut(&mut self) -> ::core::result::Result<&mut #ty, #error> {
        #borrowed_held
        match self {
          Self::#ident(member) => ::core::result::Result::Ok(member),
          #refused
        }
      }
    }
  }
}