ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Validating a struct whose fields are an application's nodes into the graph model the emitter
//! consumes.
//!
//! The smallest front end in this crate, and deliberately so: a graph declares no storage and no
//! faces. Its content is the LIST, and the three entries beside it are each about the list or about
//! what running it means — where `ingraph` lives, what the ENGINE WORDS its members wrote mean
//! (`engines(…)`), and where its retirees and its current pointers are written down (`retired(…)`
//! and `generations(…)`, the two entries that name a DURABLE thing at all). A fifth, `dedup(…)`,
//! RETIRED with the fused doors it chose the join for: see [`DEDUP_IS_A_RECIPES`].
//!
//! # What this pass can see, and what it cannot
//!
//! It sees TOKENS. So it enforces the shape — a struct, with named fields, with no generic parameter
//! — the one list rule a token comparison can decide (no type written twice), the RESERVED mount,
//! and the words a field takes. Whether a field's type is a legal NODE is not a token question at
//! all, and it is not left unchecked either: the emitted walk states one storage-description
//! predicate per field, so a field that is not a node is `E0277` where the graph is written, carrying
//! that trait's own sentence. A resource field is the same division one tier over — the catalog walk
//! states the citizenship predicate, so a `#[ingraph(resource)]` field whose type never declared
//! itself one is `E0277` at the root.
//!
//! # ONE list, two kinds, and `resources` belongs to neither
//!
//! Nodes and resources are the same struct's fields, told apart by one word — see
//! [`resource`](self::resource) for its three spellings, and for the second word a NODE field takes:
//! `query`, which is the ROOT QUERY's membership. A macro cannot ask whether a type implements
//! anything, so which members have root fields is read off THIS declaration and checked by the
//! projection the emitted fold writes. The word `resources` is RESERVED at that
//! shared namespace, because the emitted options spine groups every resource's section under a
//! `resources` key: a member mounted there would be a second meaning for it, so the derive refuses
//! one and says why. `registry` is reserved beside it, for the graph-level registry-timing seat the
//! spine grows on every root — see [`reserve_the_registry_seat`] — and `retired` beside that, for
//! the ledger's own connection, which the spine grows only where a root wrote `retired(<engine>)`
//! and whose NAME is held whether it did or not: see [`reserve_the_retired_seat`]. `generations` is
//! the fourth, on the same conditional-field/unconditional-name posture: see
//! [`reserve_the_generations_seat`].
//!
//! That division is the three-author wall showing through. This derive cannot read a member's own
//! declaration, so it cannot know what the member subscribes to and does not pretend to —
//! subscribe-completeness is an assembly check, named as one.

use std::collections::BTreeMap;

use ingraph_codegen::graph::{
  FusedMember, GenerationsSeat, GraphModel, InterfaceMount, OriginMount, RetiredLedger,
};

use ingraph_codegen::{
  catalog::{RESERVED_MOUNT, ResourceField},
  engine::{EngineBinding, EngineKind},
  model::DatabaseKind,
  options::{RESERVED_GENERATIONS_MOUNT, RESERVED_REGISTRY_MOUNT, RESERVED_RETIRED_MOUNT},
};

use crate::{
  attribute::{self, named},
  errors::Errors,
  value,
};

mod resource;

#[cfg(test)]
mod dedup;
#[cfg(test)]
mod engines;
#[cfg(test)]
mod tests;

/// Validate a decorated struct into the model the emitter consumes.
///
/// # Errors
/// A [`syn::Error`] carrying EVERY rule the pass could still see violated, each spanned at the token
/// that violated it, so one compile reports the whole declaration's problems.
pub(crate) fn parse(
  input: &syn::DeriveInput,
  arguments: &[syn::Attribute],
) -> syn::Result<GraphModel> {
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let Options {
    krate,
    engines,
    retired,
    generations,
  } = options(arguments, &mut errors);
  concrete(&input.generics, &mut errors);

  let Members {
    nodes,
    mounts,
    queried,
    interfaces,
    fused,
    origins,
    resources,
  } = match members(input, &mut errors) {
    Ok(list) => list,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  an_origin_needs_a_node_to_feed(&origins, &nodes, &mut errors);

  errors.into_result(GraphModel {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    vis: input.vis.clone(),
    name: input.ident.clone(),
    nodes,
    mounts,
    queried,
    interfaces,
    fused,
    origins,
    resources,
    engines,
    retired,
    generations,
  })
}

/// What a root's own attribute says: where `ingraph` lives, what its ENGINE WORDS mean, and where
/// its retirees and its current pointers are written down.
///
/// A struct rather than the tuple it grew out of, on [`Members`]'s own reasoning one function over:
/// four unrelated things read off one walk is where a caller starts binding the wrong one.
struct Options {
  /// `crate = "…"`, or [`None`] for `::ingraph`.
  krate: Option<syn::Path>,
  /// `engines(<word> = "path::To::Engine")`, in the order they were written.
  engines: Vec<EngineBinding>,
  /// `retired(<engine>)`, or [`None`] where the root declared no ledger.
  retired: Option<RetiredLedger>,
  /// `generations(<engine>)`, or [`None`] where the root declared no seat.
  generations: Option<GenerationsSeat>,
}

/// **THE ONE HALF OF *AN ORIGIN NOBODY LISTENS TO* THIS PASS CAN DECIDE** — a root that mounts an
/// origin and no node at all.
///
/// An origin's out-edge IS its feed, and the only tier that can declare an upstream is the NODE
/// tier: an interface is a contract, a resource is a citizen the launch hands out, a retrieving
/// declaration owns a corpus, and none of the three implements `Declared`. So a root with origins
/// and an empty node list has an origin whose consumer could not exist — which is decidable from
/// the field list alone, and is therefore said HERE rather than three walks later.
///
/// # The OTHER half is NOT static, and the reason is worth writing down
///
/// Whether a root that DOES mount nodes has one listening to this origin is a question about that
/// node's own `subscribe(…)`, which lives in another declaration's tokens — the three-author wall.
/// Nor can the emission ask at compile time: the join runs on `TypeId`, `Declared::UPSTREAMS` is a
/// `&'static [Upstream]` of them, and comparing two `TypeId`s in a `const` is not stable
/// (`const_cmp` / `const_trait_impl`), so no assertion this pass could emit can count an origin's
/// consumers. It stays a LAUNCH refusal — `Refusal::PureLeaf` for none, `Refusal::SplitOrigin` for
/// two, `Refusal::UnbridgedOrigin` for one that listens the wrong way — said where the identities
/// have actually been joined.
///
/// One row per origin field rather than one for the root, because each field is a thing an author
/// fixes and there may be several.
fn an_origin_needs_a_node_to_feed(
  origins: &[OriginMount],
  nodes: &[syn::Type],
  errors: &mut Errors,
) {
  if origins.is_empty() || !nodes.is_empty() {
    return;
  }
  for origin in origins {
    errors.push(syn::Error::new_spanned(
      &origin.ty,
      "this origin can have no consumer — a root mounting NO NODE has nothing that could subscribe \
       to it, and an origin's one out-edge IS its feed. Only the node tier declares upstreams: an \
       `interface` is a contract, a `resource` is a citizen the launch hands out, and a `fuse` \
       member owns a corpus. Add the node that names this origin in its own \
       `subscribe(upstream(node = \"…\"))`, or take the origin off a root that runs nothing",
    ));
  }
}

/// Walk the struct-level attribute: where `ingraph` lives, which ENGINE WORDS this program binds,
/// and where its RETIREES and its CURRENT POINTERS are written down.
///
/// Three entries, and the last two are the reason a graph root has a grammar at all beyond the
/// first.
///
/// A declaration names its engines by WORD, and a word is a NAME — so somewhere has to say what the
/// name means, and the root is the one declaration that knows: it is the deployment's whole catalog
/// already, the same list the resources are read off.
///
/// `retired(<engine>)` is on the root for the same reason and a second one. A retirement is a fact
/// about a ROOT KEY rather than about any member, so no member's declaration could carry it; and the
/// ledger is ONE per deployment, which is a statement only the one declaration that sees the whole
/// list can make. It names an ENGINE and nothing else — see [`retired_engine`], where the division
/// against the `[retired]` section is argued.
///
/// `generations(<engine>)` is `retired(…)`'s sibling and is on the root for both of those reasons
/// again: a run closes over a ROOT KEY rather than over any member, and the pointer table is ONE per
/// deployment. It names an ENGINE and nothing else — see [`generations_engine`], where the division
/// against the `[generations]` section is argued, and where the vocabulary being one word SHORTER
/// than this one's is argued too.
///
/// `dedup(…)` used to be a fifth entry and is RETIRED here — see [`DEDUP_IS_A_RECIPES`], which is
/// what a declaration that still writes it is told.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
  let mut krate: Option<syn::Path> = None;
  let mut engines: Vec<EngineBinding> = Vec::new();
  let mut block: Option<syn::Path> = None;
  let mut retired: Option<RetiredLedger> = None;
  let mut ledger: Option<syn::Path> = None;
  let mut generations: Option<GenerationsSeat> = None;
  let mut seat: Option<syn::Path> = None;

  attribute::walk(attrs, errors, |meta, errors| {
    // `crate` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
    // arrives here as an ordinary one-segment path.
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(
        &meta,
        "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
      ) {
        Ok(path) => {
          if krate.replace(path).is_some() {
            errors.push(syn::Error::new_spanned(
              &meta.path,
              "`crate` is declared more than once — one declaration names one crate",
            ));
          }
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    if meta.path.is_ident(ENGINES) {
      return attribute::block(
        &meta,
        &mut block,
        "`engines(…)` is declared more than once — one root, one engine table, and two blocks would \
         be two places for one word to be bound",
        errors,
        |inner, errors| {
          engine_binding(&inner, &mut engines, errors);
          Ok(())
        },
      );
    }

    if meta.path.is_ident(RETIRED) {
      return attribute::block(
        &meta,
        &mut ledger,
        "`retired(…)` is declared more than once — one root, one ledger, and two blocks would be \
         two places a deployment's retirees could be written down",
        errors,
        |inner, errors| {
          retired_engine(&inner, &mut retired, errors);
          Ok(())
        },
      );
    }

    if meta.path.is_ident(GENERATIONS) {
      return attribute::block(
        &meta,
        &mut seat,
        "`generations(…)` is declared more than once — one root, one seat, and two blocks would be \
         two places a deployment's current pointers could be written down",
        errors,
        |inner, errors| {
          generations_engine(&inner, &mut generations, errors);
          Ok(())
        },
      );
    }

    // THE RETIRED WORD, refused by name rather than as an unknown one: a reader who wrote it wrote
    // something that used to mean a real thing here, and what they are owed is where it went.
    if meta.path.is_ident(DEDUP) {
      errors.push(syn::Error::new_spanned(&meta.path, DEDUP_IS_A_RECIPES));
      attribute::skip_entry(&meta);
      return Ok(());
    }

    errors.push(attribute::unknown(
      &meta,
      "unknown entry in `#[ingraph(…)]` on a graph root — it takes `crate = \"…\"`, \
       `engines(<word> = \"path::To::Engine\")`, `retired(<engine>)` and `generations(<engine>)`, \
       and nothing else: a graph's content is the list its fields are, plus what the words on those \
       fields' declarations MEAN and where its retirees and its current pointers are written down",
      // `dedup` IS NOT A CANDIDATE, which is the retirement rather than an oversight: it has its own
      // sentence above, and offering it as a near miss would point a reader at a word that no longer
      // decides anything here.
      &["crate", ENGINES, RETIRED, GENERATIONS],
    ));
    Ok(())
  });

  Options {
    krate,
    engines,
    retired,
    generations,
  }
}

/// The word `engines(…)` is spelled with, once.
const ENGINES: &str = "engines";

/// The word `retired(…)` is spelled with, once.
const RETIRED: &str = "retired";

/// The word `generations(…)` is spelled with, once.
const GENERATIONS: &str = "generations";

/// The word `dedup(…)` is spelled with, once — the tier's own spelling, one grain up.
const DEDUP: &str = "dedup";

/// THE ENGINE INSIDE `retired(…)`: a bare word naming one of the four the framework builds.
///
/// # It takes NO options, and the refusal says where they went
///
/// `retired(sqlite(path = "…"))` is not a spelling. Which engine a ledger runs on decides what the
/// program COMPILES — a driver, a dialect, a feature — and is therefore the declaration's; WHERE on
/// that engine is a path on somebody's disk or a host in somebody's network, which is the
/// deployment's and reaches the framework through the `[retired]` section. That is the same division
/// `#[ingraph::resource(tantivy)]` already refuses by name one declaration over, and for the same
/// reason.
///
/// # A word this crate does not ship is refused with the four it does
///
/// The vocabulary is CLOSED, unlike `engines(…)`'s binding position one entry up, and the two
/// closures differ for a reason: an engine WORD is a name a deployment mints for a type it wrote,
/// while this names a store the framework builds out of a DSN with no type from anybody. A store of
/// a deployment's own is not a word here at all — it is `RetiredStore` implemented and handed to
/// `Keeper::new`.
fn retired_engine(
  inner: &syn::meta::ParseNestedMeta<'_>,
  retired: &mut Option<RetiredLedger>,
  errors: &mut Errors,
) {
  let Some(word) = inner.path.get_ident().map(ToString::to_string) else {
    errors.push(attribute::unknown(
      inner,
      "the engine inside `retired(…)` is ONE word — `retired(sqlite)` — and a path with several \
       segments is not one",
      &RETIRED_ENGINES,
    ));
    return;
  };

  let Some(engine) = DatabaseKind::ALL
    .into_iter()
    .find(|kind| kind.as_str() == word)
  else {
    let refusal = format!(
      "`{word}` is not an engine the retired ledger builds — it takes `sqlite`, `postgres`, \
       `mysql` or `mongo`, the same four words a record's own `persist(…)` takes. A key-value store \
       and a store of your own are FUTURE words on the same seam: implement \
       `ingraph::RetiredStore` and hand it to `Keeper::new`, which needs no word here at all"
    );
    errors.push(attribute::unknown(inner, &refusal, &RETIRED_ENGINES));
    attribute::skip_entry(inner);
    return;
  };

  if attribute::has_value(inner) || attribute::has_block(inner) {
    errors.push(attribute::named(
      inner,
      format!(
        "`{word}` is a bare word — it names WHICH engine this root's retired ledger runs on, and \
         WHERE on that engine is the deployment's, which reaches the framework through the \
         `[retired]` section (`dsn = \"…\"`) rather than through this attribute"
      ),
    ));
    attribute::skip_entry(inner);
    return;
  }

  // FILL ONCE, and the FIRST word is kept — `attribute::set_once`'s own rule, spelled here because
  // the message is this seat's: the rest of the pass reads a settled declaration rather than
  // whichever engine happened to be written last.
  if let Some(first) = retired.as_ref() {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`retired(…)` already named `{first}` — one root, one ledger. A deployment's retirees are \
         the truth about which root keys are out, and two engines holding that truth is two \
         answers to one question",
        first = first.engine.as_str(),
      ),
    ));
    return;
  }
  *retired = Some(RetiredLedger { engine });
}

/// The four words `retired(…)` takes, for a near-miss suggestion.
const RETIRED_ENGINES: [&str; 4] = ["sqlite", "postgres", "mysql", "mongo"];

/// The three words `generations(…)` takes, for a near-miss suggestion — [`RETIRED_ENGINES`] minus
/// the document store, and see [`generations_engine`] for why that one is missing.
const GENERATIONS_ENGINES: [&str; 3] = ["sqlite", "postgres", "mysql"];

/// THE ENGINE INSIDE `generations(…)`: a bare word naming one of the three the framework builds.
///
/// [`retired_engine`]'s sibling, and everything that door argues holds here — the word decides what
/// the program COMPILES so it is the declaration's, and WHERE on that engine is the deployment's.
/// Two things differ.
///
/// # The section it sends the knobs to has TWO of them
///
/// `generations(sqlite(path = "…"))` is not a spelling, and neither is a retention depth written
/// here. WHERE the pointers live and HOW DEEP the history goes are both a deployment's, and both
/// reach the framework through the `[generations]` section — `dsn` and `keep`.
///
/// # `mongo` IS REFUSED BY NAME, and the vocabulary is one word SHORTER than `retired(…)`'s
///
/// A pointer is a row anywhere; the retention duty is an anchored `DELETE` whose bound is a
/// correlated subquery over a table's own distinct runs, and that is a SQL shape. A document store
/// sweeps the same closure by MEMBERSHIP instead, which is `ingraph::GenerationsStore` implemented
/// elsewhere and handed to `Curator::new` rather than a fourth arm here. The word is a real engine
/// one entry up, so a reader who wrote it is owed that reason rather than a near-miss list.
fn generations_engine(
  inner: &syn::meta::ParseNestedMeta<'_>,
  generations: &mut Option<GenerationsSeat>,
  errors: &mut Errors,
) {
  let Some(word) = inner.path.get_ident().map(ToString::to_string) else {
    errors.push(attribute::unknown(
      inner,
      "the engine inside `generations(…)` is ONE word — `generations(sqlite)` — and a path with \
       several segments is not one",
      &GENERATIONS_ENGINES,
    ));
    return;
  };

  let engine = DatabaseKind::ALL
    .into_iter()
    .find(|kind| kind.as_str() == word)
    .filter(|kind| kind.generations_arm().is_some());
  let Some(engine) = engine else {
    let refusal = format!(
      "`{word}` is not an engine the generations seat builds — it takes `sqlite`, `postgres` or \
       `mysql`. A document store is not a word here: its retention duty is a MEMBERSHIP sweep \
       rather than the anchored `DELETE` these three share, so it arrives as \
       `ingraph::GenerationsStore` implemented and handed to `Curator::new`"
    );
    errors.push(attribute::unknown(inner, &refusal, &GENERATIONS_ENGINES));
    attribute::skip_entry(inner);
    return;
  };

  if attribute::has_value(inner) || attribute::has_block(inner) {
    errors.push(attribute::named(
      inner,
      format!(
        "`{word}` is a bare word — it names WHICH engine this root's current pointers run on, and \
         WHERE on that engine and HOW DEEP its history goes are the deployment's, which reach the \
         framework through the `[generations]` section (`dsn = \"…\"`, `keep = <n>`) rather than \
         through this attribute"
      ),
    ));
    attribute::skip_entry(inner);
    return;
  }

  // FILL ONCE, and the FIRST word is kept — [`retired_engine`]'s own rule one door up, spelled
  // again because the message is this seat's.
  if let Some(first) = generations.as_ref() {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`generations(…)` already named `{first}` — one root, one seat. The pointer table is the \
         truth about which generation each closure is reading, and two engines holding that truth \
         is two answers to one question",
        first = first.engine.as_str(),
      ),
    ));
    return;
  }
  *generations = Some(GenerationsSeat { engine });
}

/// **THE RETIREMENT SENTENCE** the root's `dedup(…)` earns, and where the word went.
///
/// The word chose the JOIN a root's fused doors ran — `HashJoin` or `EqJoin`, and the `where` row
/// those doors stated about the root parameter. Those doors are `#[ingraph::search]`'s now: a recipe
/// LISTS the members it fuses and carries its own `dedup(…)`, read where the fold is minted. So the
/// root's copy chose nothing at all, and an unpublished word that decides nothing is deleted rather
/// than deprecated.
///
/// Refused BY NAME rather than swallowed by the roster: a reader who wrote it wrote something that
/// used to mean a real thing here, and a bare *unknown entry* would send them looking for a typo.
const DEDUP_IS_A_RECIPES: &str = "`dedup(…)` is a RECIPE's word — it chooses the join a FUSED read tells two roots apart with, and \
   a root mints no fused door. Write it on the declaration that does: \
   `#[ingraph::search(dedup(hash))]`, beside the members that recipe fuses. A root's own words are \
   `crate = \"…\"` and `engines(<word> = \"path::To::Engine\")`";

/// ONE entry inside `engines(…)`: a word, and the concrete engine it names.
///
/// REFER-QUOTED, as every word in this grammar that points at something written elsewhere is: the
/// engine is another crate's type, so naming it here is a reference, and a reference is written in a
/// string literal. The re-parse RESPANS onto that literal, so a path naming nothing is `E0412` where
/// its author wrote it.
fn engine_binding(
  inner: &syn::meta::ParseNestedMeta<'_>,
  engines: &mut Vec<EngineBinding>,
  errors: &mut Errors,
) {
  let Some(word) = inner.path.get_ident().cloned() else {
    errors.push(attribute::unknown(
      inner,
      "an engine word is ONE word — the entry's own name is the word a declaration writes on a \
       field — and a path with several segments is not one. The PATH goes on the right: \
       `<word> = \"path::To::Engine\"`",
      // THE BINDING POSITION, and it is OPEN by construction: the word an entry names here is the
      // one this deployment is MINTING, so there is no vocabulary for it to be near. A word this
      // crate ships is refused by name below, which is the only closed half this position has.
      &[],
    ));
    return;
  };

  // A word this crate SHIPS is bound already, under its own feature, exactly as `postgres` is one
  // family over. Rebinding it would give one word two meanings inside one program, which is the
  // collision the table exists to make impossible — so it is refused rather than allowed to win.
  if let Some(shipped) = EngineKind::of(&word) {
    errors.push(named(
      inner,
      format!(
        "`{word}` is an engine `ingraph` ships, so it BINDS ITSELF — under `feature = \"{word}\"`, \
         the way a database word does. A deployment says only whether it compiled it, and rebinding \
         it here would give one word two meanings in one program. A third-party engine takes a word \
         of its own, and `{word}` holds {serves}",
        serves = shipped.serves().plural(),
      ),
    ));
    return;
  }

  if let Some(first) = engines.iter().find(|bound| bound.word == word) {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{first}` is bound more than once — one word names one engine, and a second entry would \
         leave every field that wrote the word pointing at whichever binding the reader reached \
         first",
        first = first.word,
      ),
    ));
    attribute::skip_entry(inner);
    return;
  }

  match value::parse_literal::<syn::Path>(
    inner,
    &format!(
      "`{word} = \"…\"` names the engine this word means, as a type path in a string literal — a \
       word that points at something written elsewhere is quoted"
    ),
  ) {
    Ok(engine) => engines.push(EngineBinding { word, engine }),
    Err(e) => {
      // Swallow what the entry carried, for `attribute::unknown`'s reason: one mistake should cost
      // one error rather than one plus a parse failure at the token after it.
      errors.push(e);
      attribute::skip_entry(inner);
    }
  }
}

/// A graph root carries no generic parameter.
///
/// Its fields are the NODES, and a parameter is not a node until it is substituted: the list would
/// name a different graph per instantiation, and the walk a caller drives is one walk over one
/// list.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  if generics.params.is_empty() {
    return;
  }
  errors.push(syn::Error::new_spanned(
    &generics.params,
    "a graph root takes no generic parameter — its fields ARE the node list, and a parameter is \
     not a node until it is substituted, so a generic root would name a different graph per \
     instantiation",
  ));
}

/// What a graph's field list yields — one list per TIER, and the query fold's membership beside the
/// tier it is read off.
///
/// A struct rather than the tuple it grew out of: the interface tier is the third list and the
/// fourth positional element of a tuple is where a caller starts binding the wrong one.
struct Members {
  /// The node TYPES the storage walk hands over.
  nodes: Vec<syn::Type>,
  /// The node mount NAMES, in the same order.
  mounts: Vec<syn::Ident>,
  /// The nodes whose ROOT FIELDS the query fold projects.
  queried: Vec<syn::Type>,
  /// The INTERFACES, each with its own mount name and its own `query` word.
  interfaces: Vec<InterfaceMount>,
  /// The RETRIEVING members, which the slot walk visits and the launch builds.
  fused: Vec<FusedMember>,
  /// The ORIGINS, which the options spine sections and the launch mounts as heads.
  origins: Vec<OriginMount>,
  /// The RESOURCES read off the same list.
  resources: Vec<ResourceField>,
}

/// The two member lists, in the order the fields were written.
///
/// # Errors
/// A TERMINAL refusal where there is no list to read at all — the declaration is not a struct, or
/// carries no field, or names its fields positionally. Everything else is collected.
fn members(input: &syn::DeriveInput, errors: &mut Errors) -> Result<Members, syn::Error> {
  let syn::Data::Struct(data) = &input.data else {
    return Err(syn::Error::new_spanned(
      &input.ident,
      "a graph root is a STRUCT whose fields are the nodes — an enum declares alternatives, and \
       a graph holds all of its nodes at once",
    ));
  };

  let syn::Fields::Named(fields) = &data.fields else {
    return Err(syn::Error::new_spanned(
      &input.ident,
      "a graph root's fields are NAMED — a field's name is what the query surface mounts the \
       node under, so a positional one would leave the mount unnamed",
    ));
  };

  if fields.named.is_empty() {
    return Err(syn::Error::new_spanned(
      &input.ident,
      "a graph root with no field declares no node, and a walk over nothing is a walk nobody \
       needs",
    ));
  }

  // Two spellings of one type are two DECLARED types here — the emitter holds tokens, so
  // `media::Video` beside a `use`d `Video` is not a collision this pass can see. That is the same
  // wall `Related`'s own note records one crate over, and the cost of missing it is a table created
  // twice by a create that is idempotent anyway.
  let mut seen: BTreeMap<String, (&syn::Field, bool)> = BTreeMap::new();
  let mut nodes = Vec::with_capacity(fields.named.len());
  let mut mounts = Vec::with_capacity(fields.named.len());
  let mut queried = Vec::new();
  let mut interfaces = Vec::new();
  let mut fused = Vec::new();
  let mut origins = Vec::new();
  let mut resources = Vec::new();
  for field in &fields.named {
    reserve_the_grouping_key(field, errors);
    reserve_the_registry_seat(field, errors);
    reserve_the_retired_seat(field, errors);
    reserve_the_generations_seat(field, errors);
    let resource::Words {
      resource: declared,
      interface,
      query,
      fuse,
      origin,
    } = resource::words(field, errors);
    let spelling = quote::ToTokens::to_token_stream(&field.ty).to_string();
    if let Some((first, was_resource)) = seen.insert(spelling, (field, declared.is_some())) {
      let first = first
        .ident
        .as_ref()
        .map_or_else(String::new, ToString::to_string);
      // A collision involving a RESOURCE gets its own sentence, the node one's advice being about
      // storage. The pair where neither is a resource keeps the wording it has always had.
      let message = if was_resource || declared.is_some() {
        format!(
          "this type is already in the graph, as `{first}` — a root lists each member ONCE, and \
           two fields naming one resource would declare it twice under two mounts"
        )
      } else {
        format!(
          "this node is already in the graph, as `{first}` — a graph lists each node ONCE, \
           and a second field naming one mounts the same storage under two names"
        )
      };
      errors.push(syn::Error::new_spanned(&field.ty, message));
      continue;
    }
    let Some(mount) = field.ident.clone() else {
      continue;
    };
    match declared {
      Some(resource::Declaration { source, teardown }) => resources.push(ResourceField {
        mount,
        ty: field.ty.clone(),
        source,
        teardown,
      }),
      // The INTERFACE tier, which is a list of its own and never the node one: the walk, the create
      // pass and the options spine are each written about a member an interface is not.
      None if interface => interfaces.push(InterfaceMount {
        mount,
        ty: field.ty.clone(),
        queried: query,
      }),
      // The INDEX tier, which is a list of its own and never the node one — a retrieving
      // declaration implements neither `Declared` nor `AsyncConstructor`, so the three walks a node
      // joins are each written about a member an index is not.
      //
      // IT CARRIES THE MOUNT WORD TOO, which is the root query-surface gap closed: a retrieving
      // declaration mints a query unit and binds it at the same seat an interface does, and until
      // this line the word was read on such a field and thrown away.
      None if fuse => fused.push(FusedMember {
        mount,
        ty: field.ty.clone(),
        queried: query,
      }),
      // The ORIGIN TIER, which is a list of its own for the reason the two above are: an origin
      // implements `DeclaredOrigin` rather than `Declared`, so the storage walk, the root query and
      // the create pass's node predicates are each written about a member an origin is not. What it
      // joins instead is the options spine and the launch's own five origin lines.
      None if origin => origins.push(OriginMount {
        mount,
        ty: field.ty.clone(),
      }),
      None => {
        if query {
          queried.push(field.ty.clone());
        }
        nodes.push(field.ty.clone());
        mounts.push(mount);
      }
    }
  }
  Ok(Members {
    nodes,
    mounts,
    queried,
    interfaces,
    fused,
    origins,
    resources,
  })
}

/// `resources` is the DOCUMENT's grouping key, so no member may be mounted under it.
///
/// The refusal is the derive's rather than the deserializer's because the derive is the half that
/// knows WHY: the emitted spine carries one `resources` field holding every resource's section, and
/// a member of that name would be a second meaning for one key. A reader told only that a field
/// collided would have to reconstruct that.
fn reserve_the_grouping_key(field: &syn::Field, errors: &mut Errors) {
  let Some(mount) = &field.ident else {
    return;
  };
  if mount != RESERVED_MOUNT {
    return;
  }
  errors.push(syn::Error::new_spanned(
    mount,
    format!(
      "`{RESERVED_MOUNT}` is a RESERVED mount on a graph root — the emitted options spine groups \
       every resource's section under it (`[{RESERVED_MOUNT}.<field>]`), so a member of that name \
       would be a second meaning for one document key; rename the field"
    ),
  ));
}

/// `registry` is the DOCUMENT's own registry-timing key, so no member may be mounted under it.
///
/// [`reserve_the_grouping_key`]'s sibling, and the same rule one seat over: the emitted spine
/// carries one `registry` field holding the root-key registry's own timing — `[registry]`'s
/// defaults and its per-family overrides — and a member of that name would be a second meaning for
/// it. Unlike `resources` the seat is on EVERY root, so the refusal applies whether or not this
/// declaration would otherwise have grown one.
fn reserve_the_registry_seat(field: &syn::Field, errors: &mut Errors) {
  let Some(mount) = &field.ident else {
    return;
  };
  if mount != RESERVED_REGISTRY_MOUNT {
    return;
  }
  errors.push(syn::Error::new_spanned(
    mount,
    format!(
      "`{RESERVED_REGISTRY_MOUNT}` is a RESERVED mount on a graph root — the emitted options \
       spine holds the root-key registry's own timing under it (`[{RESERVED_REGISTRY_MOUNT}]`, \
       `[{RESERVED_REGISTRY_MOUNT}.<family>]`), so a member of that name would be a second meaning \
       for one document key; rename the field"
    ),
  ));
}

/// `retired` is the RETIRED LEDGER's own document key, so no member may be mounted under it.
///
/// [`reserve_the_registry_seat`]'s sibling, and reserved UNCONDITIONALLY though the seat itself is
/// not: only a root that wrote `retired(<engine>)` grows the field, and a member named `retired` on
/// a root that has no ledger yet would have to be renamed the day it declares one. That is
/// `resources`' own posture — a conditional field under an unconditional name.
fn reserve_the_retired_seat(field: &syn::Field, errors: &mut Errors) {
  let Some(mount) = &field.ident else {
    return;
  };
  if mount != RESERVED_RETIRED_MOUNT {
    return;
  }
  errors.push(syn::Error::new_spanned(
    mount,
    format!(
      "`{RESERVED_RETIRED_MOUNT}` is a RESERVED mount on a graph root — the emitted options spine \
       holds the retired ledger's own connection under it (`[{RESERVED_RETIRED_MOUNT}]`), so a \
       member of that name would be a second meaning for one document key; rename the field"
    ),
  ));
}

/// `generations` is the GENERATIONS SEAT's own document key, so no member may be mounted under it.
///
/// [`reserve_the_retired_seat`]'s sibling, and reserved UNCONDITIONALLY though the seat itself is
/// not: only a root that wrote `generations(<engine>)` grows the field, and a member named
/// `generations` on a root that has no seat yet would have to be renamed the day it declares one.
fn reserve_the_generations_seat(field: &syn::Field, errors: &mut Errors) {
  let Some(mount) = &field.ident else {
    return;
  };
  if mount != RESERVED_GENERATIONS_MOUNT {
    return;
  }
  errors.push(syn::Error::new_spanned(
    mount,
    format!(
      "`{RESERVED_GENERATIONS_MOUNT}` is a RESERVED mount on a graph root — the emitted options \
       spine holds the generations seat's own connection and retention under it \
       (`[{RESERVED_GENERATIONS_MOUNT}]`), so a member of that name would be a second meaning for \
       one document key; rename the field"
    ),
  ));
}