Skip to main content

ingraph_codegen/
unit.rs

1//! The FACTORED UNITS: the per-column emissions a grammar word composes, and the same emissions a
2//! standalone derive is the bare door of.
3//!
4//! # One authority, by construction
5//!
6//! A record's Filter, Comparison and OrderBy faces are each a per-column walk over a header and a
7//! list of rows. `#[ingraph::record(…)]` composes those walks and adds storage and wire extras;
8//! `#[derive(ingraph::Filter)]` and its two siblings compose the SAME walks and add nothing;
9//! `#[ingraph::interface(…)]` composes the filter and the order-by and adds the crossing, the term
10//! and the entry points. So the three doors' faces cannot drift: there is one emitter, and what
11//! separates a door from its neighbour is which rows it hands that emitter.
12//!
13//! The units take ROWS and not a model, which is what makes that true rather than aspirational: a
14//! model is what the record front end builds, and a unit that read one could only ever serve the
15//! record. Each row is the smallest thing the walk reads — a member, the NOUN a sentence calls it,
16//! the tokens the walk splices, and the paragraph a front end has to add — so a further front end
17//! supplies rows without owning a model at all.
18//!
19//! The nouns and the paragraphs are the caller's for one reason, stated once here and at each
20//! field: a walk that read a MODE to choose between *the `title` column* and *the shared `title`
21//! column* would be the near-duplicate again with a branch in it. The party that knows which is true
22//! spells it; the shape is never asked to guess.
23//!
24//! The identity is PINNED beside the by-construction argument: the same struct through the grammar
25//! word and through the bare derive, compared as TOKENS.
26//!
27//! # What is NOT here
28//!
29//! The per-database LOWERINGS (`ComplexComparison`, the `ORDER BY` clause builders, the order terms)
30//! and the storage extras. Those are the grammar words' own additions — a standalone type has no
31//! table to render against — and the split is the ruling's: the units are what the words COMPOSE,
32//! and storage and wire extras are what the words ADD.
33//!
34//! The ORDER-BY face is four functions rather than one, and the split follows the record's own
35//! GATES: the enum and `direction` exist wherever a term does, `identity` exists where a page can be
36//! completed, and `subject_path` exists wherever a wire order is decoded. A unit that emitted all
37//! three together would put a method on a record that has no page to use it.
38//!
39//! # The WIRE faces are here too, and B-27 is what put them here
40//!
41//! [`wire`](self::wire) carries the `InputType` impls the filter's struct and the order-by's enum
42//! wear. They were a record's alone until an interface joined the emitted root, which is what a
43//! filter and an order-by are SPENT by — so the same argument the struct halves already answered
44//! reaches the faces: one emitter, and what separates a door from its neighbour is which rows it
45//! hands that emitter.
46
47use quote::quote;
48
49use crate::{method::Member, name::RustSafeName};
50
51pub mod wire;
52
53/// What every unit needs of its caller before it reads a single column.
54///
55/// The `subject` is a NOUN and not a type path: the doc sentences read *a predicate over the stored
56/// columns of a `Cue`*, and the word in that sentence is the declaration's, which a standalone
57/// derive spells as the struct's own name.
58pub struct UnitHeader<'a> {
59  /// The visibility every emitted item carries — the declaration's own.
60  pub vis: &'a syn::Visibility,
61  /// The emitted type's name.
62  pub name: syn::Ident,
63  /// What the doc sentences call the thing these columns belong to, ALREADY SPELLED — a link where
64  /// the caller knows one resolves at the doc site, plain code otherwise.
65  ///
66  /// Spelled by the caller rather than built here, because whether `[`Cue`]` resolves is a fact
67  /// about where the expansion lands and the caller is the only party that knows it. A broken doc
68  /// link is a warning in a DECLARING crate's own build, which is the one place an emitter must not
69  /// put one.
70  pub subject: String,
71  /// A paragraph appended to the emitted face's own doc — what a reader of THIS subject's face has
72  /// to know that the SHAPE's sentence cannot state.
73  ///
74  /// The shape is the unit's and the sentence about it is too; what a front end knows on top of it
75  /// is a fact about the SUBJECT. An interface's filter is one per contract where a record's page
76  /// has one per database, and no sentence written from rows alone could say so — so the paragraph
77  /// arrives from the party that knows it, rather than the walk growing a mode to tell them apart.
78  ///
79  /// `None` where the shape's own sentence is the whole of it.
80  pub note: Option<String>,
81}
82
83impl UnitHeader<'_> {
84  /// The whole doc of one emitted face: the shape's sentence, then the caller's paragraph.
85  fn doc(&self, sentence: &str) -> String {
86    crate::emit::leading(&noted(sentence, self.note.as_deref()))
87  }
88}
89
90/// One sentence, and the paragraph a caller may put after it.
91fn noted(sentence: &str, note: Option<&str>) -> String {
92  match note {
93    Some(note) => format!("{sentence}\n\n{note}"),
94    None => sentence.to_owned(),
95  }
96}
97
98/// One column, as the FILTER unit reads it.
99pub struct FilterColumn {
100  /// The Rust member — layer 1, the field's own name.
101  pub member: syn::Ident,
102  /// The NOUN a doc sentence calls this column, ALREADY SPELLED — the backticked name and whatever
103  /// else the subject's own vocabulary puts on it, as in *`title` column*.
104  ///
105  /// Spelled by the caller for [`UnitHeader::subject`]'s reason one layer down: an interface's
106  /// columns are the SHARED ones and a record's are its own, and which adjective is true is a fact
107  /// about the front end rather than about this walk. The head noun rides along with it, so a
108  /// subject whose column is a COLLECTION says that instead.
109  pub name: String,
110  /// The filter this column is guarded by, already projected through the marker layer.
111  pub filter: proc_macro2::TokenStream,
112  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
113  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
114  /// condition seat.
115  ///
116  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
117  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
118  /// arrives with the column exactly as its filter and its noun do. See
119  /// [`Condition`](crate::model::Condition).
120  pub gate: proc_macro2::TokenStream,
121}
122
123/// One column, as the COMPARISON unit reads it.
124pub struct ComparisonColumn {
125  /// The Rust member — layer 1, the field's own name.
126  pub member: syn::Ident,
127  /// The NOUN a doc sentence calls this column, ALREADY SPELLED — see [`FilterColumn::name`].
128  pub name: String,
129  /// What this column's field is held at —
130  /// `<F as ToDatabaseComparison<V, Db>>::Comparison`, built by the caller because which FILTER and
131  /// which STORED type a column has is the grammar word's answer.
132  pub held: proc_macro2::TokenStream,
133  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
134  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
135  /// condition seat.
136  ///
137  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
138  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
139  /// arrives with the column exactly as its filter and its noun do. See
140  /// [`Condition`](crate::model::Condition).
141  pub gate: proc_macro2::TokenStream,
142}
143
144/// One column, as the ORDER-BY unit reads it.
145pub struct OrderColumn {
146  /// The variant this column is ordered by — the member in upper camel, which is what makes the
147  /// variant rename-proof.
148  pub variant: syn::Ident,
149  /// The NOUN a doc sentence calls this column, ALREADY SPELLED — see [`FilterColumn::name`].
150  pub name: String,
151  /// The SEMANTIC IDENTITY a cursor folds — the member's own external spelling, which no rename
152  /// moves.
153  pub identity: String,
154  /// A paragraph appended to THIS variant's doc — [`UnitHeader::note`] one layer down, and for its
155  /// reason: whether a page over this column is refused before a row is read is the front end's
156  /// answer and not the walk's.
157  pub note: Option<String>,
158  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
159  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
160  /// condition seat.
161  ///
162  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
163  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
164  /// arrives with the column exactly as its filter and its noun do. See
165  /// [`Condition`](crate::model::Condition).
166  pub gate: proc_macro2::TokenStream,
167}
168
169impl OrderColumn {
170  /// One row built from a member and the noun a sentence calls its column — the two derivations
171  /// written once, so a variant and an identity cannot come to disagree about which column they name.
172  pub fn of(member: &syn::Ident, name: String) -> Self {
173    Self {
174      variant: crate::emit::upper_camel(&member.to_string()),
175      name,
176      identity: RustSafeName::from_ident(member).external().to_owned(),
177      note: None,
178      gate: proc_macro2::TokenStream::new(),
179    }
180  }
181
182  /// The same row, carrying the paragraph this column's own variant adds.
183  #[must_use]
184  pub fn with_note(mut self, note: String) -> Self {
185    self.note = Some(note);
186    self
187  }
188
189  /// The same row, carrying the CONDITION its column is declared under.
190  #[must_use]
191  pub fn with_gate(mut self, gate: proc_macro2::TokenStream) -> Self {
192    self.gate = gate;
193    self
194  }
195}
196
197/// The FILTER face: a struct with one optional filter per column, and the builder pair per member.
198///
199/// # Each field carries its type's FILTER, never its value
200///
201/// `Option<value>` expresses equality ALONE, and on a nullable column it collapses three states — no
202/// predicate, `IS NULL`, `= v` — into two, making a null match inexpressible. The framework carries
203/// the null test on a `Nullable<F>` wrapper and registers `Option<T>` to it, where a bare `T` gets
204/// the plain filter, so nullability needs no detection here — and must get NONE: the domain type is
205/// written verbatim, and normalising an `Option` away would hand a nullable column the filter of a
206/// `NOT NULL` one, where `IS NULL` does not exist.
207///
208/// # `with_*` names the builder step
209///
210/// The argument is a filter rather than a value: its TYPE is the filter's and its ROLE is the
211/// builder's — it is what the field takes in the value being built. `filter_*` would read as
212/// APPLYING a filter rather than setting one, and every emitted key already spells this shape
213/// `with_*`.
214pub fn filter(
215  header: &UnitHeader<'_>,
216  columns: &[FilterColumn],
217) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
218  let (vis, name, subject) = (&header.vis, &header.name, &header.subject);
219  let substrate = crate::emit::substrate();
220
221  let fields = columns.iter().map(|column| {
222    let (member, filter, gate) = (&column.member, &column.filter, &column.gate);
223    quote!(#gate #substrate #member: ::core::option::Option<#filter>,)
224  });
225  let doc = header.doc(&format!(
226    "A predicate over the stored columns of a {subject} — each field its type's FILTER, so a client \
227     may ask for any shape the framework's filters offer rather than equality alone."
228  ));
229  let declaration = quote! {
230    #[doc = #doc]
231    #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::default::Default)]
232    #vis struct #name {
233      #(#fields)*
234    }
235  };
236
237  let builders = columns.iter().map(|column| {
238    let (member, filter, gate) = (&column.member, &column.filter, &column.gate);
239    let with = Member::With.name(member);
240    let borrow = Member::Borrow.name(member);
241    let doc = crate::emit::leading(&format!(
242      "The same predicate with a filter on the {}.",
243      column.name
244    ));
245    let borrow_doc = crate::emit::leading(&format!("The filter on the {}, if any.", column.name));
246    quote! {
247      #gate
248      #[doc = #doc]
249      #[must_use]
250      #[inline]
251      #vis fn #with(mut self, filter: #filter) -> Self {
252        self.#member = ::core::option::Option::Some(filter);
253        self
254      }
255
256      #gate
257      #[doc = #borrow_doc]
258      #[inline]
259      #vis const fn #borrow(&self) -> ::core::option::Option<&#filter> {
260        self.#member.as_ref()
261      }
262    }
263  });
264
265  (
266    declaration,
267    quote! {
268      impl #name {
269        #(#builders)*
270      }
271    },
272  )
273}
274
275/// The COMPARISON face: a struct holding one crossed comparison per column, over a database
276/// parameter, under the `where` clause its field types are well formed by.
277///
278/// # The empty case gets a `PhantomData`, and only it
279///
280/// With no column the database parameter occurs nowhere in the struct and `E0392` would land inside
281/// an expansion its author cannot edit. Nothing can collide with the name, because a collision would
282/// have to be with a column and there are none.
283///
284/// # The `where` clause is the CALLER's
285///
286/// What a comparison assumes is one list — that the database is a `Backend` at all, and that each
287/// column's filter crosses into something for it — and the struct's clause is the whole of what
288/// makes its field types well formed. The unit takes it rather than building it because the
289/// refinement a `flatten` column states is a fact about the COLUMN's storage, which is a grammar
290/// word's business and not this walk's. An impl asserting anything MORE would report a missing
291/// crossing twice; one asserting less would not apply to the type it is written for — so the clause
292/// is spliced verbatim into both.
293pub fn comparison(
294  header: &UnitHeader<'_>,
295  database: &syn::Ident,
296  crossings: &proc_macro2::TokenStream,
297  columns: &[ComparisonColumn],
298) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
299  let (vis, name, subject) = (&header.vis, &header.name, &header.subject);
300
301  // A FUNCTION PARAMETER and a struct-expression field are both attribute positions, so the
302  // positional `new` really loses an argument where its column is gone — and the crossing that calls
303  // it loses the same one, both walks reading this one list.
304  let members = columns.iter().map(|column| {
305    let (member, gate) = (&column.member, &column.gate);
306    quote!(#gate #member,)
307  });
308  let marker = columns
309    .is_empty()
310    .then(|| quote!(db: ::core::marker::PhantomData<fn() -> #database>,));
311
312  let fields = columns.iter().map(|column| {
313    let (member, held, gate) = (&column.member, &column.held, &column.gate);
314    quote!(#gate #member: #held,)
315  });
316  let doc = header.doc(&format!(
317    "A predicate over a {subject}'s columns, in the types this database stores — each field the \
318     comparison its column's filter crosses into, so a query may ask for any shape that column's \
319     operators offer rather than equality alone."
320  ));
321  let declaration = quote! {
322    #[doc = #doc]
323    #vis struct #name<#database>
324    where
325      #crossings
326    {
327      #(#fields)*
328      #marker
329    }
330  };
331
332  // A borrow rather than an `Option<&…>`: whether the column is compared at all is the kind's own
333  // `is_empty`, so an outer `Option` would be a second encoding of a fact the value already
334  // carries — and two encodings of one fact can disagree.
335  let accessors = columns.iter().map(|column| {
336    let (member, held, gate) = (&column.member, &column.held, &column.gate);
337    let borrow = Member::Borrow.name(member);
338    let doc = crate::emit::leading(&format!(
339      "The predicate on the {}, in the type this database stores.",
340      column.name
341    ));
342    quote! {
343      #gate
344      #[doc = #doc]
345      #[inline]
346      #vis const fn #borrow(&self) -> &#held {
347        &self.#member
348      }
349    }
350  });
351  // Positional, in column order, and the only construction path there is: `Default` went with the
352  // shape and the fields are private, so before this a comparison could be named and not built. It
353  // takes one PREDICATE per column rather than one value, which is what the fields are; the empty
354  // comparison is `Default` on each kind, passed in one at a time.
355  let arguments = columns.iter().map(|column| {
356    let (member, held, gate) = (&column.member, &column.held, &column.gate);
357    quote!(#gate #member: #held,)
358  });
359  let marker_field = columns
360    .is_empty()
361    .then(|| quote!(db: ::core::marker::PhantomData,));
362  let new_doc = crate::emit::leading(
363    "Construct a predicate from one comparison per column, in the order this database stores them.",
364  );
365  let arity = crate::emit::wide_signature();
366
367  (
368    declaration,
369    quote! {
370      impl<#database> #name<#database>
371      where
372        #crossings
373      {
374        #[doc = #new_doc]
375        #arity
376        #[inline]
377        #vis const fn new(#(#arguments)*) -> Self {
378          Self { #(#members)* #marker_field }
379        }
380
381        #(#accessors)*
382      }
383    },
384  )
385}
386
387/// The ORDER-BY face: one variant per orderable column, each CARRYING its direction, plus the
388/// question every term answers whatever a database does with it.
389///
390/// # One value is one whole term
391///
392/// A query orders by a LIST of these, and the list is ordered by the GraphQL specification where an
393/// input object's fields are not: `ORDER BY a, b` is not `ORDER BY b, a`, so the sequence is carried
394/// by the one structure the spec calls ordered. Two parallel lists — `orderBy: [a, b],
395/// orderDirection: [desc]` — is the shape this replaces, and the pairing is why: nothing in a type
396/// system makes two lists the same length, so a mismatch is silently completed rather than refused.
397///
398/// The SHAPE is async-graphql's `OneofObject` — an enum of single-value tuple variants — and that
399/// derive is the backend's, so it is not emitted here. What is emitted is the shape it takes.
400///
401/// An or-pattern in `direction` rather than an arm per variant, because every arm's body is the
402/// binding and nothing else. The EMPTY case is a subject that stores no column at all: the enum is
403/// uninhabited there and the empty `match` is what a value of it can be taken apart into.
404pub fn order_by(
405  header: &UnitHeader<'_>,
406  direction_ty: &proc_macro2::TokenStream,
407  columns: &[OrderColumn],
408) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
409  let (vis, name, subject) = (&header.vis, &header.name, &header.subject);
410
411  let variants = columns.iter().map(|column| {
412    let (variant, gate) = (&column.variant, &column.gate);
413    let doc = crate::emit::leading(&noted(
414      &format!("Order by the {}, in the direction given.", column.name),
415      column.note.as_deref(),
416    ));
417    quote! {
418      #gate
419      #[doc = #doc]
420      #variant(#direction_ty),
421    }
422  });
423  let doc = header.doc(&format!(
424    "One ordering term over a {subject} — which column, and which way it runs."
425  ));
426  let declaration = quote! {
427    #[doc = #doc]
428    #[derive(
429      ::core::fmt::Debug, ::core::clone::Clone,
430      ::core::marker::Copy,
431      ::core::cmp::PartialEq,
432      ::core::cmp::Eq
433    )]
434    #vis enum #name {
435      #(#variants)*
436    }
437  };
438
439  // ONE ARM PER VARIANT where any is conditional, and an or-pattern where none is. A pattern
440  // ALTERNATIVE is not an attribute position — `A(d) | #[cfg(…)] B(d)` is not Rust — so a variant the
441  // build removed could not leave the alternation; an arm can carry the gate, and every arm's body is
442  // the same binding either way.
443  let conditional = columns.iter().any(|column| !column.gate.is_empty());
444  let body = if columns.is_empty() {
445    quote!(match self {})
446  } else if conditional {
447    let arms = columns.iter().map(|column| {
448      let (variant, gate) = (&column.variant, &column.gate);
449      quote!(#gate Self::#variant(direction) => direction,)
450    });
451    quote! {
452      match self {
453        #(#arms)*
454      }
455    }
456  } else {
457    let bindings = columns.iter().map(|column| {
458      let variant = &column.variant;
459      quote!(Self::#variant(direction))
460    });
461    quote! {
462      match self {
463        #(#bindings)|* => direction,
464      }
465    }
466  };
467  let doc = crate::emit::leading("Which way this term runs.");
468
469  (
470    declaration,
471    quote! {
472      #[doc = #doc]
473      #[inline]
474      #vis const fn direction(self) -> #direction_ty {
475        #body
476      }
477    },
478  )
479}
480
481/// The SEMANTIC IDENTITY method — the one input a cursor's SIGNATURE takes from a term.
482///
483/// It is the FIELD's own name — the name a per-database rename renames FROM — so a cursor minted
484/// against one deployment's dialect is the same order's on the next: a rendered name would SPLIT one
485/// order apart the moment either database renamed a column, and could ALIAS two orders together
486/// where two renames crossed.
487///
488/// It is no longer the ONLY name a rename cannot move — the variant is one too, being built from the
489/// same member — and that is a strengthening rather than a redundancy. What this still answers is
490/// what a variant cannot: a VALUE a decoder generic over the term type can ask for, fold into a
491/// signature and compare, where a variant is a type-level thing each subject spells for itself.
492///
493/// A method of its own rather than a part of [`order_by`], because its GATE is not the enum's: it is
494/// the PAGE's, and a subject with no page to complete has nothing to do with it.
495pub fn order_identity(
496  vis: &syn::Visibility,
497  term_name: &proc_macro2::TokenStream,
498  columns: &[OrderColumn],
499) -> proc_macro2::TokenStream {
500  let identities = columns.iter().map(|column| {
501    let (variant, identity, gate) = (&column.variant, &column.identity, &column.gate);
502    quote!(#gate Self::#variant(_) => #term_name::new(#identity),)
503  });
504  let body = if columns.is_empty() {
505    quote!(match self {})
506  } else {
507    quote! {
508      match self {
509        #(#identities)*
510      }
511    }
512  };
513  let doc = crate::emit::leading(
514    "WHICH column this term names, under the name a per-database rename cannot move — what a \
515     cursor's signature is folded from.",
516  );
517  quote! {
518    #[doc = #doc]
519    #[inline]
520    #vis const fn identity(self) -> &'static #term_name {
521      #body
522    }
523  }
524}
525
526/// THE SAME identity, as the wire's decode reads it: a PATH rather than one name, and answered
527/// through a trait so a decoder generic over the term type can ask.
528///
529/// The arms are built from the same rows [`order_identity`]'s are, so the two cannot drift into
530/// naming different columns. What differs is the SHAPE and the GATE. The shape is a path because
531/// `cover.title` and `title` are two subjects and so are `cover.title` and `cover.duration` — every
532/// emitted term is one segment today, and the path is what keeps the day a term reaches through a
533/// relation from being a change to the uniqueness rule. The gate is none: `identity` is the PAGE's,
534/// where a wire order is every order-capable subject's.
535///
536/// A `const` ITEM per arm, and not an inline `const { … }` block: the block does not make the borrow
537/// inside it `'static` either, so both spellings without an item are `E0716`.
538///
539/// `match *self` rather than `match self`, and the EMPTY case is what forces it: the trait takes
540/// `&self`, a reference is always considered INHABITED, and an empty match on one is `E0004` even
541/// where the enum has no variant to write an arm for. Dereferencing puts the match back on the
542/// uninhabited place. The populated arm follows the same spelling rather than the reverse, so a
543/// subject storing one column and a subject storing none read alike; no arm binds, so nothing moves
544/// out of the borrow.
545pub fn order_subject_path(
546  name: &syn::Ident,
547  to_subject_path: &proc_macro2::TokenStream,
548  subject_path: &proc_macro2::TokenStream,
549  term_name: &proc_macro2::TokenStream,
550  columns: &[OrderColumn],
551) -> proc_macro2::TokenStream {
552  let subjects = columns.iter().map(|column| {
553    let (variant, identity, gate) = (&column.variant, &column.identity, &column.gate);
554    quote! {
555      #gate
556      Self::#variant(_) => {
557        const __INGRAPH_SUBJECT: #subject_path =
558          #subject_path::new(&[#term_name::new(#identity)]);
559        __INGRAPH_SUBJECT
560      }
561    }
562  });
563  let body = if columns.is_empty() {
564    quote!(match *self {})
565  } else {
566    quote! {
567      match *self {
568        #(#subjects)*
569      }
570    }
571  };
572  quote! {
573    #[automatically_derived]
574    impl #to_subject_path for #name {
575      #[inline]
576      fn subject_path(&self) -> #subject_path {
577        #body
578      }
579    }
580  }
581}
582
583/// One column, as the comparison's LOWERING reads it.
584pub struct LoweringColumn {
585  /// The Rust member — layer 1, which no word moves.
586  pub member: syn::Ident,
587  /// The name this database RENDERS the column under — layer 3, which a per-database rename moves.
588  ///
589  /// Empty where no frame is pushed, which is the one state that has no rendered name to carry: see
590  /// [`flatten`](Self::flatten).
591  pub rendered: String,
592  /// Whether this member is applied at the holder's OWN address rather than one segment below it.
593  ///
594  /// Two declarations reach it and their reasons are different. A `flatten` COLUMN lends no name, so
595  /// its type's columns join the holder's namespace. A REVERSE RELATION position names no column of
596  /// this row at all — only the child's foreign key and this row's id, both known without it — so
597  /// the address it is handed goes unread and a frame below it would be a segment nothing renders.
598  ///
599  /// One flag rather than two, because what the emission does with it is one thing: not pushing a
600  /// frame. [`unframed`](Self::unframed) is the second reason's own door, so a reader of a call site
601  /// sees which of the two it is.
602  pub flatten: bool,
603  /// The qualified path this member's lowering is reached through — `None` for the
604  /// `ComplexComparison<Db>` every column takes.
605  ///
606  /// A RELATION member takes the other door, and the reason is the wall its own crossing note
607  /// records: its type is a projection through `ToRelatedComparison`, and a `where` clause saying
608  /// that projection lowers resolves through the impl that defines it, demanding of a generic `Db`
609  /// what only a concrete one can give. `ToLoweredRelatedComparison` carries the rendering as
610  /// METHODS over the FILTER, so the call names no projection and the clause names no dialect.
611  ///
612  /// A `TokenStream` rather than a flag, because the path carries the position's own far side —
613  /// `<RelatedFilter<…> as ToLoweredRelatedComparison<…, DB>>` — which only the caller knows.
614  pub through: Option<proc_macro2::TokenStream>,
615  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
616  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
617  /// condition seat.
618  ///
619  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
620  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
621  /// arrives with the column exactly as its filter and its noun do. See
622  /// [`Condition`](crate::model::Condition).
623  pub gate: proc_macro2::TokenStream,
624}
625
626impl LoweringColumn {
627  /// A member applied at the address it is handed, under no name of its own — what a REVERSE
628  /// RELATION position is.
629  #[must_use]
630  pub fn unframed(member: syn::Ident, through: proc_macro2::TokenStream) -> Self {
631    Self {
632      member,
633      rendered: String::new(),
634      flatten: true,
635      through: Some(through),
636      gate: proc_macro2::TokenStream::new(),
637    }
638  }
639
640  /// A member applied one segment below the address, under the name `rendered` — an ordinary COLUMN,
641  /// or a forward relation position, which renders at the FOREIGN KEY's own address.
642  #[must_use]
643  pub fn framed(
644    member: syn::Ident,
645    rendered: String,
646    through: Option<proc_macro2::TokenStream>,
647  ) -> Self {
648    Self {
649      member,
650      rendered,
651      flatten: false,
652      through,
653      gate: proc_macro2::TokenStream::new(),
654    }
655  }
656
657  /// The same row, carrying the CONDITION its column is declared under.
658  #[must_use]
659  pub fn with_gate(mut self, gate: proc_macro2::TokenStream) -> Self {
660    self.gate = gate;
661    self
662  }
663}
664
665/// The framework seats the LOWERING spells, resolved by the caller through its own shelf.
666pub struct LoweringSeats {
667  /// `comparison::Backend`.
668  pub backend: proc_macro2::TokenStream,
669  /// `comparison::ComplexComparison`.
670  pub complex: proc_macro2::TokenStream,
671  /// `comparison::Frame`.
672  pub frame: proc_macro2::TokenStream,
673  /// `comparison::At`.
674  pub at: proc_macro2::TokenStream,
675  /// `field::FieldName`.
676  pub field_name: proc_macro2::TokenStream,
677}
678
679/// The comparison's LOWERING: `ComplexComparison`, threading one accumulator through the columns.
680///
681/// # It needs no predicate the struct did not already carry
682///
683/// Each field is held at `<F as ToDatabaseComparison<V, Db>>::Comparison`, and the map's ITEM BOUND
684/// — `type Comparison: ComplexComparison<Db>` — is what says such a field lowers. So the `where`
685/// clause is the struct's own, spliced verbatim, and nothing here adds to it.
686///
687/// # The two names of one column, a layer apart
688///
689/// The MEMBER this reads is the field's and no word moves it; the FRAME pushed below is the string
690/// this database RENDERS, which a per-database rename is exactly what moves. A `flatten` column
691/// pushes no frame at all — its own name is dropped, so its type's columns join the holder's
692/// namespace.
693///
694/// A sum with no leading zero: `0 + x` is `clippy::identity_op`, which a consumer building under
695/// `-D warnings` would see inside an expansion it cannot edit.
696pub fn comparison_lowering(
697  name: &syn::Ident,
698  database: &syn::Ident,
699  crossings: &proc_macro2::TokenStream,
700  seats: &LoweringSeats,
701  columns: &[LoweringColumn],
702) -> proc_macro2::TokenStream {
703  let LoweringSeats {
704    backend,
705    complex,
706    frame,
707    at,
708    field_name,
709  } = seats;
710
711  // The DOOR each member's lowering is reached through: `ComplexComparison<Db>` for a column, and the
712  // relation map's refinement for a position — see [`LoweringColumn::through`] for the wall that
713  // second door exists to walk around.
714  let door = |column: &LoweringColumn| {
715    column
716      .through
717      .clone()
718      .unwrap_or_else(|| quote!(#complex::<#database>))
719  };
720  // An OPERAND of a binary expression is not an attribute position — `a + #[cfg(…)] b` is not Rust
721  // — so where any column is conditional the sum is ACCUMULATED in statements a gate can sit on. The
722  // `+` chain stays wherever nothing can be absent, which is every declaration that wrote no
723  // condition.
724  let conditional = columns.iter().any(|column| !column.gate.is_empty());
725  let conjuncts = if columns.is_empty() {
726    quote!(0)
727  } else if conditional {
728    let counts = columns.iter().map(|column| {
729      let (member, door, gate) = (&column.member, door(column), &column.gate);
730      quote! {
731        #gate
732        {
733          __ingraph_conjuncts += #door::conjuncts(&self.#member);
734        }
735      }
736    });
737    quote! {
738      {
739        let mut __ingraph_conjuncts = 0usize;
740        #(#counts)*
741        __ingraph_conjuncts
742      }
743    }
744  } else {
745    let counts = columns.iter().map(|column| {
746      let (member, door) = (&column.member, door(column));
747      quote!(#door::conjuncts(&self.#member))
748    });
749    quote!(#(#counts)+*)
750  };
751
752  let parts = columns.iter().map(|column| {
753    let (member, rendered, door) = (&column.member, &column.rendered, door(column));
754    let gate = &column.gate;
755    if column.flatten {
756      return quote! {
757        #gate
758        let __ingraph_builder = #door::apply(
759          &self.#member,
760          __ingraph_at,
761          __ingraph_builder,
762        )?;
763      };
764    }
765    quote! {
766      #gate
767      let __ingraph_frame = #at::frame(__ingraph_at, #field_name::new(#rendered));
768      #gate
769      let __ingraph_builder = #door::apply(
770        &self.#member,
771        #frame::at(&__ingraph_frame),
772        __ingraph_builder,
773      )?;
774    }
775  });
776  let at_binding = if columns.is_empty() {
777    quote!(_)
778  } else {
779    quote!(__ingraph_at)
780  };
781
782  let conjuncts_doc = crate::emit::leading(
783    "How many conjuncts this predicate renders — the sum over its columns, since each is a \
784     comparison of its own.",
785  );
786  let apply_doc = crate::emit::leading(
787    "Render every column's conjuncts into `builder`, each at the same row and one segment below the \
788     address this predicate was applied at.",
789  );
790  quote! {
791    #[automatically_derived]
792    impl<#database> #complex<#database> for #name<#database>
793    where
794      #crossings
795    {
796      #[doc = #conjuncts_doc]
797      #[inline]
798      fn conjuncts(&self) -> ::core::primitive::usize {
799        #conjuncts
800      }
801
802      #[doc = #apply_doc]
803      fn apply<'q>(
804        &'q self,
805        #at_binding: #at<'_>,
806        __ingraph_builder: <#database as #backend>::Builder<'q>,
807      ) -> ::core::result::Result<
808        <#database as #backend>::Builder<'q>,
809        <#database as #backend>::Error,
810      > {
811        #(#parts)*
812        ::core::result::Result::Ok(__ingraph_builder)
813      }
814    }
815  }
816}