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
//! The FACTORED UNITS: the per-column emissions a grammar word composes, and the same emissions a
//! standalone derive is the bare door of.
//!
//! # One authority, by construction
//!
//! A record's Filter, Comparison and OrderBy faces are each a per-column walk over a header and a
//! list of rows. `#[ingraph::record(…)]` composes those walks and adds storage and wire extras;
//! `#[derive(ingraph::Filter)]` and its two siblings compose the SAME walks and add nothing;
//! `#[ingraph::interface(…)]` composes the filter and the order-by and adds the crossing, the term
//! and the entry points. So the three doors' faces cannot drift: there is one emitter, and what
//! separates a door from its neighbour is which rows it hands that emitter.
//!
//! The units take ROWS and not a model, which is what makes that true rather than aspirational: a
//! model is what the record front end builds, and a unit that read one could only ever serve the
//! record. Each row is the smallest thing the walk reads — a member, the NOUN a sentence calls it,
//! the tokens the walk splices, and the paragraph a front end has to add — so a further front end
//! supplies rows without owning a model at all.
//!
//! The nouns and the paragraphs are the caller's for one reason, stated once here and at each
//! field: a walk that read a MODE to choose between *the `title` column* and *the shared `title`
//! column* would be the near-duplicate again with a branch in it. The party that knows which is true
//! spells it; the shape is never asked to guess.
//!
//! The identity is PINNED beside the by-construction argument: the same struct through the grammar
//! word and through the bare derive, compared as TOKENS.
//!
//! # What is NOT here
//!
//! The per-database LOWERINGS (`ComplexComparison`, the `ORDER BY` clause builders, the order terms)
//! and the storage extras. Those are the grammar words' own additions — a standalone type has no
//! table to render against — and the split is the ruling's: the units are what the words COMPOSE,
//! and storage and wire extras are what the words ADD.
//!
//! The ORDER-BY face is four functions rather than one, and the split follows the record's own
//! GATES: the enum and `direction` exist wherever a term does, `identity` exists where a page can be
//! completed, and `subject_path` exists wherever a wire order is decoded. A unit that emitted all
//! three together would put a method on a record that has no page to use it.
//!
//! # The WIRE faces are here too, and B-27 is what put them here
//!
//! [`wire`](self::wire) carries the `InputType` impls the filter's struct and the order-by's enum
//! wear. They were a record's alone until an interface joined the emitted root, which is what a
//! filter and an order-by are SPENT by — so the same argument the struct halves already answered
//! reaches the faces: one emitter, and what separates a door from its neighbour is which rows it
//! hands that emitter.

use quote::quote;

use crate::{method::Member, name::RustSafeName};

pub mod wire;

/// What every unit needs of its caller before it reads a single column.
///
/// The `subject` is a NOUN and not a type path: the doc sentences read *a predicate over the stored
/// columns of a `Cue`*, and the word in that sentence is the declaration's, which a standalone
/// derive spells as the struct's own name.
pub struct UnitHeader<'a> {
  /// The visibility every emitted item carries — the declaration's own.
  pub vis: &'a syn::Visibility,
  /// The emitted type's name.
  pub name: syn::Ident,
  /// What the doc sentences call the thing these columns belong to, ALREADY SPELLED — a link where
  /// the caller knows one resolves at the doc site, plain code otherwise.
  ///
  /// Spelled by the caller rather than built here, because whether `[`Cue`]` resolves is a fact
  /// about where the expansion lands and the caller is the only party that knows it. A broken doc
  /// link is a warning in a DECLARING crate's own build, which is the one place an emitter must not
  /// put one.
  pub subject: String,
  /// A paragraph appended to the emitted face's own doc — what a reader of THIS subject's face has
  /// to know that the SHAPE's sentence cannot state.
  ///
  /// The shape is the unit's and the sentence about it is too; what a front end knows on top of it
  /// is a fact about the SUBJECT. An interface's filter is one per contract where a record's page
  /// has one per database, and no sentence written from rows alone could say so — so the paragraph
  /// arrives from the party that knows it, rather than the walk growing a mode to tell them apart.
  ///
  /// `None` where the shape's own sentence is the whole of it.
  pub note: Option<String>,
}

impl UnitHeader<'_> {
  /// The whole doc of one emitted face: the shape's sentence, then the caller's paragraph.
  fn doc(&self, sentence: &str) -> String {
    crate::emit::leading(&noted(sentence, self.note.as_deref()))
  }
}

/// One sentence, and the paragraph a caller may put after it.
fn noted(sentence: &str, note: Option<&str>) -> String {
  match note {
    Some(note) => format!("{sentence}\n\n{note}"),
    None => sentence.to_owned(),
  }
}

/// One column, as the FILTER unit reads it.
pub struct FilterColumn {
  /// The Rust member — layer 1, the field's own name.
  pub member: syn::Ident,
  /// The NOUN a doc sentence calls this column, ALREADY SPELLED — the backticked name and whatever
  /// else the subject's own vocabulary puts on it, as in *`title` column*.
  ///
  /// Spelled by the caller for [`UnitHeader::subject`]'s reason one layer down: an interface's
  /// columns are the SHARED ones and a record's are its own, and which adjective is true is a fact
  /// about the front end rather than about this walk. The head noun rides along with it, so a
  /// subject whose column is a COLLECTION says that instead.
  pub name: String,
  /// The filter this column is guarded by, already projected through the marker layer.
  pub filter: proc_macro2::TokenStream,
  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
  /// condition seat.
  ///
  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
  /// arrives with the column exactly as its filter and its noun do. See
  /// [`Condition`](crate::model::Condition).
  pub gate: proc_macro2::TokenStream,
}

/// One column, as the COMPARISON unit reads it.
pub struct ComparisonColumn {
  /// The Rust member — layer 1, the field's own name.
  pub member: syn::Ident,
  /// The NOUN a doc sentence calls this column, ALREADY SPELLED — see [`FilterColumn::name`].
  pub name: String,
  /// What this column's field is held at —
  /// `<F as ToDatabaseComparison<V, Db>>::Comparison`, built by the caller because which FILTER and
  /// which STORED type a column has is the grammar word's answer.
  pub held: proc_macro2::TokenStream,
  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
  /// condition seat.
  ///
  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
  /// arrives with the column exactly as its filter and its noun do. See
  /// [`Condition`](crate::model::Condition).
  pub gate: proc_macro2::TokenStream,
}

/// One column, as the ORDER-BY unit reads it.
pub struct OrderColumn {
  /// The variant this column is ordered by — the member in upper camel, which is what makes the
  /// variant rename-proof.
  pub variant: syn::Ident,
  /// The NOUN a doc sentence calls this column, ALREADY SPELLED — see [`FilterColumn::name`].
  pub name: String,
  /// The SEMANTIC IDENTITY a cursor folds — the member's own external spelling, which no rename
  /// moves.
  pub identity: String,
  /// A paragraph appended to THIS variant's doc — [`UnitHeader::note`] one layer down, and for its
  /// reason: whether a page over this column is refused before a row is read is the front end's
  /// answer and not the walk's.
  pub note: Option<String>,
  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
  /// condition seat.
  ///
  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
  /// arrives with the column exactly as its filter and its noun do. See
  /// [`Condition`](crate::model::Condition).
  pub gate: proc_macro2::TokenStream,
}

impl OrderColumn {
  /// One row built from a member and the noun a sentence calls its column — the two derivations
  /// written once, so a variant and an identity cannot come to disagree about which column they name.
  pub fn of(member: &syn::Ident, name: String) -> Self {
    Self {
      variant: crate::emit::upper_camel(&member.to_string()),
      name,
      identity: RustSafeName::from_ident(member).external().to_owned(),
      note: None,
      gate: proc_macro2::TokenStream::new(),
    }
  }

  /// The same row, carrying the paragraph this column's own variant adds.
  #[must_use]
  pub fn with_note(mut self, note: String) -> Self {
    self.note = Some(note);
    self
  }

  /// The same row, carrying the CONDITION its column is declared under.
  #[must_use]
  pub fn with_gate(mut self, gate: proc_macro2::TokenStream) -> Self {
    self.gate = gate;
    self
  }
}

/// The FILTER face: a struct with one optional filter per column, and the builder pair per member.
///
/// # Each field carries its type's FILTER, never its value
///
/// `Option<value>` expresses equality ALONE, and on a nullable column it collapses three states — no
/// predicate, `IS NULL`, `= v` — into two, making a null match inexpressible. The framework carries
/// the null test on a `Nullable<F>` wrapper and registers `Option<T>` to it, where a bare `T` gets
/// the plain filter, so nullability needs no detection here — and must get NONE: the domain type is
/// written verbatim, and normalising an `Option` away would hand a nullable column the filter of a
/// `NOT NULL` one, where `IS NULL` does not exist.
///
/// # `with_*` names the builder step
///
/// The argument is a filter rather than a value: its TYPE is the filter's and its ROLE is the
/// builder's — it is what the field takes in the value being built. `filter_*` would read as
/// APPLYING a filter rather than setting one, and every emitted key already spells this shape
/// `with_*`.
pub fn filter(
  header: &UnitHeader<'_>,
  columns: &[FilterColumn],
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
  let (vis, name, subject) = (&header.vis, &header.name, &header.subject);
  let substrate = crate::emit::substrate();

  let fields = columns.iter().map(|column| {
    let (member, filter, gate) = (&column.member, &column.filter, &column.gate);
    quote!(#gate #substrate #member: ::core::option::Option<#filter>,)
  });
  let doc = header.doc(&format!(
    "A predicate over the stored columns of a {subject} — each field its type's FILTER, so a client \
     may ask for any shape the framework's filters offer rather than equality alone."
  ));
  let declaration = quote! {
    #[doc = #doc]
    #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::default::Default)]
    #vis struct #name {
      #(#fields)*
    }
  };

  let builders = columns.iter().map(|column| {
    let (member, filter, gate) = (&column.member, &column.filter, &column.gate);
    let with = Member::With.name(member);
    let borrow = Member::Borrow.name(member);
    let doc = crate::emit::leading(&format!(
      "The same predicate with a filter on the {}.",
      column.name
    ));
    let borrow_doc = crate::emit::leading(&format!("The filter on the {}, if any.", column.name));
    quote! {
      #gate
      #[doc = #doc]
      #[must_use]
      #[inline]
      #vis fn #with(mut self, filter: #filter) -> Self {
        self.#member = ::core::option::Option::Some(filter);
        self
      }

      #gate
      #[doc = #borrow_doc]
      #[inline]
      #vis const fn #borrow(&self) -> ::core::option::Option<&#filter> {
        self.#member.as_ref()
      }
    }
  });

  (
    declaration,
    quote! {
      impl #name {
        #(#builders)*
      }
    },
  )
}

/// The COMPARISON face: a struct holding one crossed comparison per column, over a database
/// parameter, under the `where` clause its field types are well formed by.
///
/// # The empty case gets a `PhantomData`, and only it
///
/// With no column the database parameter occurs nowhere in the struct and `E0392` would land inside
/// an expansion its author cannot edit. Nothing can collide with the name, because a collision would
/// have to be with a column and there are none.
///
/// # The `where` clause is the CALLER's
///
/// What a comparison assumes is one list — that the database is a `Backend` at all, and that each
/// column's filter crosses into something for it — and the struct's clause is the whole of what
/// makes its field types well formed. The unit takes it rather than building it because the
/// refinement a `flatten` column states is a fact about the COLUMN's storage, which is a grammar
/// word's business and not this walk's. An impl asserting anything MORE would report a missing
/// crossing twice; one asserting less would not apply to the type it is written for — so the clause
/// is spliced verbatim into both.
pub fn comparison(
  header: &UnitHeader<'_>,
  database: &syn::Ident,
  crossings: &proc_macro2::TokenStream,
  columns: &[ComparisonColumn],
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
  let (vis, name, subject) = (&header.vis, &header.name, &header.subject);

  // A FUNCTION PARAMETER and a struct-expression field are both attribute positions, so the
  // positional `new` really loses an argument where its column is gone — and the crossing that calls
  // it loses the same one, both walks reading this one list.
  let members = columns.iter().map(|column| {
    let (member, gate) = (&column.member, &column.gate);
    quote!(#gate #member,)
  });
  let marker = columns
    .is_empty()
    .then(|| quote!(db: ::core::marker::PhantomData<fn() -> #database>,));

  let fields = columns.iter().map(|column| {
    let (member, held, gate) = (&column.member, &column.held, &column.gate);
    quote!(#gate #member: #held,)
  });
  let doc = header.doc(&format!(
    "A predicate over a {subject}'s columns, in the types this database stores — each field the \
     comparison its column's filter crosses into, so a query may ask for any shape that column's \
     operators offer rather than equality alone."
  ));
  let declaration = quote! {
    #[doc = #doc]
    #vis struct #name<#database>
    where
      #crossings
    {
      #(#fields)*
      #marker
    }
  };

  // A borrow rather than an `Option<&…>`: whether the column is compared at all is the kind's own
  // `is_empty`, so an outer `Option` would be a second encoding of a fact the value already
  // carries — and two encodings of one fact can disagree.
  let accessors = columns.iter().map(|column| {
    let (member, held, gate) = (&column.member, &column.held, &column.gate);
    let borrow = Member::Borrow.name(member);
    let doc = crate::emit::leading(&format!(
      "The predicate on the {}, in the type this database stores.",
      column.name
    ));
    quote! {
      #gate
      #[doc = #doc]
      #[inline]
      #vis const fn #borrow(&self) -> &#held {
        &self.#member
      }
    }
  });
  // Positional, in column order, and the only construction path there is: `Default` went with the
  // shape and the fields are private, so before this a comparison could be named and not built. It
  // takes one PREDICATE per column rather than one value, which is what the fields are; the empty
  // comparison is `Default` on each kind, passed in one at a time.
  let arguments = columns.iter().map(|column| {
    let (member, held, gate) = (&column.member, &column.held, &column.gate);
    quote!(#gate #member: #held,)
  });
  let marker_field = columns
    .is_empty()
    .then(|| quote!(db: ::core::marker::PhantomData,));
  let new_doc = crate::emit::leading(
    "Construct a predicate from one comparison per column, in the order this database stores them.",
  );
  let arity = crate::emit::wide_signature();

  (
    declaration,
    quote! {
      impl<#database> #name<#database>
      where
        #crossings
      {
        #[doc = #new_doc]
        #arity
        #[inline]
        #vis const fn new(#(#arguments)*) -> Self {
          Self { #(#members)* #marker_field }
        }

        #(#accessors)*
      }
    },
  )
}

/// The ORDER-BY face: one variant per orderable column, each CARRYING its direction, plus the
/// question every term answers whatever a database does with it.
///
/// # One value is one whole term
///
/// A query orders by a LIST of these, and the list is ordered by the GraphQL specification where an
/// input object's fields are not: `ORDER BY a, b` is not `ORDER BY b, a`, so the sequence is carried
/// by the one structure the spec calls ordered. Two parallel lists — `orderBy: [a, b],
/// orderDirection: [desc]` — is the shape this replaces, and the pairing is why: nothing in a type
/// system makes two lists the same length, so a mismatch is silently completed rather than refused.
///
/// The SHAPE is async-graphql's `OneofObject` — an enum of single-value tuple variants — and that
/// derive is the backend's, so it is not emitted here. What is emitted is the shape it takes.
///
/// An or-pattern in `direction` rather than an arm per variant, because every arm's body is the
/// binding and nothing else. The EMPTY case is a subject that stores no column at all: the enum is
/// uninhabited there and the empty `match` is what a value of it can be taken apart into.
pub fn order_by(
  header: &UnitHeader<'_>,
  direction_ty: &proc_macro2::TokenStream,
  columns: &[OrderColumn],
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
  let (vis, name, subject) = (&header.vis, &header.name, &header.subject);

  let variants = columns.iter().map(|column| {
    let (variant, gate) = (&column.variant, &column.gate);
    let doc = crate::emit::leading(&noted(
      &format!("Order by the {}, in the direction given.", column.name),
      column.note.as_deref(),
    ));
    quote! {
      #gate
      #[doc = #doc]
      #variant(#direction_ty),
    }
  });
  let doc = header.doc(&format!(
    "One ordering term over a {subject} — which column, and which way it runs."
  ));
  let declaration = quote! {
    #[doc = #doc]
    #[derive(
      ::core::fmt::Debug, ::core::clone::Clone,
      ::core::marker::Copy,
      ::core::cmp::PartialEq,
      ::core::cmp::Eq
    )]
    #vis enum #name {
      #(#variants)*
    }
  };

  // ONE ARM PER VARIANT where any is conditional, and an or-pattern where none is. A pattern
  // ALTERNATIVE is not an attribute position — `A(d) | #[cfg(…)] B(d)` is not Rust — so a variant the
  // build removed could not leave the alternation; an arm can carry the gate, and every arm's body is
  // the same binding either way.
  let conditional = columns.iter().any(|column| !column.gate.is_empty());
  let body = if columns.is_empty() {
    quote!(match self {})
  } else if conditional {
    let arms = columns.iter().map(|column| {
      let (variant, gate) = (&column.variant, &column.gate);
      quote!(#gate Self::#variant(direction) => direction,)
    });
    quote! {
      match self {
        #(#arms)*
      }
    }
  } else {
    let bindings = columns.iter().map(|column| {
      let variant = &column.variant;
      quote!(Self::#variant(direction))
    });
    quote! {
      match self {
        #(#bindings)|* => direction,
      }
    }
  };
  let doc = crate::emit::leading("Which way this term runs.");

  (
    declaration,
    quote! {
      #[doc = #doc]
      #[inline]
      #vis const fn direction(self) -> #direction_ty {
        #body
      }
    },
  )
}

/// The SEMANTIC IDENTITY method — the one input a cursor's SIGNATURE takes from a term.
///
/// It is the FIELD's own name — the name a per-database rename renames FROM — so a cursor minted
/// against one deployment's dialect is the same order's on the next: a rendered name would SPLIT one
/// order apart the moment either database renamed a column, and could ALIAS two orders together
/// where two renames crossed.
///
/// It is no longer the ONLY name a rename cannot move — the variant is one too, being built from the
/// same member — and that is a strengthening rather than a redundancy. What this still answers is
/// what a variant cannot: a VALUE a decoder generic over the term type can ask for, fold into a
/// signature and compare, where a variant is a type-level thing each subject spells for itself.
///
/// A method of its own rather than a part of [`order_by`], because its GATE is not the enum's: it is
/// the PAGE's, and a subject with no page to complete has nothing to do with it.
pub fn order_identity(
  vis: &syn::Visibility,
  term_name: &proc_macro2::TokenStream,
  columns: &[OrderColumn],
) -> proc_macro2::TokenStream {
  let identities = columns.iter().map(|column| {
    let (variant, identity, gate) = (&column.variant, &column.identity, &column.gate);
    quote!(#gate Self::#variant(_) => #term_name::new(#identity),)
  });
  let body = if columns.is_empty() {
    quote!(match self {})
  } else {
    quote! {
      match self {
        #(#identities)*
      }
    }
  };
  let doc = crate::emit::leading(
    "WHICH column this term names, under the name a per-database rename cannot move — what a \
     cursor's signature is folded from.",
  );
  quote! {
    #[doc = #doc]
    #[inline]
    #vis const fn identity(self) -> &'static #term_name {
      #body
    }
  }
}

/// THE SAME identity, as the wire's decode reads it: a PATH rather than one name, and answered
/// through a trait so a decoder generic over the term type can ask.
///
/// The arms are built from the same rows [`order_identity`]'s are, so the two cannot drift into
/// naming different columns. What differs is the SHAPE and the GATE. The shape is a path because
/// `cover.title` and `title` are two subjects and so are `cover.title` and `cover.duration` — every
/// emitted term is one segment today, and the path is what keeps the day a term reaches through a
/// relation from being a change to the uniqueness rule. The gate is none: `identity` is the PAGE's,
/// where a wire order is every order-capable subject's.
///
/// A `const` ITEM per arm, and not an inline `const { … }` block: the block does not make the borrow
/// inside it `'static` either, so both spellings without an item are `E0716`.
///
/// `match *self` rather than `match self`, and the EMPTY case is what forces it: the trait takes
/// `&self`, a reference is always considered INHABITED, and an empty match on one is `E0004` even
/// where the enum has no variant to write an arm for. Dereferencing puts the match back on the
/// uninhabited place. The populated arm follows the same spelling rather than the reverse, so a
/// subject storing one column and a subject storing none read alike; no arm binds, so nothing moves
/// out of the borrow.
pub fn order_subject_path(
  name: &syn::Ident,
  to_subject_path: &proc_macro2::TokenStream,
  subject_path: &proc_macro2::TokenStream,
  term_name: &proc_macro2::TokenStream,
  columns: &[OrderColumn],
) -> proc_macro2::TokenStream {
  let subjects = columns.iter().map(|column| {
    let (variant, identity, gate) = (&column.variant, &column.identity, &column.gate);
    quote! {
      #gate
      Self::#variant(_) => {
        const __INGRAPH_SUBJECT: #subject_path =
          #subject_path::new(&[#term_name::new(#identity)]);
        __INGRAPH_SUBJECT
      }
    }
  });
  let body = if columns.is_empty() {
    quote!(match *self {})
  } else {
    quote! {
      match *self {
        #(#subjects)*
      }
    }
  };
  quote! {
    #[automatically_derived]
    impl #to_subject_path for #name {
      #[inline]
      fn subject_path(&self) -> #subject_path {
        #body
      }
    }
  }
}

/// One column, as the comparison's LOWERING reads it.
pub struct LoweringColumn {
  /// The Rust member — layer 1, which no word moves.
  pub member: syn::Ident,
  /// The name this database RENDERS the column under — layer 3, which a per-database rename moves.
  ///
  /// Empty where no frame is pushed, which is the one state that has no rendered name to carry: see
  /// [`flatten`](Self::flatten).
  pub rendered: String,
  /// Whether this member is applied at the holder's OWN address rather than one segment below it.
  ///
  /// Two declarations reach it and their reasons are different. A `flatten` COLUMN lends no name, so
  /// its type's columns join the holder's namespace. A REVERSE RELATION position names no column of
  /// this row at all — only the child's foreign key and this row's id, both known without it — so
  /// the address it is handed goes unread and a frame below it would be a segment nothing renders.
  ///
  /// One flag rather than two, because what the emission does with it is one thing: not pushing a
  /// frame. [`unframed`](Self::unframed) is the second reason's own door, so a reader of a call site
  /// sees which of the two it is.
  pub flatten: bool,
  /// The qualified path this member's lowering is reached through — `None` for the
  /// `ComplexComparison<Db>` every column takes.
  ///
  /// A RELATION member takes the other door, and the reason is the wall its own crossing note
  /// records: its type is a projection through `ToRelatedComparison`, and a `where` clause saying
  /// that projection lowers resolves through the impl that defines it, demanding of a generic `Db`
  /// what only a concrete one can give. `ToLoweredRelatedComparison` carries the rendering as
  /// METHODS over the FILTER, so the call names no projection and the clause names no dialect.
  ///
  /// A `TokenStream` rather than a flag, because the path carries the position's own far side —
  /// `<RelatedFilter<…> as ToLoweredRelatedComparison<…, DB>>` — which only the caller knows.
  pub through: Option<proc_macro2::TokenStream>,
  /// The CONDITION the column is declared under, as the attribute to prefix onto every artifact it
  /// mints here — empty for a column that wrote none, and for every unit whose front end has no
  /// condition seat.
  ///
  /// Carried on the ROW rather than looked up, because a unit is shared: the record family knows a
  /// field's `#[cfg]` and the interface and standalone families have no such word, so the fact
  /// arrives with the column exactly as its filter and its noun do. See
  /// [`Condition`](crate::model::Condition).
  pub gate: proc_macro2::TokenStream,
}

impl LoweringColumn {
  /// A member applied at the address it is handed, under no name of its own — what a REVERSE
  /// RELATION position is.
  #[must_use]
  pub fn unframed(member: syn::Ident, through: proc_macro2::TokenStream) -> Self {
    Self {
      member,
      rendered: String::new(),
      flatten: true,
      through: Some(through),
      gate: proc_macro2::TokenStream::new(),
    }
  }

  /// A member applied one segment below the address, under the name `rendered` — an ordinary COLUMN,
  /// or a forward relation position, which renders at the FOREIGN KEY's own address.
  #[must_use]
  pub fn framed(
    member: syn::Ident,
    rendered: String,
    through: Option<proc_macro2::TokenStream>,
  ) -> Self {
    Self {
      member,
      rendered,
      flatten: false,
      through,
      gate: proc_macro2::TokenStream::new(),
    }
  }

  /// The same row, carrying the CONDITION its column is declared under.
  #[must_use]
  pub fn with_gate(mut self, gate: proc_macro2::TokenStream) -> Self {
    self.gate = gate;
    self
  }
}

/// The framework seats the LOWERING spells, resolved by the caller through its own shelf.
pub struct LoweringSeats {
  /// `comparison::Backend`.
  pub backend: proc_macro2::TokenStream,
  /// `comparison::ComplexComparison`.
  pub complex: proc_macro2::TokenStream,
  /// `comparison::Frame`.
  pub frame: proc_macro2::TokenStream,
  /// `comparison::At`.
  pub at: proc_macro2::TokenStream,
  /// `field::FieldName`.
  pub field_name: proc_macro2::TokenStream,
}

/// The comparison's LOWERING: `ComplexComparison`, threading one accumulator through the columns.
///
/// # It needs no predicate the struct did not already carry
///
/// Each field is held at `<F as ToDatabaseComparison<V, Db>>::Comparison`, and the map's ITEM BOUND
/// — `type Comparison: ComplexComparison<Db>` — is what says such a field lowers. So the `where`
/// clause is the struct's own, spliced verbatim, and nothing here adds to it.
///
/// # The two names of one column, a layer apart
///
/// The MEMBER this reads is the field's and no word moves it; the FRAME pushed below is the string
/// this database RENDERS, which a per-database rename is exactly what moves. A `flatten` column
/// pushes no frame at all — its own name is dropped, so its type's columns join the holder's
/// namespace.
///
/// A sum with no leading zero: `0 + x` is `clippy::identity_op`, which a consumer building under
/// `-D warnings` would see inside an expansion it cannot edit.
pub fn comparison_lowering(
  name: &syn::Ident,
  database: &syn::Ident,
  crossings: &proc_macro2::TokenStream,
  seats: &LoweringSeats,
  columns: &[LoweringColumn],
) -> proc_macro2::TokenStream {
  let LoweringSeats {
    backend,
    complex,
    frame,
    at,
    field_name,
  } = seats;

  // The DOOR each member's lowering is reached through: `ComplexComparison<Db>` for a column, and the
  // relation map's refinement for a position — see [`LoweringColumn::through`] for the wall that
  // second door exists to walk around.
  let door = |column: &LoweringColumn| {
    column
      .through
      .clone()
      .unwrap_or_else(|| quote!(#complex::<#database>))
  };
  // An OPERAND of a binary expression is not an attribute position — `a + #[cfg(…)] b` is not Rust
  // — so where any column is conditional the sum is ACCUMULATED in statements a gate can sit on. The
  // `+` chain stays wherever nothing can be absent, which is every declaration that wrote no
  // condition.
  let conditional = columns.iter().any(|column| !column.gate.is_empty());
  let conjuncts = if columns.is_empty() {
    quote!(0)
  } else if conditional {
    let counts = columns.iter().map(|column| {
      let (member, door, gate) = (&column.member, door(column), &column.gate);
      quote! {
        #gate
        {
          __ingraph_conjuncts += #door::conjuncts(&self.#member);
        }
      }
    });
    quote! {
      {
        let mut __ingraph_conjuncts = 0usize;
        #(#counts)*
        __ingraph_conjuncts
      }
    }
  } else {
    let counts = columns.iter().map(|column| {
      let (member, door) = (&column.member, door(column));
      quote!(#door::conjuncts(&self.#member))
    });
    quote!(#(#counts)+*)
  };

  let parts = columns.iter().map(|column| {
    let (member, rendered, door) = (&column.member, &column.rendered, door(column));
    let gate = &column.gate;
    if column.flatten {
      return quote! {
        #gate
        let __ingraph_builder = #door::apply(
          &self.#member,
          __ingraph_at,
          __ingraph_builder,
        )?;
      };
    }
    quote! {
      #gate
      let __ingraph_frame = #at::frame(__ingraph_at, #field_name::new(#rendered));
      #gate
      let __ingraph_builder = #door::apply(
        &self.#member,
        #frame::at(&__ingraph_frame),
        __ingraph_builder,
      )?;
    }
  });
  let at_binding = if columns.is_empty() {
    quote!(_)
  } else {
    quote!(__ingraph_at)
  };

  let conjuncts_doc = crate::emit::leading(
    "How many conjuncts this predicate renders — the sum over its columns, since each is a \
     comparison of its own.",
  );
  let apply_doc = crate::emit::leading(
    "Render every column's conjuncts into `builder`, each at the same row and one segment below the \
     address this predicate was applied at.",
  );
  quote! {
    #[automatically_derived]
    impl<#database> #complex<#database> for #name<#database>
    where
      #crossings
    {
      #[doc = #conjuncts_doc]
      #[inline]
      fn conjuncts(&self) -> ::core::primitive::usize {
        #conjuncts
      }

      #[doc = #apply_doc]
      fn apply<'q>(
        &'q self,
        #at_binding: #at<'_>,
        __ingraph_builder: <#database as #backend>::Builder<'q>,
      ) -> ::core::result::Result<
        <#database as #backend>::Builder<'q>,
        <#database as #backend>::Error,
      > {
        #(#parts)*
        ::core::result::Result::Ok(__ingraph_builder)
      }
    }
  }
}