Skip to main content

ingraph_codegen/
interface.rs

1//! The INTERFACE face: a member set with a CONTRACT over it.
2//!
3//! An interface is a union plus a promise. The union half is the same payload-carrying enum
4//! [`crate::union`] equips — one variant per member, each carrying that member — and the promise is
5//! the `fields(…)` list: every member has these fields, at these types, and the ones the
6//! declaration marks COMPUTED are derived rather than stored.
7//!
8//! # It is a PSEUDO-RECORD, and today it declares only the promise
9//!
10//! An interface names no table and mints no id. What it has instead is the set of its members'
11//! rows, which is why its query layer is a fan-out rather than a select — and that layer is not
12//! this round's. What lands here is the DECLARATION and the TEETH: the contract as a Rust trait,
13//! the per-member implementations of it, and one type equation per (stored field, database, member)
14//! saying the member's row really carries the column at the type the interface pinned.
15//!
16//! # The three TIERS a field can be in, and the two FACES they land on
17//!
18//! | tier | written | every member | whose face carries it |
19//! |---|---|---|---|
20//! | stored | nothing, or `persist(<db>(type = "…"))` | carries the column | `<I>Fields`, on the MEMBER |
21//! | computed | `graphql(computed)` | DERIVES the value | `<I>Derivations`, on the member's wire OUTPUT |
22//! | try_computed | `graphql(try_computed)` | derives it, fallibly | the same, returning a `Result` |
23//!
24//! Stored and computed are MUTUALLY EXCLUSIVE, in both directions: a value a member derives is not
25//! a column its row holds, and a column its row holds is not a value it derives. The front end
26//! refuses either spelling of the pair rather than electing one.
27//!
28//! **The domain contract is STORED-ONLY**, and the split is the ruling rather than a staging. A
29//! computed field is a QUERY-LAYER construct — it is derived to be answered, and what answers a
30//! query is the wire output — so putting it on the domain trait would have made every member's
31//! domain type owe a method its rows have no column for and its pipeline never asks. `<I>Fields`
32//! therefore carries the stored tier and nothing else, and the computed tier is
33//! `<I>Derivations`, whose implementors are the members' GraphQL OUTPUT types.
34//!
35//! `<I>Derivations` is DECLARED here and implemented nowhere: the emission writes the trait, and a
36//! member's output type writes the impl by hand. There is no escape machinery under it for the same
37//! reason — a hand author writes their own glue, and a generated adapter would be a seam nobody
38//! asked for. The interface's own output face is what consumes it, and that face is the find half's.
39//!
40//! # A member may call a stored field something else, and the INTERFACE is where it says so
41//!
42//! `created_at(type = "Timestamp", members(Audio(field = "imported_at")))`: the member `Audio` carries this
43//! field as `imported_at`, in its own struct and in its own row.
44//!
45//! HERE rather than on the member, and the reason is what a macro can see. A member-side word would
46//! have to reach an interface's expansion across a derive boundary, and the only things that cross
47//! one are a type and a const — neither of which produces the IDENT a field access needs. Written
48//! on the interface, every hop of the chain is backed by the SAME derive input: the block's key is
49//! checked token-for-token against the enum's own variants, the variant names the payload type it
50//! carries, that type projects to `<M as Record<Db>>::Row`, and the declared ident is what the
51//! access spells.
52//!
53//! It extends the axis one step, and the step is INTERFACE-SPECIFIC: interface field block ▸
54//! `members(…)` ▸ one block per variant ▸ entries. A record grows no member axis, having no members
55//! — so this is the one grammar in the framework where a block's key is a variant rather than a
56//! database or a domain, and the container is what says where that holds. POSITION decides: outside
57//! it every key is a word the grammar owns, inside it every key is a variant.
58//!
59//! # The names this expansion puts in the declaring scope
60//!
61//! [`InterfaceModel::emitted_types`] is the list, and each name arrives with what it IS: the sealed
62//! refusal the union half writes, the CONTRACT trait, the DERIVATIONS trait a member writes its
63//! computed half through, the DISCRIMINANT, the two ADDRESSES over it — the id sum a row carries
64//! and the key sum a hit will — one PROJECTION ROW per SQL database the declaration is about, the
65//! page's cursor and predicate, the order-by, and the two the wire query surface is: the FILTER a
66//! client sends and the ARGUMENT object that carries it.
67//!
68//! The RESERVED list is empty, and this is where it ended. Every name on it had a function here and
69//! no emission — the point being that a name decided when its emission lands is a name decided
70//! twice — and each has since been taken by the emission that reserved it. The KEY was the last,
71//! and it is the one that left by RULING rather than by a consumer: it is the fusion seam's premise,
72//! so it is minted before that seam rather than with it.
73//!
74//! # `crate = "…"` exists here where the union has none
75//!
76//! A union's whole expansion is `core`, so there is nothing for the option to move. An interface's
77//! is not: the membership evidence, the storability the equations read a row through, and the
78//! backend gates they ride are all framework names, so the declaration states its root once and
79//! every emitted path follows it.
80
81use quote::format_ident;
82
83use crate::{
84  model::{AliasOptions, DatabaseKind, Declared, Label, Marker, Role, boxed_error, stored_type},
85  prefix::EmissionPrefix,
86  union::{UnionMember, default_unwrap_error_name},
87};
88
89mod binding;
90mod contract;
91mod cross;
92mod equations;
93mod face;
94mod hydrate;
95mod order;
96mod page;
97mod queries;
98mod row;
99mod union_face;
100mod wire;
101
102#[cfg(test)]
103mod tests;
104
105/// One interface's declaration, validated.
106///
107/// Public fields for the reason [`RecordModel`](crate::model::RecordModel)'s are: nothing here
108/// parses, so a front end that is not the derive builds the same struct and reaches the same
109/// emitter.
110#[derive(Debug, Clone)]
111pub struct InterfaceModel {
112  /// The EMISSION NAMESPACE this declaration's minted names wear.
113  ///
114  /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
115  /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
116  /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
117  pub prefix: EmissionPrefix,
118  /// The declaration's visibility, which every emitted item takes.
119  pub vis: syn::Visibility,
120  /// The declared enum's own name.
121  pub name: syn::Ident,
122  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
123  /// another.
124  pub krate: syn::Path,
125  /// Its members, in declaration order. Never empty, and never two of one type.
126  ///
127  /// The UNION's own member type, because a member is the same thing in both declarations: the
128  /// variant that names it and the type it carries. Sharing it is what lets one seam equip both.
129  pub members: Vec<UnionMember>,
130  /// The fields every member promises, in declaration order.
131  pub fields: Vec<InterfaceField>,
132  /// What the emitted REFUSAL type is called, when the declaration named it.
133  ///
134  /// `None` is `<Interface>UnwrapError`, which is what [`InterfaceModel::error`] resolves.
135  pub error: Option<syn::Ident>,
136  /// `graphql(computed(error = "…"))` — the type every FALLIBLE computed field answers with.
137  ///
138  /// ONE cell and DB-LESS, which is the ruled exception to this grammar's database blocks: a
139  /// computed value is derived from the member rather than read out of a row, so the crossing names
140  /// no database and there is nothing for a per-database cell to differ about. `None` is the boxed
141  /// refusal — see [`InterfaceModel::computed_error`].
142  pub computed_error: Option<syn::Path>,
143  /// The databases the interface's own `persist(…)` block named, in the order they were written.
144  ///
145  /// A SELECTION rather than a storage declaration: an interface owns no table, so what this does
146  /// is say which databases the row equations are checked at. A field's own per-database pin names
147  /// one too, and [`InterfaceModel::databases`] is where the two are joined.
148  pub persist: Vec<InterfaceDatabase>,
149  /// `persist(<db>(try_into(error = "…")))` — what HYDRATING a page of this interface refuses with,
150  /// per database. Never two for one database.
151  ///
152  /// The `try_into` LEG, and it is the read direction the verb rule names: a page's rows leave
153  /// storage for the members' own wire outputs, and every refusal on that path — the driver's, the
154  /// members' own crossings, and the coherence check between the union and the gather — unifies
155  /// here. `None` for a database is the boxed refusal, which absorbs all three through `core`'s own
156  /// blanket.
157  ///
158  /// The other three legs stay REFUSED at the front end: `from`, `try_from` and `into` type
159  /// crossings an interface performs nowhere, and an entry nobody reads is a rule its author
160  /// believes they declared.
161  pub errors: Vec<InterfaceError>,
162  /// `graphql(input(comparison(<db>(try_into(error = "…")))))` — what CROSSING a wire filter into
163  /// this database's predicate refuses with, per database. Never two for one database.
164  ///
165  /// The `try_into` leg again, and the direction is the same one the verb rule names one axis over:
166  /// a filter's operands LEAVE the wire for the types this database stores, so every refusal on
167  /// that path — each column's own crossing, and each declared operand converter's — unifies here.
168  /// `None` for a database is the boxed refusal.
169  ///
170  /// Separate from [`InterfaceModel::errors`] because they type two crossings that run at different
171  /// moments: one is a page's rows leaving storage, the other is a predicate's operands entering
172  /// it. A single cell for both would make a caller catch one to learn about the other.
173  pub operand_errors: Vec<InterfaceError>,
174  /// `graphql(plural = "…")` — this interface's plural as a WORD, where the pluraliser's answer is
175  /// wrong.
176  ///
177  /// The NAMING TOWER's middle tier, and the record's own knob one declaration over: it moves the
178  /// list FIELD and both page type names together, which is the whole of what the tier buys — one
179  /// correction of English rather than three readers of it.
180  ///
181  /// `None` is the derived plural, and a derived plural EQUAL to the singular is legal here where a
182  /// record refuses it. See [`InterfaceModel::published_plural`].
183  pub plural: Option<String>,
184  /// `graphql(connection(rename = "…"))` — what the schema calls a page of this interface.
185  ///
186  /// The tower's TOP, covering the plural-built word outright and independently of the edge's.
187  pub connection: Option<String>,
188  /// `graphql(edge(rename = "…"))` — what the schema calls one edge of that page.
189  pub edge: Option<String>,
190}
191
192/// ONE database inside the interface's own `persist(…)`: which, and what its synthetic words are
193/// named in.
194#[derive(Debug, Clone)]
195pub struct InterfaceDatabase {
196  /// Which database.
197  pub kind: DatabaseKind,
198  /// `alias(prefix = "…")` — the namespace this database's SYNTHETIC WORDS are minted in.
199  ///
200  /// The same knob a record spends on its row-source names, and the same reason for being per
201  /// database: one deployment's schema holds legacy tables inside the default namespace and the
202  /// others do not. What it moves here is everything the union statement INVENTS — the discriminant
203  /// the arms project and the name the outer query gives the derived table.
204  ///
205  /// [`AliasOptions::depth`] is never filled: an interface owns no table, so it mints no alias array
206  /// for a depth to be the length of, and the word is refused where the block is read.
207  pub aliases: AliasOptions,
208}
209
210/// ONE database's refusal cell for the crossing an interface's hydration performs.
211#[derive(Debug, Clone)]
212pub struct InterfaceError {
213  /// Which database's hydration.
214  pub kind: DatabaseKind,
215  /// The type it answers with.
216  pub error: syn::Path,
217}
218
219/// One field of the contract: what every member has, and how.
220#[derive(Debug, Clone)]
221pub struct InterfaceField {
222  /// The field's name — the contract method's name, and the row column's.
223  pub name: syn::Ident,
224  /// The DOMAIN type, as the declaration spelled it.
225  pub ty: syn::Type,
226  /// Which tier the field is in.
227  pub tier: Tier,
228  /// The INTERPRETATION word the pin declared — `list(scalar)`, `string`, `label = "a::Path"` — or
229  /// `None` where the type answers for itself.
230  ///
231  /// # A pin's word is the record's own, and the two readers it splits are what it is FOR
232  ///
233  /// A collection column has two stored readings and they are different types: the member's ROW
234  /// holds the LIST, and the comparison a filter crosses into is keyed on the ELEMENT the database
235  /// stores. Nothing about `type = "Vec<u64>"` and `persist(sqlite(type = "i64"))` says which of the
236  /// two the pin is — `type Ids = Vec<Uuid7>` and a scalar are the same tokens — so before the word
237  /// there was one reading, it was the wrong one at one of the sites, and a collection contract
238  /// field was `E0308` at the row equation.
239  ///
240  /// The record settles the same question the same way, which is what makes this precedent-consistent
241  /// rather than a second grammar: its collection interpretation IS word-declared
242  /// ([`Label`](crate::model::Label)), and this reads the very same vocabulary through the very same
243  /// front-end door.
244  ///
245  /// [`InterfaceField::collects`] is what every reader asks; the marker itself reaches
246  /// [`InterfaceModel::filter_of`], where it picks the filter KIND exactly as a record's does.
247  pub marker: Option<Marker>,
248  /// `copy`: the type is cheap enough to hand back by value.
249  ///
250  /// A CLAIM the emitter cannot check, exactly as [`Projection::Copied`](crate::model::Projection)
251  /// is: a model carries names and types, not trait implementations, so a field marked `copy` whose
252  /// type is not `Copy` produces a contract implementation that does not compile — at the member,
253  /// naming the field.
254  pub copy: bool,
255  /// What each database stores the field at, where the declaration pinned one. Never two for one
256  /// database.
257  ///
258  /// Empty is not "stored nowhere": a database with no pin stores the field at the DOMAIN type,
259  /// which is the uniform mapping [`stored_type`] carries for the record's rows as well.
260  pub pins: Vec<Pin>,
261  /// `graphql(type = "…")` — the WIRE FORM, when it is not the domain type.
262  ///
263  /// Held rather than spent, and what it is waiting for is the SDL. The filter object deliberately
264  /// does not read it: an operand's filter and the comparison's are ONE kind or the crossing between
265  /// them cannot be written, and a wire form that moved a `u64` onto a `String` would move the
266  /// operand's filter from the scalar kind to the text one. What a declared wire form is for is the
267  /// name a schema publishes, and no schema is rendered here — so the entry stays read-and-held
268  /// rather than spent on the one face it would make unwritable.
269  pub wire: Option<syn::Type>,
270  /// `graphql(input(comparison(<db>(try_into = "…"))))` — what carries this field's OPERAND across
271  /// into one database's stored form. Never two for one database.
272  ///
273  /// The declared leg REPLACES the whole chain for that database, which is the grammar's own law:
274  /// a field with no entry crosses through the stored type's own [`TryFrom`], and one with an entry
275  /// crosses through the named function and never asks the type. Empty is the former.
276  pub operands: Vec<Operand>,
277  /// `members(<Variant>(field = "…"))` — what ONE member calls this field, where it calls it
278  /// something else.
279  ///
280  /// Never two for one variant, and never a variant the enum does not declare: both are refused at
281  /// the declaration, which can check them because the member set and the contract are ONE derive
282  /// input. That is the whole reason the rename lives HERE rather than on the member — a
283  /// member-side word would have to cross a derive boundary, and only a type or a const does that,
284  /// neither of which produces the IDENT a field access needs.
285  ///
286  /// Empty is not "no member calls it anything": [`InterfaceField::column`] is the one place the
287  /// default is resolved, and the default is the interface's own field name.
288  pub members: Vec<MemberColumn>,
289}
290
291/// ONE database's operand crossing for one field: the function its values enter storage through.
292#[derive(Debug, Clone)]
293pub struct Operand {
294  /// Which database's predicate.
295  pub kind: DatabaseKind,
296  /// The function, handed one operand and answering with the stored form or a refusal.
297  pub convert: syn::Path,
298}
299
300/// What ONE member calls one field of the contract.
301#[derive(Debug, Clone)]
302pub struct MemberColumn {
303  /// The member's VARIANT, exactly as the enum spells it.
304  ///
305  /// The variant rather than the payload type, because the variant is what the declaration wrote
306  /// and what a refusal about it names. The hop from one to the other is a LOOKUP rather than a
307  /// guess: both come out of the same derive input.
308  pub variant: syn::Ident,
309  /// The column this member carries the field under — in its own struct, and in its own row.
310  pub column: syn::Ident,
311}
312
313/// Which TIER one field of the contract is in.
314///
315/// A vocabulary rather than a pair of flags, because the three are mutually exclusive by
316/// construction — which is what makes "computed beside persist" a front-end refusal rather than a
317/// state some later pass has to remember cannot happen.
318#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
319pub enum Tier {
320  /// A stored column: every member's row carries it, and the interface pins its type per database.
321  Stored,
322  /// `graphql(computed)`: every member DERIVES the value, and cannot fail doing it.
323  Computed,
324  /// `graphql(try_computed)`: every member derives it and may refuse.
325  TryComputed,
326}
327
328impl Tier {
329  /// Whether the field is DERIVED by the member rather than read out of its row.
330  #[must_use]
331  pub const fn computed(self) -> bool {
332    matches!(self, Self::Computed | Self::TryComputed)
333  }
334
335  /// Whether deriving it may refuse — the one bit that decides a `Result` in the contract.
336  #[must_use]
337  pub const fn fallible(self) -> bool {
338    matches!(self, Self::TryComputed)
339  }
340}
341
342/// ONE database's pin for one stored field: the type that database keeps it at.
343#[derive(Debug, Clone)]
344pub struct Pin {
345  /// Which database.
346  pub kind: DatabaseKind,
347  /// `type = "…"` — the stored type, when it is not the domain one.
348  pub stored: Option<syn::Type>,
349}
350
351impl InterfaceField {
352  /// The type ONE database's row carries this field at: the pin, or the domain type.
353  ///
354  /// Through [`stored_type`], which is the mapping a record's own row already takes, so an
355  /// interface pinning nothing and a record declaring nothing agree by construction rather than by
356  /// two functions happening to say the same thing.
357  ///
358  /// **A COLLECTION's unpinned answer is its own type and not its element's**, which is why every
359  /// reader that wants a stored VALUE goes through [`InterfaceModel::stored_at`] instead: a pin
360  /// names what a database keeps ONE element at, and the domain type is the list of them.
361  #[must_use]
362  pub fn pinned(&self, kind: DatabaseKind) -> &syn::Type {
363    stored_type(
364      self
365        .pins
366        .iter()
367        .find(|pin| pin.kind == kind)
368        .and_then(|pin| pin.stored.as_ref()),
369      &self.ty,
370    )
371  }
372
373  /// Whether this database's pin was WRITTEN, which is the one thing [`Self::pinned`] cannot say
374  /// about its own answer.
375  #[must_use]
376  fn declares(&self, kind: DatabaseKind) -> bool {
377    self
378      .pins
379      .iter()
380      .any(|pin| pin.kind == kind && pin.stored.is_some())
381  }
382
383  /// Whether the pin's word named a COLLECTION — the one question the word answers for every reader
384  /// here, asked in one place so the two readings of a pin cannot disagree about which fields are
385  /// many-valued.
386  ///
387  /// A marker the DECLARING crate owns (`label = "a::Path"`) answers NO, which is the limit
388  /// [`Marker::resolved`](crate::model::Marker) already has and the same one the record's own
389  /// `collects` has: what the framework did not name, it cannot classify.
390  #[must_use]
391  pub fn collects(&self) -> bool {
392    self.collection().is_some()
393  }
394
395  /// WHICH collection word the pin declared — the shape its members' edge tables have, and the one
396  /// fact the consistency equation is written about.
397  #[must_use]
398  pub fn collection(&self) -> Option<Label> {
399    match &self.marker {
400      Some(Marker::Framework(marker)) if marker.label.collection() => Some(marker.label),
401      _ => None,
402    }
403  }
404
405  /// The function ONE database's predicate carries this field's operands across through, where the
406  /// declaration named one.
407  #[must_use]
408  pub fn operand(&self, kind: DatabaseKind) -> Option<&syn::Path> {
409    self
410      .operands
411      .iter()
412      .find(|operand| operand.kind == kind)
413      .map(|operand| &operand.convert)
414  }
415
416  /// What ONE member calls this field: the declared rename, or the interface's own name.
417  ///
418  /// The ONE place the default is resolved, and THREE consumers read it — the member's own contract
419  /// impl, which accesses that struct field; the row equation, which accesses the same name on that
420  /// member's row; and the arrangement layer, which will render `<column> AS <field>` once there is
421  /// a query to render it into. A default spelled at three sites is how two of them come to
422  /// disagree about a column nobody renamed.
423  /// Matched UNRAW'D, which is the rule the front end's own block-key check runs on: `r#` is Rust's
424  /// escape for a word that collides with its grammar and no part of the name, so a variant is one
425  /// name however it had to be spelled.
426  #[must_use]
427  pub fn column(&self, variant: &syn::Ident) -> &syn::Ident {
428    use syn::ext::IdentExt as _;
429
430    self
431      .members
432      .iter()
433      .find(|member| member.variant.unraw() == variant.unraw())
434      .map_or(&self.name, |member| &member.column)
435  }
436}
437
438impl InterfaceModel {
439  /// The refusal type a wrong-variant unwrap answers with — the declared name, else
440  /// `<Interface>UnwrapError`.
441  #[must_use]
442  pub fn error(&self) -> syn::Ident {
443    self
444      .error
445      .clone()
446      .unwrap_or_else(|| default_unwrap_error_name(&self.name))
447  }
448
449  /// What the CONTRACT trait is called.
450  #[must_use]
451  pub fn fields_name(&self) -> syn::Ident {
452    default_fields_name(&self.name)
453  }
454
455  /// What the DERIVATIONS trait is called.
456  #[must_use]
457  pub fn derivations_name(&self) -> syn::Ident {
458    default_derivations_name(&self.name)
459  }
460
461  /// What HYDRATING a page of this interface in `kind` refuses with: the declared cell, or the boxed
462  /// refusal.
463  ///
464  /// The boxed default is what makes the three sources unify without a declaration saying anything:
465  /// `core`'s own blanket absorbs any `Error + Send + Sync` into it, and the driver's refusal, the
466  /// members' crossings and the coherence check are each one.
467  #[must_use]
468  pub fn hydration_error(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
469    match self.errors.iter().find(|cell| cell.kind == kind) {
470      Some(cell) => {
471        let path = &cell.error;
472        quote::quote!(#path)
473      }
474      None => boxed_error(),
475    }
476  }
477
478  /// What CROSSING a wire filter into this database's predicate refuses with: the declared cell, or
479  /// the boxed refusal.
480  ///
481  /// The boxed default absorbs every column's crossing without a declaration saying anything, for
482  /// [`InterfaceModel::hydration_error`]'s reason: `core`'s own blanket takes any
483  /// `Error + Send + Sync` into it, and a column's crossing refusal is one.
484  #[must_use]
485  pub fn operand_error(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
486    match self.operand_errors.iter().find(|cell| cell.kind == kind) {
487      Some(cell) => {
488        let path = &cell.error;
489        quote::quote!(#path)
490      }
491      None => boxed_error(),
492    }
493  }
494
495  /// The type a fallible computed field answers with: the declared one, or the boxed refusal.
496  #[must_use]
497  pub fn computed_error(&self) -> proc_macro2::TokenStream {
498    match &self.computed_error {
499      Some(path) => quote::quote!(#path),
500      None => boxed_error(),
501    }
502  }
503
504  /// The fields the members' ROWS carry — the whole of what the CONTRACT trait is over.
505  pub fn stored(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
506    self
507      .fields
508      .iter()
509      .filter(|field| field.tier == Tier::Stored)
510  }
511
512  /// The fields a member DERIVES — the whole of what the DERIVATIONS trait is over.
513  pub fn computed(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
514    self.fields.iter().filter(|field| field.tier.computed())
515  }
516
517  /// The stored fields a UNION ARM can select and the projection row can hold —
518  /// [`Self::stored`] less the collections.
519  ///
520  /// # A collection is stored, promised and equated, and it is not a column of the union's output
521  ///
522  /// An arm renders `SELECT "<the member's name>" AS "<the interface's>"`, so every column here is
523  /// one column of one member's table. A collection is not one on any backend this framework ships:
524  /// SQLite and MySQL keep every collection in an edge table, PostgreSQL keeps it in a table of its
525  /// own for the elements its arrays cannot hold, and the choice is the MEMBER's — so an arm that
526  /// selected the name would ask a table for a column it may not have, and two arms could disagree
527  /// about whether it is there at all.
528  ///
529  /// **The list is not lost, it arrives one moment later.** A page of an interface is two statements
530  /// — the union, and one gather per member keyed on the addresses it returned — and the gather
531  /// fetches the member's WHOLE row through the framework's own `rows`, which materializes every
532  /// collection the row declares. So the client receives the list from the member's own hydration,
533  /// which is where a record's own page receives it too.
534  ///
535  /// So the two lists are two vocabularies rather than one narrowed twice, exactly as
536  /// `RecordModel::ordered_columns` and `DatabaseBackend::paged_columns` are: the CONTRACT promises every stored
537  /// field, and the PROJECTION carries the ones a union statement can hand back.
538  pub fn projected(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
539    self.stored().filter(|field| !field.collects())
540  }
541
542  /// The stored fields that are COLLECTIONS — [`Self::stored`] less [`Self::projected`], and the
543  /// complement is exact.
544  ///
545  /// What reads it is the per-ARM half of a predicate: a collection has no column in the union's
546  /// output to compare, so its conjuncts are rendered against each member's own edge table rather
547  /// than once above the union. See `SqlInterface::collections`.
548  pub fn collected(&self) -> impl Iterator<Item = &InterfaceField> + Clone {
549    self.stored().filter(|field| field.collects())
550  }
551
552  /// The type ONE database keeps one VALUE of this field at — the type a comparison over it is
553  /// keyed on, and the type a row's field holds one of.
554  ///
555  /// # A pin names ONE element, and a collection is where that stops being the same sentence
556  ///
557  /// `type = "Vec<u64>", persist(sqlite(type = "i64"))` says the domain holds a list of `u64` and
558  /// SQLite keeps each of them as an `i64`. So a WRITTEN pin is already the value's type at either
559  /// kind of field, and an unwritten one is not: the domain type of a scalar IS its value, and the
560  /// domain type of a collection is the list.
561  ///
562  /// So an unpinned collection is asked for its ELEMENT, through the same projection the marker
563  /// layer resolves a collection's element with — `State<Extracted<Inner>>`, the projection layer's
564  /// answer to *what does this collection hold*. Asking the TYPE rather than reading the tokens is
565  /// what keeps `type Marks = Vec<u64>` as transparent one level in as it is at the field, which is
566  /// the rule this emitter keeps everywhere.
567  #[must_use]
568  pub fn stored_at(&self, field: &InterfaceField, kind: DatabaseKind) -> proc_macro2::TokenStream {
569    let held = field.pinned(kind);
570    if !field.collects() || field.declares(kind) {
571      return quote::quote!(#held);
572    }
573    let state = self.framework(&["state"], "State");
574    let extracted = self.framework(&["state"], "Extracted");
575    let inner = self.framework(&["state"], "Inner");
576    quote::quote!(<#held as #state<#extracted<#inner>>>::Output)
577  }
578
579  /// What ONE member's ROW field holds for this field: the `Vec` of the stored value where the pin's
580  /// word named a collection, and the stored value itself everywhere else.
581  ///
582  /// The other half of [`Self::stored_at`]'s split, written beside it so the two readings of one pin
583  /// are one function apart — see [`equations`](self::equations), which is their only consumer and
584  /// the site the split exists for.
585  #[must_use]
586  pub fn row_at(&self, field: &InterfaceField, kind: DatabaseKind) -> proc_macro2::TokenStream {
587    let held = self.stored_at(field, kind);
588    if field.collects() {
589      return quote::quote!(::std::vec::Vec<#held>);
590    }
591    held
592  }
593
594  /// The databases this interface's row equations are checked at.
595  ///
596  /// The interface's own `persist(…)` selection JOINED with every database a field pinned a type
597  /// at, in [`DatabaseKind::ALL`]'s order so an expansion is stable and diffable. Joined rather than
598  /// taken from one of the two, because both are the declaration saying which databases it is about
599  /// and neither is a refinement of the other: a field pinning `sqlite(type = "u32")` has said
600  /// SQLite as plainly as the block naming it, and an interface whose fields are all short-form has
601  /// only the block to say it with.
602  #[must_use]
603  pub fn databases(&self) -> Vec<DatabaseKind> {
604    DatabaseKind::ALL
605      .into_iter()
606      .filter(|kind| {
607        self.persist.iter().any(|database| database.kind == *kind)
608          || self
609            .fields
610            .iter()
611            .any(|field| field.pins.iter().any(|pin| pin.kind == *kind))
612      })
613      .collect()
614  }
615
616  /// The namespace one database's SYNTHETIC WORDS are minted in — its own, or the framework's.
617  ///
618  /// A database reached only through a field's `type` pin took no `alias(…)` and gets the default,
619  /// which is the same answer the block-less case gives: the block is where an override is written,
620  /// and a pin says which database a type is checked at and nothing more.
621  fn alias_prefix(&self, kind: DatabaseKind) -> &str {
622    self
623      .persist
624      .iter()
625      .find(|database| database.kind == kind)
626      .map_or(self.prefix.mark(), |database| {
627        database.aliases.prefix_in(&self.prefix)
628      })
629  }
630
631  /// `<prefix>_kind__` — the column every arm of this database's union projects its DISCRIMINANT
632  /// under, and the Rust field the projection row holds it in.
633  ///
634  /// One name for both faces, which is the discipline the default already keeps: what a decode reads
635  /// by string and what the struct holds are the same slot, and spelling them differently would be
636  /// the one place a reader had to hold a mapping.
637  #[must_use]
638  pub fn kind_word(&self, kind: DatabaseKind) -> String {
639    format!("{}_kind__", self.alias_prefix(kind))
640  }
641
642  /// `<prefix>_union__` — the name the outer query gives the derived table it selects the union
643  /// from.
644  #[must_use]
645  pub fn source_word(&self, kind: DatabaseKind) -> String {
646    format!("{}_union__", self.alias_prefix(kind))
647  }
648
649  /// Whether this database's words are the ones the ENGINE already defaults to, which is what lets
650  /// an emission STATE NOTHING where nothing moved.
651  ///
652  /// The engine defaults both items, so a declaration that named no prefix expands exactly as it did
653  /// before the knob existed — the posture `COLLECTIONS` already takes one trait over.
654  ///
655  /// # The comparison is against `ingraph`'s constant, NOT against this model's namespace
656  ///
657  /// `ingraph::interface::KIND` is `__ig_kind__` whoever built the model, because the runtime holds
658  /// one default and it is the framework's own. So a declaration a DOMAIN FRAMEWORK expanded is
659  /// never silent here: its words moved relative to what the engine believes, and the emission has
660  /// to say so. Asking [`EmissionPrefix::is_default`](crate::prefix::EmissionPrefix::is_default)
661  /// instead would let a `__mg` model state nothing and then decode `__mg_kind__` out of a column
662  /// its own arm had projected as `__ig_kind__` — a failure at run time, where this is none.
663  #[must_use]
664  pub fn mints_the_default_words(&self, kind: DatabaseKind) -> bool {
665    self.alias_prefix(kind) == crate::alias::ALIAS_PREFIX
666  }
667
668  /// Every TYPE this model's emission declares into the DECLARING SCOPE, in EMISSION ORDER.
669  ///
670  /// The front end refuses a declaration whose emitted names collide, and it asks HERE which those
671  /// are rather than keeping a list of its own — the argument
672  /// [`RecordModel::emitted_types`](crate::model::RecordModel::emitted_types) already carries. Each
673  /// name arrives with what it IS, through the same [`Role`] vocabulary the record's emission
674  /// speaks, so a collision refusal reads the same whichever derive wrote the type.
675  #[must_use]
676  pub fn emitted_types(&self) -> Vec<Declared> {
677    let declared = |name: syn::Ident, role: Role| Declared { name, role };
678    let mut emitted = vec![
679      declared(self.error(), Role::UnwrapError),
680      declared(self.fields_name(), Role::Fields),
681      declared(self.derivations_name(), Role::Derivations),
682    ];
683    // The PROJECTION's types, in the emitter's own walk: the discriminant once, the two addresses
684    // over it, then one row per SQL database — and nothing at all where there is no projection to
685    // write, which is [`InterfaceModel::projects`]'s condition asked rather than restated.
686    if self.projects() {
687      emitted.push(declared(default_kind_name(&self.name), Role::Kind));
688      emitted.push(declared(default_id_name(&self.name), Role::Id));
689      emitted.push(declared(default_key_name(&self.name), Role::Key));
690      emitted.extend(
691        self
692          .sql_databases()
693          .into_iter()
694          .map(|kind| declared(default_row_name(&self.name, kind), Role::Row(kind))),
695      );
696      // The PAGE's types, after every row, because that is the order [`InterfaceModel::emit`] places
697      // them in: the projection is what a statement hands back, and the cursor and the predicate are
698      // what a page over it is resumed and narrowed by.
699      emitted.extend(self.sql_databases().into_iter().flat_map(|kind| {
700        [
701          declared(self.cursor_name(kind), Role::Cursor(kind)),
702          declared(self.comparison_name(kind), Role::Comparison(kind)),
703        ]
704      }));
705      emitted.push(declared(default_order_by_name(&self.name), Role::OrderBy));
706      // The WIRE query surface, after the two types it is written over: a filter is the predicate a
707      // client sends and the arguments are the whole call, so the argument object names the filter
708      // and the order-by and neither names it.
709      emitted.push(declared(default_filter_name(&self.name), Role::Filter));
710      emitted.push(declared(default_input_name(&self.name), Role::Input));
711    }
712    // The wire OUTPUT is unconditional, where every name above it rides the projection: an
713    // interface's members all have wire faces — I-1 refuses one that has not — so the sum over them
714    // is writable whatever a declaration stores.
715    emitted.push(declared(default_output_name(&self.name), Role::Output));
716    // The QUERY UNIT, last because that is the emitter's own walk — and only where one is written:
717    // an interface with no page to answer binds `()` and declares no type, so naming it here would
718    // refuse a declaration for a clash that could not happen. The record's own list draws the same
719    // line at the same member.
720    if self.wire_query_database().is_some() {
721      emitted.push(declared(
722        crate::model::default_queries_name(&self.name),
723        Role::Queries,
724      ));
725    }
726    emitted
727  }
728
729  /// The whole expansion: the member face, the contract, the pins discharged at the rows, and the
730  /// interface's own projection.
731  ///
732  /// The projection comes LAST because it reads what the equations proved: a row carrying one field
733  /// per shared column at the pinned type is honest exactly while every member's own row carries
734  /// that column at that type, and the equations are what say so. rustc reports in emission order,
735  /// so a member storing the column at something else is told THAT rather than being told about a
736  /// decode.
737  #[must_use]
738  pub fn emit(&self) -> proc_macro2::TokenStream {
739    let face = self.union_face();
740    let contract = self.contract();
741    let equations = self.equations();
742    let projection = self.projection();
743    let page = self.page();
744    let ordering = self.ordering();
745    let wire = self.wire();
746    let output = self.output();
747    let sdl_face = self.sdl_face();
748    let queries = self.queries();
749    let bindings = self.bindings();
750    quote::quote! {
751      #face
752      #contract
753      #equations
754      #projection
755      #page
756      #ordering
757      #wire
758      #output
759      #sdl_face
760      #queries
761      #bindings
762    }
763  }
764
765  /// One framework name, rooted at whatever [`InterfaceModel::krate`] says the crate is.
766  ///
767  /// Every framework path an expansion writes goes through the shelf —
768  /// `#krate::__private::<module>::<item>` with no exception — so emitted code depends on the shelf
769  /// rather than on where an item actually lives. [`RecordModel::framework`](crate::emit) is the
770  /// same function for the other model, and the two agree because the shelf's promise is one.
771  pub(crate) fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
772    let krate = &self.krate;
773    let module = module.iter().map(|segment| format_ident!("{segment}"));
774    let name = format_ident!("{name}");
775    quote::quote!(#krate::__private #(:: #module)* :: #name)
776  }
777}
778
779/// What an interface's CONTRACT trait is called: `<Interface>Fields`.
780///
781/// The projections every member answers — one method per declared field, whatever tier it is in.
782/// Named for what it is about rather than for what it does, as the declaration's own `fields(…)`
783/// block is.
784#[must_use]
785pub fn default_fields_name(interface: &syn::Ident) -> syn::Ident {
786  format_ident!("{interface}Fields")
787}
788
789/// What an interface's DERIVATIONS trait is called: `<Interface>Derivations`.
790///
791/// The COMPUTED subset, and the one trait a member writes by hand: the contract's stored half is
792/// emitted from the member's own columns, and its computed half delegates here.
793#[must_use]
794pub fn default_derivations_name(interface: &syn::Ident) -> syn::Ident {
795  format_ident!("{interface}Derivations")
796}
797
798/// What an interface's DISCRIMINANT is called: `<Interface>Kind`.
799///
800/// A stored interface addresses a member by `(kind, id)` — the shape the several-upstreams ruling
801/// already settled for a derived index's lineage — and the vocabulary naming which member a row came
802/// from is that pair's first half.
803#[must_use]
804pub fn default_kind_name(interface: &syn::Ident) -> syn::Ident {
805  format_ident!("{interface}Kind")
806}
807
808/// What an interface's ADDRESS is called: `<Interface>Id`.
809///
810/// A SUM over the members' own ids — one variant per member, carrying
811/// `<M as Identifiable>::Id` — because an interface addresses a member row by `(kind, id)` and the
812/// members need not agree about what an id IS. Heterogeneous member id types are legal by design:
813/// a `Video` keyed by an integer and an `Audio` keyed by text are one interface, and the enum is
814/// what lets one projection carry either.
815///
816/// The RECORD's own `<R>Id` convention does not exist to clash with — a record's id is a bare
817/// column type and gets no emitted name — so the suffix is free.
818#[must_use]
819pub fn default_id_name(interface: &syn::Ident) -> syn::Ident {
820  format_ident!("{interface}Id")
821}
822
823/// What an interface's ROW is called in one database: `<Interface><Db>Row`.
824///
825/// NOT [`default_row_name`](crate::model::default_row_name)'s convention: a record's row is
826/// `<Record><Suffix>` because it IS that record in that database, where an interface's is the shared
827/// projection its members' rows are read INTO — so the noun is part of the name.
828#[must_use]
829pub fn default_row_name(interface: &syn::Ident, kind: DatabaseKind) -> syn::Ident {
830  format_ident!("{interface}{}Row", kind.suffix())
831}
832
833/// What an interface's KEY is called: `<Interface>Key`.
834///
835/// The RECORD's convention exactly — reached through
836/// [`model::default_key_name`](crate::model::default_key_name) rather than respelled, because a name
837/// written twice is a name that can come to be written differently — over the same thing one
838/// declaration up: a SUM over `<M as Transformer>::Key`, because a key is the member's own and an
839/// interface joining members joins whatever keys they have.
840///
841/// The LAST name to leave this module's reserved list, and the only one that left by ruling rather
842/// than by a consumer — see the module note.
843#[must_use]
844pub fn default_key_name(interface: &syn::Ident) -> syn::Ident {
845  crate::model::default_key_name(interface)
846}
847
848/// What an interface's FILTER is called: `<Interface>Filter`.
849///
850/// The RECORD's convention, reached through [`model::default_filter_name`](crate::model::default_filter_name)
851/// rather than respelled — see [`default_key_name`] — and the type it names is the record's own
852/// filter one declaration over: a predicate a client sends, over the columns every member carries.
853#[must_use]
854pub fn default_filter_name(interface: &syn::Ident) -> syn::Ident {
855  crate::model::default_filter_name(interface)
856}
857
858/// What an interface's ORDER is called: `<Interface>OrderBy`. The RECORD's convention — see
859/// [`default_key_name`].
860#[must_use]
861pub fn default_order_by_name(interface: &syn::Ident) -> syn::Ident {
862  crate::model::default_order_by_name(interface)
863}
864
865/// What an interface's wire ARGUMENT object is called: `<Interface>GraphqlInput`.
866///
867/// The RECORD's convention — see [`default_key_name`] — over the lane an interface actually has:
868/// filter ▸ order ▸ first/last/after/before, and no ceiling and no skip, because
869/// `InterfaceFind` offers neither.
870#[must_use]
871pub fn default_input_name(interface: &syn::Ident) -> syn::Ident {
872  crate::model::default_input_name(interface)
873}
874
875/// What an interface's wire OUTPUT object is called: `<Interface>GraphqlOutput`. The RECORD's
876/// convention — see [`default_key_name`].
877#[must_use]
878pub fn default_output_name(interface: &syn::Ident) -> syn::Ident {
879  crate::model::default_output_name(interface)
880}