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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! The INTERFACE face: a member set with a CONTRACT over it.
//!
//! An interface is a union plus a promise. The union half is the same payload-carrying enum
//! [`crate::union`] equips — one variant per member, each carrying that member — and the promise is
//! the `fields(…)` list: every member has these fields, at these types, and the ones the
//! declaration marks COMPUTED are derived rather than stored.
//!
//! # It is a PSEUDO-RECORD, and today it declares only the promise
//!
//! An interface names no table and mints no id. What it has instead is the set of its members'
//! rows, which is why its query layer is a fan-out rather than a select — and that layer is not
//! this round's. What lands here is the DECLARATION and the TEETH: the contract as a Rust trait,
//! the per-member implementations of it, and one type equation per (stored field, database, member)
//! saying the member's row really carries the column at the type the interface pinned.
//!
//! # The three TIERS a field can be in, and the two FACES they land on
//!
//! | tier | written | every member | whose face carries it |
//! |---|---|---|---|
//! | stored | nothing, or `persist(<db>(type = "…"))` | carries the column | `<I>Fields`, on the MEMBER |
//! | computed | `graphql(computed)` | DERIVES the value | `<I>Derivations`, on the member's wire OUTPUT |
//! | try_computed | `graphql(try_computed)` | derives it, fallibly | the same, returning a `Result` |
//!
//! Stored and computed are MUTUALLY EXCLUSIVE, in both directions: a value a member derives is not
//! a column its row holds, and a column its row holds is not a value it derives. The front end
//! refuses either spelling of the pair rather than electing one.
//!
//! **The domain contract is STORED-ONLY**, and the split is the ruling rather than a staging. A
//! computed field is a QUERY-LAYER construct — it is derived to be answered, and what answers a
//! query is the wire output — so putting it on the domain trait would have made every member's
//! domain type owe a method its rows have no column for and its pipeline never asks. `<I>Fields`
//! therefore carries the stored tier and nothing else, and the computed tier is
//! `<I>Derivations`, whose implementors are the members' GraphQL OUTPUT types.
//!
//! `<I>Derivations` is DECLARED here and implemented nowhere: the emission writes the trait, and a
//! member's output type writes the impl by hand. There is no escape machinery under it for the same
//! reason — a hand author writes their own glue, and a generated adapter would be a seam nobody
//! asked for. The interface's own output face is what consumes it, and that face is the find half's.
//!
//! # A member may call a stored field something else, and the INTERFACE is where it says so
//!
//! `created_at(type = "Timestamp", members(Audio(field = "imported_at")))`: the member `Audio` carries this
//! field as `imported_at`, in its own struct and in its own row.
//!
//! HERE rather than on the member, and the reason is what a macro can see. A member-side word would
//! have to reach an interface's expansion across a derive boundary, and the only things that cross
//! one are a type and a const — neither of which produces the IDENT a field access needs. Written
//! on the interface, every hop of the chain is backed by the SAME derive input: the block's key is
//! checked token-for-token against the enum's own variants, the variant names the payload type it
//! carries, that type projects to `<M as Record<Db>>::Row`, and the declared ident is what the
//! access spells.
//!
//! It extends the axis one step, and the step is INTERFACE-SPECIFIC: interface field block ▸
//! `members(…)` ▸ one block per variant ▸ entries. A record grows no member axis, having no members
//! — so this is the one grammar in the framework where a block's key is a variant rather than a
//! database or a domain, and the container is what says where that holds. POSITION decides: outside
//! it every key is a word the grammar owns, inside it every key is a variant.
//!
//! # The names this expansion puts in the declaring scope
//!
//! [`InterfaceModel::emitted_types`] is the list, and each name arrives with what it IS: the sealed
//! refusal the union half writes, the CONTRACT trait, the DERIVATIONS trait a member writes its
//! computed half through, the DISCRIMINANT, the two ADDRESSES over it — the id sum a row carries
//! and the key sum a hit will — one PROJECTION ROW per SQL database the declaration is about, the
//! page's cursor and predicate, the order-by, and the two the wire query surface is: the FILTER a
//! client sends and the ARGUMENT object that carries it.
//!
//! The RESERVED list is empty, and this is where it ended. Every name on it had a function here and
//! no emission — the point being that a name decided when its emission lands is a name decided
//! twice — and each has since been taken by the emission that reserved it. The KEY was the last,
//! and it is the one that left by RULING rather than by a consumer: it is the fusion seam's premise,
//! so it is minted before that seam rather than with it.
//!
//! # `crate = "…"` exists here where the union has none
//!
//! A union's whole expansion is `core`, so there is nothing for the option to move. An interface's
//! is not: the membership evidence, the storability the equations read a row through, and the
//! backend gates they ride are all framework names, so the declaration states its root once and
//! every emitted path follows it.

use quote::format_ident;

use crate::{
  model::{AliasOptions, DatabaseKind, Declared, Label, Marker, Role, boxed_error, stored_type},
  prefix::EmissionPrefix,
  union::{UnionMember, default_unwrap_error_name},
};

mod binding;
mod contract;
mod cross;
mod equations;
mod face;
mod hydrate;
mod order;
mod page;
mod queries;
mod row;
mod union_face;
mod wire;

#[cfg(test)]
mod tests;

/// One interface'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 InterfaceModel {
  /// The EMISSION NAMESPACE this declaration's minted names wear.
  ///
  /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
  /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
  /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
  pub prefix: EmissionPrefix,
  /// The declaration's visibility, which every emitted item takes.
  pub vis: syn::Visibility,
  /// The declared enum's own name.
  pub name: syn::Ident,
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  pub krate: syn::Path,
  /// Its members, in declaration order. Never empty, and never two of one type.
  ///
  /// The UNION's own member type, because a member is the same thing in both declarations: the
  /// variant that names it and the type it carries. Sharing it is what lets one seam equip both.
  pub members: Vec<UnionMember>,
  /// The fields every member promises, in declaration order.
  pub fields: Vec<InterfaceField>,
  /// What the emitted REFUSAL type is called, when the declaration named it.
  ///
  /// `None` is `<Interface>UnwrapError`, which is what [`InterfaceModel::error`] resolves.
  pub error: Option<syn::Ident>,
  /// `graphql(computed(error = "…"))` — the type every FALLIBLE computed field answers with.
  ///
  /// ONE cell and DB-LESS, which is the ruled exception to this grammar's database blocks: a
  /// computed value is derived from the member rather than read out of a row, so the crossing names
  /// no database and there is nothing for a per-database cell to differ about. `None` is the boxed
  /// refusal — see [`InterfaceModel::computed_error`].
  pub computed_error: Option<syn::Path>,
  /// The databases the interface's own `persist(…)` block named, in the order they were written.
  ///
  /// A SELECTION rather than a storage declaration: an interface owns no table, so what this does
  /// is say which databases the row equations are checked at. A field's own per-database pin names
  /// one too, and [`InterfaceModel::databases`] is where the two are joined.
  pub persist: Vec<InterfaceDatabase>,
  /// `persist(<db>(try_into(error = "…")))` — what HYDRATING a page of this interface refuses with,
  /// per database. Never two for one database.
  ///
  /// The `try_into` LEG, and it is the read direction the verb rule names: a page's rows leave
  /// storage for the members' own wire outputs, and every refusal on that path — the driver's, the
  /// members' own crossings, and the coherence check between the union and the gather — unifies
  /// here. `None` for a database is the boxed refusal, which absorbs all three through `core`'s own
  /// blanket.
  ///
  /// The other three legs stay REFUSED at the front end: `from`, `try_from` and `into` type
  /// crossings an interface performs nowhere, and an entry nobody reads is a rule its author
  /// believes they declared.
  pub errors: Vec<InterfaceError>,
  /// `graphql(input(comparison(<db>(try_into(error = "…")))))` — what CROSSING a wire filter into
  /// this database's predicate refuses with, per database. Never two for one database.
  ///
  /// The `try_into` leg again, and the direction is the same one the verb rule names one axis over:
  /// a filter's operands LEAVE the wire for the types this database stores, so every refusal on
  /// that path — each column's own crossing, and each declared operand converter's — unifies here.
  /// `None` for a database is the boxed refusal.
  ///
  /// Separate from [`InterfaceModel::errors`] because they type two crossings that run at different
  /// moments: one is a page's rows leaving storage, the other is a predicate's operands entering
  /// it. A single cell for both would make a caller catch one to learn about the other.
  pub operand_errors: Vec<InterfaceError>,
  /// `graphql(plural = "…")` — this interface's plural as a WORD, where the pluraliser's answer is
  /// wrong.
  ///
  /// The NAMING TOWER's middle tier, and the record's own knob one declaration over: it moves the
  /// list FIELD and both page type names together, which is the whole of what the tier buys — one
  /// correction of English rather than three readers of it.
  ///
  /// `None` is the derived plural, and a derived plural EQUAL to the singular is legal here where a
  /// record refuses it. See [`InterfaceModel::published_plural`].
  pub plural: Option<String>,
  /// `graphql(connection(rename = "…"))` — what the schema calls a page of this interface.
  ///
  /// The tower's TOP, covering the plural-built word outright and independently of the edge's.
  pub connection: Option<String>,
  /// `graphql(edge(rename = "…"))` — what the schema calls one edge of that page.
  pub edge: Option<String>,
}

/// ONE database inside the interface's own `persist(…)`: which, and what its synthetic words are
/// named in.
#[derive(Debug, Clone)]
pub struct InterfaceDatabase {
  /// Which database.
  pub kind: DatabaseKind,
  /// `alias(prefix = "…")` — the namespace this database's SYNTHETIC WORDS are minted in.
  ///
  /// The same knob a record spends on its row-source names, and the same reason for being per
  /// database: one deployment's schema holds legacy tables inside the default namespace and the
  /// others do not. What it moves here is everything the union statement INVENTS — the discriminant
  /// the arms project and the name the outer query gives the derived table.
  ///
  /// [`AliasOptions::depth`] is never filled: an interface owns no table, so it mints no alias array
  /// for a depth to be the length of, and the word is refused where the block is read.
  pub aliases: AliasOptions,
}

/// ONE database's refusal cell for the crossing an interface's hydration performs.
#[derive(Debug, Clone)]
pub struct InterfaceError {
  /// Which database's hydration.
  pub kind: DatabaseKind,
  /// The type it answers with.
  pub error: syn::Path,
}

/// One field of the contract: what every member has, and how.
#[derive(Debug, Clone)]
pub struct InterfaceField {
  /// The field's name — the contract method's name, and the row column's.
  pub name: syn::Ident,
  /// The DOMAIN type, as the declaration spelled it.
  pub ty: syn::Type,
  /// Which tier the field is in.
  pub tier: Tier,
  /// The INTERPRETATION word the pin declared — `list(scalar)`, `string`, `label = "a::Path"` — or
  /// `None` where the type answers for itself.
  ///
  /// # A pin's word is the record's own, and the two readers it splits are what it is FOR
  ///
  /// A collection column has two stored readings and they are different types: the member's ROW
  /// holds the LIST, and the comparison a filter crosses into is keyed on the ELEMENT the database
  /// stores. Nothing about `type = "Vec<u64>"` and `persist(sqlite(type = "i64"))` says which of the
  /// two the pin is — `type Ids = Vec<Uuid7>` and a scalar are the same tokens — so before the word
  /// there was one reading, it was the wrong one at one of the sites, and a collection contract
  /// field was `E0308` at the row equation.
  ///
  /// The record settles the same question the same way, which is what makes this precedent-consistent
  /// rather than a second grammar: its collection interpretation IS word-declared
  /// ([`Label`](crate::model::Label)), and this reads the very same vocabulary through the very same
  /// front-end door.
  ///
  /// [`InterfaceField::collects`] is what every reader asks; the marker itself reaches
  /// [`InterfaceModel::filter_of`], where it picks the filter KIND exactly as a record's does.
  pub marker: Option<Marker>,
  /// `copy`: the type is cheap enough to hand back by value.
  ///
  /// A CLAIM the emitter cannot check, exactly as [`Projection::Copied`](crate::model::Projection)
  /// is: a model carries names and types, not trait implementations, so a field marked `copy` whose
  /// type is not `Copy` produces a contract implementation that does not compile — at the member,
  /// naming the field.
  pub copy: bool,
  /// What each database stores the field at, where the declaration pinned one. Never two for one
  /// database.
  ///
  /// Empty is not "stored nowhere": a database with no pin stores the field at the DOMAIN type,
  /// which is the uniform mapping [`stored_type`] carries for the record's rows as well.
  pub pins: Vec<Pin>,
  /// `graphql(type = "…")` — the WIRE FORM, when it is not the domain type.
  ///
  /// Held rather than spent, and what it is waiting for is the SDL. The filter object deliberately
  /// does not read it: an operand's filter and the comparison's are ONE kind or the crossing between
  /// them cannot be written, and a wire form that moved a `u64` onto a `String` would move the
  /// operand's filter from the scalar kind to the text one. What a declared wire form is for is the
  /// name a schema publishes, and no schema is rendered here — so the entry stays read-and-held
  /// rather than spent on the one face it would make unwritable.
  pub wire: Option<syn::Type>,
  /// `graphql(input(comparison(<db>(try_into = "…"))))` — what carries this field's OPERAND across
  /// into one database's stored form. Never two for one database.
  ///
  /// The declared leg REPLACES the whole chain for that database, which is the grammar's own law:
  /// a field with no entry crosses through the stored type's own [`TryFrom`], and one with an entry
  /// crosses through the named function and never asks the type. Empty is the former.
  pub operands: Vec<Operand>,
  /// `members(<Variant>(field = "…"))` — what ONE member calls this field, where it calls it
  /// something else.
  ///
  /// Never two for one variant, and never a variant the enum does not declare: both are refused at
  /// the declaration, which can check them because the member set and the contract are ONE derive
  /// input. That is the whole reason the rename lives HERE rather than on the member — a
  /// member-side word would have to cross a derive boundary, and only a type or a const does that,
  /// neither of which produces the IDENT a field access needs.
  ///
  /// Empty is not "no member calls it anything": [`InterfaceField::column`] is the one place the
  /// default is resolved, and the default is the interface's own field name.
  pub members: Vec<MemberColumn>,
}

/// ONE database's operand crossing for one field: the function its values enter storage through.
#[derive(Debug, Clone)]
pub struct Operand {
  /// Which database's predicate.
  pub kind: DatabaseKind,
  /// The function, handed one operand and answering with the stored form or a refusal.
  pub convert: syn::Path,
}

/// What ONE member calls one field of the contract.
#[derive(Debug, Clone)]
pub struct MemberColumn {
  /// The member's VARIANT, exactly as the enum spells it.
  ///
  /// The variant rather than the payload type, because the variant is what the declaration wrote
  /// and what a refusal about it names. The hop from one to the other is a LOOKUP rather than a
  /// guess: both come out of the same derive input.
  pub variant: syn::Ident,
  /// The column this member carries the field under — in its own struct, and in its own row.
  pub column: syn::Ident,
}

/// Which TIER one field of the contract is in.
///
/// A vocabulary rather than a pair of flags, because the three are mutually exclusive by
/// construction — which is what makes "computed beside persist" a front-end refusal rather than a
/// state some later pass has to remember cannot happen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Tier {
  /// A stored column: every member's row carries it, and the interface pins its type per database.
  Stored,
  /// `graphql(computed)`: every member DERIVES the value, and cannot fail doing it.
  Computed,
  /// `graphql(try_computed)`: every member derives it and may refuse.
  TryComputed,
}

impl Tier {
  /// Whether the field is DERIVED by the member rather than read out of its row.
  #[must_use]
  pub const fn computed(self) -> bool {
    matches!(self, Self::Computed | Self::TryComputed)
  }

  /// Whether deriving it may refuse — the one bit that decides a `Result` in the contract.
  #[must_use]
  pub const fn fallible(self) -> bool {
    matches!(self, Self::TryComputed)
  }
}

/// ONE database's pin for one stored field: the type that database keeps it at.
#[derive(Debug, Clone)]
pub struct Pin {
  /// Which database.
  pub kind: DatabaseKind,
  /// `type = "…"` — the stored type, when it is not the domain one.
  pub stored: Option<syn::Type>,
}

impl InterfaceField {
  /// The type ONE database's row carries this field at: the pin, or the domain type.
  ///
  /// Through [`stored_type`], which is the mapping a record's own row already takes, so an
  /// interface pinning nothing and a record declaring nothing agree by construction rather than by
  /// two functions happening to say the same thing.
  ///
  /// **A COLLECTION's unpinned answer is its own type and not its element's**, which is why every
  /// reader that wants a stored VALUE goes through [`InterfaceModel::stored_at`] instead: a pin
  /// names what a database keeps ONE element at, and the domain type is the list of them.
  #[must_use]
  pub fn pinned(&self, kind: DatabaseKind) -> &syn::Type {
    stored_type(
      self
        .pins
        .iter()
        .find(|pin| pin.kind == kind)
        .and_then(|pin| pin.stored.as_ref()),
      &self.ty,
    )
  }

  /// Whether this database's pin was WRITTEN, which is the one thing [`Self::pinned`] cannot say
  /// about its own answer.
  #[must_use]
  fn declares(&self, kind: DatabaseKind) -> bool {
    self
      .pins
      .iter()
      .any(|pin| pin.kind == kind && pin.stored.is_some())
  }

  /// Whether the pin's word named a COLLECTION — the one question the word answers for every reader
  /// here, asked in one place so the two readings of a pin cannot disagree about which fields are
  /// many-valued.
  ///
  /// A marker the DECLARING crate owns (`label = "a::Path"`) answers NO, which is the limit
  /// [`Marker::resolved`](crate::model::Marker) already has and the same one the record's own
  /// `collects` has: what the framework did not name, it cannot classify.
  #[must_use]
  pub fn collects(&self) -> bool {
    self.collection().is_some()
  }

  /// WHICH collection word the pin declared — the shape its members' edge tables have, and the one
  /// fact the consistency equation is written about.
  #[must_use]
  pub fn collection(&self) -> Option<Label> {
    match &self.marker {
      Some(Marker::Framework(marker)) if marker.label.collection() => Some(marker.label),
      _ => None,
    }
  }

  /// The function ONE database's predicate carries this field's operands across through, where the
  /// declaration named one.
  #[must_use]
  pub fn operand(&self, kind: DatabaseKind) -> Option<&syn::Path> {
    self
      .operands
      .iter()
      .find(|operand| operand.kind == kind)
      .map(|operand| &operand.convert)
  }

  /// What ONE member calls this field: the declared rename, or the interface's own name.
  ///
  /// The ONE place the default is resolved, and THREE consumers read it — the member's own contract
  /// impl, which accesses that struct field; the row equation, which accesses the same name on that
  /// member's row; and the arrangement layer, which will render `<column> AS <field>` once there is
  /// a query to render it into. A default spelled at three sites is how two of them come to
  /// disagree about a column nobody renamed.
  /// Matched UNRAW'D, which is the rule the front end's own block-key check runs on: `r#` is Rust's
  /// escape for a word that collides with its grammar and no part of the name, so a variant is one
  /// name however it had to be spelled.
  #[must_use]
  pub fn column(&self, variant: &syn::Ident) -> &syn::Ident {
    use syn::ext::IdentExt as _;

    self
      .members
      .iter()
      .find(|member| member.variant.unraw() == variant.unraw())
      .map_or(&self.name, |member| &member.column)
  }
}

impl InterfaceModel {
  /// The refusal type a wrong-variant unwrap answers with — the declared name, else
  /// `<Interface>UnwrapError`.
  #[must_use]
  pub fn error(&self) -> syn::Ident {
    self
      .error
      .clone()
      .unwrap_or_else(|| default_unwrap_error_name(&self.name))
  }

  /// What the CONTRACT trait is called.
  #[must_use]
  pub fn fields_name(&self) -> syn::Ident {
    default_fields_name(&self.name)
  }

  /// What the DERIVATIONS trait is called.
  #[must_use]
  pub fn derivations_name(&self) -> syn::Ident {
    default_derivations_name(&self.name)
  }

  /// What HYDRATING a page of this interface in `kind` refuses with: the declared cell, or the boxed
  /// refusal.
  ///
  /// The boxed default is what makes the three sources unify without a declaration saying anything:
  /// `core`'s own blanket absorbs any `Error + Send + Sync` into it, and the driver's refusal, the
  /// members' crossings and the coherence check are each one.
  #[must_use]
  pub fn hydration_error(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    match self.errors.iter().find(|cell| cell.kind == kind) {
      Some(cell) => {
        let path = &cell.error;
        quote::quote!(#path)
      }
      None => boxed_error(),
    }
  }

  /// What CROSSING a wire filter into this database's predicate refuses with: the declared cell, or
  /// the boxed refusal.
  ///
  /// The boxed default absorbs every column's crossing without a declaration saying anything, for
  /// [`InterfaceModel::hydration_error`]'s reason: `core`'s own blanket takes any
  /// `Error + Send + Sync` into it, and a column's crossing refusal is one.
  #[must_use]
  pub fn operand_error(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    match self.operand_errors.iter().find(|cell| cell.kind == kind) {
      Some(cell) => {
        let path = &cell.error;
        quote::quote!(#path)
      }
      None => boxed_error(),
    }
  }

  /// The type a fallible computed field answers with: the declared one, or the boxed refusal.
  #[must_use]
  pub fn computed_error(&self) -> proc_macro2::TokenStream {
    match &self.computed_error {
      Some(path) => quote::quote!(#path),
      None => boxed_error(),
    }
  }

  /// The fields the members' ROWS carry — the whole of what the CONTRACT trait is over.
  pub fn stored(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
    self
      .fields
      .iter()
      .filter(|field| field.tier == Tier::Stored)
  }

  /// The fields a member DERIVES — the whole of what the DERIVATIONS trait is over.
  pub fn computed(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
    self.fields.iter().filter(|field| field.tier.computed())
  }

  /// The stored fields a UNION ARM can select and the projection row can hold —
  /// [`Self::stored`] less the collections.
  ///
  /// # A collection is stored, promised and equated, and it is not a column of the union's output
  ///
  /// An arm renders `SELECT "<the member's name>" AS "<the interface's>"`, so every column here is
  /// one column of one member's table. A collection is not one on any backend this framework ships:
  /// SQLite and MySQL keep every collection in an edge table, PostgreSQL keeps it in a table of its
  /// own for the elements its arrays cannot hold, and the choice is the MEMBER's — so an arm that
  /// selected the name would ask a table for a column it may not have, and two arms could disagree
  /// about whether it is there at all.
  ///
  /// **The list is not lost, it arrives one moment later.** A page of an interface is two statements
  /// — the union, and one gather per member keyed on the addresses it returned — and the gather
  /// fetches the member's WHOLE row through the framework's own `rows`, which materializes every
  /// collection the row declares. So the client receives the list from the member's own hydration,
  /// which is where a record's own page receives it too.
  ///
  /// So the two lists are two vocabularies rather than one narrowed twice, exactly as
  /// `RecordModel::ordered_columns` and `DatabaseBackend::paged_columns` are: the CONTRACT promises every stored
  /// field, and the PROJECTION carries the ones a union statement can hand back.
  pub fn projected(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
    self.stored().filter(|field| !field.collects())
  }

  /// The stored fields that are COLLECTIONS — [`Self::stored`] less [`Self::projected`], and the
  /// complement is exact.
  ///
  /// What reads it is the per-ARM half of a predicate: a collection has no column in the union's
  /// output to compare, so its conjuncts are rendered against each member's own edge table rather
  /// than once above the union. See `SqlInterface::collections`.
  pub fn collected(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
    self.stored().filter(|field| field.collects())
  }

  /// The type ONE database keeps one VALUE of this field at — the type a comparison over it is
  /// keyed on, and the type a row's field holds one of.
  ///
  /// # A pin names ONE element, and a collection is where that stops being the same sentence
  ///
  /// `type = "Vec<u64>", persist(sqlite(type = "i64"))` says the domain holds a list of `u64` and
  /// SQLite keeps each of them as an `i64`. So a WRITTEN pin is already the value's type at either
  /// kind of field, and an unwritten one is not: the domain type of a scalar IS its value, and the
  /// domain type of a collection is the list.
  ///
  /// So an unpinned collection is asked for its ELEMENT, through the same projection the marker
  /// layer resolves a collection's element with — `State<Extracted<Inner>>`, the projection layer's
  /// answer to *what does this collection hold*. Asking the TYPE rather than reading the tokens is
  /// what keeps `type Marks = Vec<u64>` as transparent one level in as it is at the field, which is
  /// the rule this emitter keeps everywhere.
  #[must_use]
  pub fn stored_at(&self, field: &InterfaceField, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let held = field.pinned(kind);
    if !field.collects() || field.declares(kind) {
      return quote::quote!(#held);
    }
    let state = self.framework(&["state"], "State");
    let extracted = self.framework(&["state"], "Extracted");
    let inner = self.framework(&["state"], "Inner");
    quote::quote!(<#held as #state<#extracted<#inner>>>::Output)
  }

  /// What ONE member's ROW field holds for this field: the `Vec` of the stored value where the pin's
  /// word named a collection, and the stored value itself everywhere else.
  ///
  /// The other half of [`Self::stored_at`]'s split, written beside it so the two readings of one pin
  /// are one function apart — see [`equations`](self::equations), which is their only consumer and
  /// the site the split exists for.
  #[must_use]
  pub fn row_at(&self, field: &InterfaceField, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let held = self.stored_at(field, kind);
    if field.collects() {
      return quote::quote!(::std::vec::Vec<#held>);
    }
    held
  }

  /// The databases this interface's row equations are checked at.
  ///
  /// The interface's own `persist(…)` selection JOINED with every database a field pinned a type
  /// at, in [`DatabaseKind::ALL`]'s order so an expansion is stable and diffable. Joined rather than
  /// taken from one of the two, because both are the declaration saying which databases it is about
  /// and neither is a refinement of the other: a field pinning `sqlite(type = "u32")` has said
  /// SQLite as plainly as the block naming it, and an interface whose fields are all short-form has
  /// only the block to say it with.
  #[must_use]
  pub fn databases(&self) -> Vec<DatabaseKind> {
    DatabaseKind::ALL
      .into_iter()
      .filter(|kind| {
        self.persist.iter().any(|database| database.kind == *kind)
          || self
            .fields
            .iter()
            .any(|field| field.pins.iter().any(|pin| pin.kind == *kind))
      })
      .collect()
  }

  /// The namespace one database's SYNTHETIC WORDS are minted in — its own, or the framework's.
  ///
  /// A database reached only through a field's `type` pin took no `alias(…)` and gets the default,
  /// which is the same answer the block-less case gives: the block is where an override is written,
  /// and a pin says which database a type is checked at and nothing more.
  fn alias_prefix(&self, kind: DatabaseKind) -> &str {
    self
      .persist
      .iter()
      .find(|database| database.kind == kind)
      .map_or(self.prefix.mark(), |database| {
        database.aliases.prefix_in(&self.prefix)
      })
  }

  /// `<prefix>_kind__` — the column every arm of this database's union projects its DISCRIMINANT
  /// under, and the Rust field the projection row holds it in.
  ///
  /// One name for both faces, which is the discipline the default already keeps: what a decode reads
  /// by string and what the struct holds are the same slot, and spelling them differently would be
  /// the one place a reader had to hold a mapping.
  #[must_use]
  pub fn kind_word(&self, kind: DatabaseKind) -> String {
    format!("{}_kind__", self.alias_prefix(kind))
  }

  /// `<prefix>_union__` — the name the outer query gives the derived table it selects the union
  /// from.
  #[must_use]
  pub fn source_word(&self, kind: DatabaseKind) -> String {
    format!("{}_union__", self.alias_prefix(kind))
  }

  /// Whether this database's words are the ones the ENGINE already defaults to, which is what lets
  /// an emission STATE NOTHING where nothing moved.
  ///
  /// The engine defaults both items, so a declaration that named no prefix expands exactly as it did
  /// before the knob existed — the posture `COLLECTIONS` already takes one trait over.
  ///
  /// # The comparison is against `ingraph`'s constant, NOT against this model's namespace
  ///
  /// `ingraph::interface::KIND` is `__ig_kind__` whoever built the model, because the runtime holds
  /// one default and it is the framework's own. So a declaration a DOMAIN FRAMEWORK expanded is
  /// never silent here: its words moved relative to what the engine believes, and the emission has
  /// to say so. Asking [`EmissionPrefix::is_default`](crate::prefix::EmissionPrefix::is_default)
  /// instead would let a `__mg` model state nothing and then decode `__mg_kind__` out of a column
  /// its own arm had projected as `__ig_kind__` — a failure at run time, where this is none.
  #[must_use]
  pub fn mints_the_default_words(&self, kind: DatabaseKind) -> bool {
    self.alias_prefix(kind) == crate::alias::ALIAS_PREFIX
  }

  /// Every TYPE this model's emission declares into the DECLARING SCOPE, in EMISSION ORDER.
  ///
  /// The front end refuses a declaration whose emitted names collide, and it asks HERE which those
  /// are rather than keeping a list of its own — the argument
  /// [`RecordModel::emitted_types`](crate::model::RecordModel::emitted_types) already carries. Each
  /// name arrives with what it IS, through the same [`Role`] vocabulary the record's emission
  /// speaks, so a collision refusal reads the same whichever derive wrote the type.
  #[must_use]
  pub fn emitted_types(&self) -> Vec<Declared> {
    let declared = |name: syn::Ident, role: Role| Declared { name, role };
    let mut emitted = vec![
      declared(self.error(), Role::UnwrapError),
      declared(self.fields_name(), Role::Fields),
      declared(self.derivations_name(), Role::Derivations),
    ];
    // The PROJECTION's types, in the emitter's own walk: the discriminant once, the two addresses
    // over it, then one row per SQL database — and nothing at all where there is no projection to
    // write, which is [`InterfaceModel::projects`]'s condition asked rather than restated.
    if self.projects() {
      emitted.push(declared(default_kind_name(&self.name), Role::Kind));
      emitted.push(declared(default_id_name(&self.name), Role::Id));
      emitted.push(declared(default_key_name(&self.name), Role::Key));
      emitted.extend(
        self
          .sql_databases()
          .into_iter()
          .map(|kind| declared(default_row_name(&self.name, kind), Role::Row(kind))),
      );
      // The PAGE's types, after every row, because that is the order [`InterfaceModel::emit`] places
      // them in: the projection is what a statement hands back, and the cursor and the predicate are
      // what a page over it is resumed and narrowed by.
      emitted.extend(self.sql_databases().into_iter().flat_map(|kind| {
        [
          declared(self.cursor_name(kind), Role::Cursor(kind)),
          declared(self.comparison_name(kind), Role::Comparison(kind)),
        ]
      }));
      emitted.push(declared(default_order_by_name(&self.name), Role::OrderBy));
      // The WIRE query surface, after the two types it is written over: a filter is the predicate a
      // client sends and the arguments are the whole call, so the argument object names the filter
      // and the order-by and neither names it.
      emitted.push(declared(default_filter_name(&self.name), Role::Filter));
      emitted.push(declared(default_input_name(&self.name), Role::Input));
    }
    // The wire OUTPUT is unconditional, where every name above it rides the projection: an
    // interface's members all have wire faces — I-1 refuses one that has not — so the sum over them
    // is writable whatever a declaration stores.
    emitted.push(declared(default_output_name(&self.name), Role::Output));
    // The QUERY UNIT, last because that is the emitter's own walk — and only where one is written:
    // an interface with no page to answer binds `()` and declares no type, so naming it here would
    // refuse a declaration for a clash that could not happen. The record's own list draws the same
    // line at the same member.
    if self.wire_query_database().is_some() {
      emitted.push(declared(
        crate::model::default_queries_name(&self.name),
        Role::Queries,
      ));
    }
    emitted
  }

  /// The whole expansion: the member face, the contract, the pins discharged at the rows, and the
  /// interface's own projection.
  ///
  /// The projection comes LAST because it reads what the equations proved: a row carrying one field
  /// per shared column at the pinned type is honest exactly while every member's own row carries
  /// that column at that type, and the equations are what say so. rustc reports in emission order,
  /// so a member storing the column at something else is told THAT rather than being told about a
  /// decode.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let face = self.union_face();
    let contract = self.contract();
    let equations = self.equations();
    let projection = self.projection();
    let page = self.page();
    let ordering = self.ordering();
    let wire = self.wire();
    let output = self.output();
    let sdl_face = self.sdl_face();
    let queries = self.queries();
    let bindings = self.bindings();
    quote::quote! {
      #face
      #contract
      #equations
      #projection
      #page
      #ordering
      #wire
      #output
      #sdl_face
      #queries
      #bindings
    }
  }

  /// One framework name, rooted at whatever [`InterfaceModel::krate`] says the crate is.
  ///
  /// Every framework path an expansion writes goes through the shelf —
  /// `#krate::__private::<module>::<item>` with no exception — so emitted code depends on the shelf
  /// rather than on where an item actually lives. [`RecordModel::framework`](crate::emit) is the
  /// same function for the other model, and the two agree because the shelf's promise is one.
  pub(crate) fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let module = module.iter().map(|segment| format_ident!("{segment}"));
    let name = format_ident!("{name}");
    quote::quote!(#krate::__private #(:: #module)* :: #name)
  }
}

/// What an interface's CONTRACT trait is called: `<Interface>Fields`.
///
/// The projections every member answers — one method per declared field, whatever tier it is in.
/// Named for what it is about rather than for what it does, as the declaration's own `fields(…)`
/// block is.
#[must_use]
pub fn default_fields_name(interface: &syn::Ident) -> syn::Ident {
  format_ident!("{interface}Fields")
}

/// What an interface's DERIVATIONS trait is called: `<Interface>Derivations`.
///
/// The COMPUTED subset, and the one trait a member writes by hand: the contract's stored half is
/// emitted from the member's own columns, and its computed half delegates here.
#[must_use]
pub fn default_derivations_name(interface: &syn::Ident) -> syn::Ident {
  format_ident!("{interface}Derivations")
}

/// What an interface's DISCRIMINANT is called: `<Interface>Kind`.
///
/// A stored interface addresses a member by `(kind, id)` — the shape the several-upstreams ruling
/// already settled for a derived index's lineage — and the vocabulary naming which member a row came
/// from is that pair's first half.
#[must_use]
pub fn default_kind_name(interface: &syn::Ident) -> syn::Ident {
  format_ident!("{interface}Kind")
}

/// What an interface's ADDRESS is called: `<Interface>Id`.
///
/// A SUM over the members' own ids — one variant per member, carrying
/// `<M as Identifiable>::Id` — because an interface addresses a member row by `(kind, id)` and the
/// members need not agree about what an id IS. Heterogeneous member id types are legal by design:
/// a `Video` keyed by an integer and an `Audio` keyed by text are one interface, and the enum is
/// what lets one projection carry either.
///
/// The RECORD's own `<R>Id` convention does not exist to clash with — a record's id is a bare
/// column type and gets no emitted name — so the suffix is free.
#[must_use]
pub fn default_id_name(interface: &syn::Ident) -> syn::Ident {
  format_ident!("{interface}Id")
}

/// What an interface's ROW is called in one database: `<Interface><Db>Row`.
///
/// NOT [`default_row_name`](crate::model::default_row_name)'s convention: a record's row is
/// `<Record><Suffix>` because it IS that record in that database, where an interface's is the shared
/// projection its members' rows are read INTO — so the noun is part of the name.
#[must_use]
pub fn default_row_name(interface: &syn::Ident, kind: DatabaseKind) -> syn::Ident {
  format_ident!("{interface}{}Row", kind.suffix())
}

/// What an interface's KEY is called: `<Interface>Key`.
///
/// The RECORD's convention exactly — reached through
/// [`model::default_key_name`](crate::model::default_key_name) rather than respelled, because a name
/// written twice is a name that can come to be written differently — over the same thing one
/// declaration up: a SUM over `<M as Transformer>::Key`, because a key is the member's own and an
/// interface joining members joins whatever keys they have.
///
/// The LAST name to leave this module's reserved list, and the only one that left by ruling rather
/// than by a consumer — see the module note.
#[must_use]
pub fn default_key_name(interface: &syn::Ident) -> syn::Ident {
  crate::model::default_key_name(interface)
}

/// What an interface's FILTER is called: `<Interface>Filter`.
///
/// The RECORD's convention, reached through [`model::default_filter_name`](crate::model::default_filter_name)
/// rather than respelled — see [`default_key_name`] — and the type it names is the record's own
/// filter one declaration over: a predicate a client sends, over the columns every member carries.
#[must_use]
pub fn default_filter_name(interface: &syn::Ident) -> syn::Ident {
  crate::model::default_filter_name(interface)
}

/// What an interface's ORDER is called: `<Interface>OrderBy`. The RECORD's convention — see
/// [`default_key_name`].
#[must_use]
pub fn default_order_by_name(interface: &syn::Ident) -> syn::Ident {
  crate::model::default_order_by_name(interface)
}

/// What an interface's wire ARGUMENT object is called: `<Interface>GraphqlInput`.
///
/// The RECORD's convention — see [`default_key_name`] — over the lane an interface actually has:
/// filter ▸ order ▸ first/last/after/before, and no ceiling and no skip, because
/// `InterfaceFind` offers neither.
#[must_use]
pub fn default_input_name(interface: &syn::Ident) -> syn::Ident {
  crate::model::default_input_name(interface)
}

/// What an interface's wire OUTPUT object is called: `<Interface>GraphqlOutput`. The RECORD's
/// convention — see [`default_key_name`].
#[must_use]
pub fn default_output_name(interface: &syn::Ident) -> syn::Ident {
  crate::model::default_output_name(interface)
}