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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
//! The STANDALONE family's front end: `#[derive(ingraph::Filter)]`, `#[derive(ingraph::Comparison)]`
//! and `#[derive(ingraph::OrderBy)]` on a hand-written struct.
//!
//! # ONE reader, so the vocabulary is TOTAL rather than a dialect
//!
//! Every field is read by [`parse::standalone_field`](crate::parse::standalone_field), which runs the
//! RECORD's own `field_markers`. So there is no second grammar to keep in step: a word the record
//! accepts is a word these doors accept, and what a door adds is the list of words that reach none of
//! its faces — refused BY NAME, each at the token that wrote it.
//!
//! The three doors share this reader and this model. Which FACE a derive emits is the only thing
//! that differs, which is what makes the family a family: one declaration may carry all three and be
//! read once per derive without the readings being able to disagree.
//!
//! # The CONVERSION HOOK, and the dependency it creates
//!
//! `#[ingraph(filter = "path::to::Filter")]` at the CONTAINER names the filter seat this struct's
//! comparison is crossed into from — the map row `ToDatabaseComparison<Self, Db>`, which is exactly
//! what a record emits for its own emitted filter.
//!
//! And the dependency rule: **without the container hook, a FIELD-level conversion word refuses by
//! name.** A conversion refines a crossing, a crossing needs a seat to start from, and a field that
//! names one with no seat declared has written a refinement of nothing. The refusal says so and names
//! the word.

use ingraph_codegen::{
  composed::{ComposedField, ComposedKind, ComposedModel},
  element::{ElementFamily, ElementModel},
  model::DatabaseKind,
  name::RustSafeName,
  standalone::{StandaloneColumn, StandaloneModel, StandaloneStored},
};
use quote::ToTokens as _;

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

#[cfg(test)]
mod composed_tests;
#[cfg(test)]
mod element_tests;
#[cfg(test)]
mod tests;

/// Which face a door emits — the one thing that differs between the three.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Face {
  /// `#[derive(ingraph::Filter)]`.
  Filter,
  /// `#[derive(ingraph::Comparison)]`.
  Comparison,
  /// `#[derive(ingraph::OrderBy)]`.
  OrderBy,
}

impl Face {
  /// The word this door is spelled with, for the sentences that name it.
  const fn word(self) -> &'static str {
    match self {
      Self::Filter => "#[derive(ingraph::Filter)]",
      Self::Comparison => "#[derive(ingraph::Comparison)]",
      Self::OrderBy => "#[derive(ingraph::OrderBy)]",
    }
  }
}

/// What `crate = "…"` has to be.
const CRATE_PATH: &str =
  "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";

/// The refusal for a crate named twice.
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";

/// What the conversion hook has to be.
const HOOK_PATH: &str = "`#[ingraph(filter = \"…\")]` must be a path to the filter type this comparison is crossed into \
   from, in a string literal";

/// Which IDENTITY a declaration took — the watershed's two sides, carried as one value so the door
/// reads the marker once and emits from what it found.
pub(crate) enum Mode {
  /// No marker: the standalone COLUMN-FILTER door, one member per field.
  Struct(Box<StandaloneModel>),
  /// `operator(…)` present: the ELEMENT mode, one minted filter for one declared value.
  Element(Box<ElementModel>),
  /// `composed` present: the COMPOSED mode, the wire face of a filter written by hand.
  Composed(Box<ComposedModel>),
}

/// Validate a decorated struct into the model the faces are emitted from.
///
/// # The WATERSHED is the MARKER, and there are two of them
///
/// One derive, THREE lawful identities, told apart by which marker is written. `operator(…)` is the
/// ELEMENT mode — this declaration is one VALUE, and what it earns is a filter of its own.
/// `composed` is the COMPOSED mode — this declaration ALREADY IS a filter, its fields being the
/// operator slots, and what it earns is the wire face those slots publish. Neither is the struct
/// mode, where the declaration is a row of columns and what it earns is a predicate over them.
///
/// The SHAPE is not the watershed and deliberately so. A newtype and a struct with named fields are
/// both legal Rust for either reading, so a door that guessed from the field count would be deciding
/// a declaration's meaning from its punctuation; the marker is a word an author writes.
///
/// The two markers are MUTUALLY EXCLUSIVE and refuse by name together: one says the declaration is
/// an operand and the other says it is a predicate over operands, and no declaration is both.
///
/// # 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, face: Face) -> syn::Result<Mode> {
  let mut errors = Errors::default();
  let options = options(&input.attrs, face, &mut errors);
  concrete(&input.generics, face, &mut errors);

  if let Some(marker) = options.composed.as_ref() {
    let model = composed(input, &options, marker, face, &mut errors);
    return match model {
      Some(model) => errors.into_result(Mode::Composed(Box::new(model))),
      // Every `None` above recorded the refusal that caused it — the element mode's own arrangement,
      // and its note is where the reason is written down.
      None => Err(errors.into_result(()).err().unwrap_or_else(|| {
        syn::Error::new_spanned(
          &input.ident,
          format!(
            "{word} could not read this declaration as a composed filter",
            word = face.word()
          ),
        )
      })),
    };
  }

  if let Some(operator) = options.operator.as_ref() {
    let model = element(input, &options, operator, face, &mut errors);
    return match model {
      Some(model) => errors.into_result(Mode::Element(Box::new(model))),
      // Every `None` above recorded the refusal that caused it, so the accumulated set IS the whole
      // report and a second sentence here would restate the one that said why. The fallback is
      // there because `Errors` cannot promise non-emptiness in its type, not because a path reaches
      // it.
      None => Err(errors.into_result(()).err().unwrap_or_else(|| {
        syn::Error::new_spanned(
          &input.ident,
          format!(
            "{word} could not read this declaration as an element",
            word = face.word()
          ),
        )
      })),
    };
  }

  a_struct_publishes_no_scalar(&options, face, &mut errors);

  let fields = match fields(input, face) {
    Ok(fields) => fields,
    Err(terminal) => return Err(errors.seal(terminal)),
  };

  let databases = options.databases.clone();
  let columns = fields
    .named
    .iter()
    .filter_map(|field| column(field, face, &databases, options.hook.is_some(), &mut errors))
    .collect();

  let subject = input.ident.clone();
  let model = StandaloneModel {
    vis: input.vis.clone(),
    krate: options
      .krate
      .unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    filter: named_or(
      options.filter.as_ref(),
      &ingraph_codegen::model::default_filter_name(&subject),
    ),
    order_by: named_or(
      options.order_by.as_ref(),
      &ingraph_codegen::model::default_order_by_name(&subject),
    ),
    comparison: named_or(options.comparison.as_ref(), &subject),
    databases: options.databases,
    columns,
    hook: options.hook,
    subject,
  };
  errors.into_result(Mode::Struct(Box::new(model)))
}

/// **A STRUCT-MODE FACE MINTS NO SCALAR**, so `graphql(rename = "…")` is refused by name there.
///
/// The word names the wire scalar an ELEMENT publishes — the one wire type only a declaring crate can
/// write, because the operand is its own. A struct-mode declaration is a PREDICATE over somebody
/// else's columns: what it mints is the filter, the comparison and the order-by, and each of those
/// already has a seat of its own. So there is no schema entity here for this word to move, and a word
/// parsed into a model nothing spends is a promise rather than a rule — which is the standing reason
/// this grammar refuses instead of ignoring.
///
/// [`beyond`] is the same law at the two marked modes; this is the unmarked one, which that walk is
/// never run for.
fn a_struct_publishes_no_scalar(options: &Options, face: Face, errors: &mut Errors) {
  let Some(at) = options.wire_name.as_ref() else {
    return;
  };
  errors.push(syn::Error::new(
    at.span(),
    format!(
      "`graphql(rename = \"…\")` names the SCALAR an element publishes, and a {word} over a struct \
       mints none — its wire face is the filter input object, whose name is \
       `filter(rename = \"…\")`'s. Write `operator(<family>)` to declare this type an ELEMENT, which \
       is the reading that gives it a scalar of its own, or drop the word.",
      word = face.word()
    ),
  ));
}

/// The face this declaration asked for, emitted.
pub(crate) fn emit(mode: &Mode, face: Face) -> proc_macro2::TokenStream {
  match (mode, face) {
    (Mode::Element(model), _) => model.emit(),
    (Mode::Composed(model), _) => model.emit(),
    (Mode::Struct(model), Face::Filter) => model.emit_filter(),
    (Mode::Struct(model), Face::Comparison) => model.emit_comparison(),
    (Mode::Struct(model), Face::OrderBy) => model.emit_order_by(),
  }
}

/// The COMPOSED mode's model, read from a marked declaration.
///
/// Returns `None` where the declaration is not readable as one filter at all — the shape refusals
/// below, which have no model to carry on with.
fn composed(
  input: &syn::DeriveInput,
  options: &Options,
  marker: &Composed,
  face: Face,
  errors: &mut Errors,
) -> Option<ComposedModel> {
  // The marker is the FILTER door's word. The other two doors emit a face over a row's COLUMNS, and
  // a composed declaration has none: its fields are OPERATOR SLOTS — `eq`, `notIn`, `startsWith` —
  // so there is nothing to compare column-wise and nothing to order by.
  if face != Face::Filter {
    errors.push(syn::Error::new_spanned(
      marker.at.clone(),
      format!(
        "`composed` declares a FILTER and reaches no face {word} emits — its fields are operator \
         slots rather than columns, so there is no comparison to mint from them and no term to \
         order by. Write `#[derive(ingraph::Filter)]` for the wire face, or drop the marker.",
        word = face.word()
      ),
    ));
    return None;
  }

  // THE TWO MARKERS, refused together. `operator(…)` says this declaration is one OPERAND and
  // `composed` says it is a predicate OVER operands; a declaration that wrote both has named itself
  // as the question and the answer, and picking one would be this door deciding which word its
  // author meant.
  if let Some(operator) = options.operator.as_ref() {
    errors.push(syn::Error::new_spanned(
      operator.at.clone(),
      "`operator(…)` and `composed` are the two ELEMENT and FILTER readings of one declaration and \
       no declaration is both — `operator(…)` says this type crosses the wire as ONE OPERAND and \
       mints a filter over it, `composed` says this type IS a filter and its fields are the \
       operator slots. Keep the one this declaration is.",
    ));
    return None;
  }

  beyond(options, errors, COMPOSED_MODE);

  let fields = match fields(input, face) {
    Ok(fields) => fields,
    Err(terminal) => {
      errors.push(terminal);
      return None;
    }
  };

  // A filter with NO slot can ask nothing, and an input object with no field is not valid SDL —
  // async-graphql builds the schema anyway and exports a document its own parser rejects, which is
  // the silent defect `crate::wire::refuse_invalid_name` is refused for the same reason.
  if fields.named.is_empty() {
    errors.push(syn::Error::new_spanned(
      &input.ident,
      "a COMPOSED filter's fields ARE its vocabulary, and this declaration has none — a filter with \
       no slot is a predicate that can ask nothing, and the input object it would publish has no \
       field, which is not valid SDL. Write the operator slots, or drop the marker.",
    ));
    return None;
  }

  let declared = fields
    .named
    .iter()
    .filter_map(|field| composed_field(field, errors))
    .collect::<Vec<_>>();

  duplicates(&declared, errors);

  let subject = input.ident.clone();
  Some(ComposedModel {
    krate: options
      .krate
      .clone()
      .unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    sdl: options.filter.as_ref().map_or_else(
      || ingraph_codegen::composed::default_sdl_name(&subject),
      RustSafeName::from_ident,
    ),
    // Rule ① reaches the face unless the declaration declined it, which is the shape every optional
    // flag in this grammar takes: what a declaration did not say is what the framework does.
    shorthand: marker.shorthand.as_ref().is_none_or(|flag| flag.value),
    fields: declared,
    subject,
  })
}

/// ONE field, read as an operator slot or as a spliced component.
///
/// Returns `None` where the field is neither — the shape refusals below, which leave the model one
/// field short and are why the model is only emitted when the whole pass reports nothing.
fn composed_field(field: &syn::Field, errors: &mut Errors) -> Option<ComposedField> {
  let member = field.ident.clone()?;
  let words = words(field, errors);

  if words.flatten.is_some() {
    // A SPLICED component publishes the names its OWN face declares, so there is nothing here for a
    // rename to move — the word would be a name that never reaches a schema.
    if let Some(rename) = words.rename.as_ref() {
      errors.push(syn::Error::new_spanned(
        rename,
        format!(
          "`{member}` is SPLICED, so it has no name of its own for `rename` to move — its \
           component's fields become this filter's fields, each under the name that component \
           publishes. Rename the slot inside the component, or drop `flatten` and hold it as a \
           nested slot.",
        ),
      ));
    }

    // …and it carries no `Option`, for the reason every slot carries one: the `Option` on a slot is
    // the absence of an operator, and a component has no absent state to spell — its fields are this
    // filter's fields and each of THOSE carries the absence.
    if optional(&field.ty) {
      errors.push(syn::Error::new_spanned(
        &field.ty,
        format!(
          "`{member}` is SPLICED and a spliced component is written BARE — the `Option` on a slot is \
           an operator the client did not write, and a component has no such absence: its fields \
           become this filter's, each carrying its own. Drop the `Option`, or drop `flatten` and let \
           the field be a nested slot.",
        ),
      ));
      return None;
    }

    return Some(ComposedField {
      member,
      ty: field.ty.clone(),
      kind: ComposedKind::Spliced,
      // A HAND-WRITTEN filter keeps its own struct, so rustc answers its members' predicates before
      // this pass is handed the item — there is nothing conditional left here to carry.
      condition: ingraph_codegen::model::Condition::always(),
    });
  }

  // EVERY slot is an `Option`, and it is the absence that carries the meaning: a slot that is not
  // set is an operator a client did not write, which is what `is_empty` reads and what the render
  // writes as `null`. A bare `T` would be an operator every filter always asks.
  if !optional(&field.ty) {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      format!(
        "`{member}` is an operator SLOT and every slot is an `Option` — the absence is the meaning, \
         a slot that is not set being an operator the client did not write. Write \
         `Option<{spelled}>`, or move the field out of the filter if it is not a slot.",
        spelled = field.ty.to_token_stream(),
      ),
    ));
    return None;
  }

  let wire = words.rename.as_ref().map_or_else(
    || ingraph_codegen::composed::wire_name(&member),
    syn::LitStr::value,
  );

  Some(ComposedField {
    member,
    ty: field.ty.clone(),
    kind: ComposedKind::Slot(wire),
    condition: ingraph_codegen::model::Condition::always(),
  })
}

/// The FIELD-level words a composed field takes.
struct Words {
  /// `rename = "…"` — what a client calls this SLOT.
  rename: Option<syn::LitStr>,
  /// `flatten` — this field is a spliced COMPONENT rather than a slot. The path is what a repeat is
  /// refused at.
  flatten: Option<syn::Path>,
}

/// The two FIELD-level words a composed field takes, and the refusal for every other.
///
/// `rename = "…"` is STRING-kind rather than the ident kind a container's `filter(rename = "…")`
/// takes, and the reason is the vocabulary itself: `in` is an operator slot on four of this crate's
/// own filter kinds and is not a Rust identifier, so a word that parsed as one could not name the
/// slot it exists to name. The fence is GraphQL's own Name grammar, applied where the word settles.
///
/// `flatten` is BARE and is the other kind of field. It is a word rather than a shape because the
/// shape does not distinguish the two: a field holding a whole filter face is a legal nested slot and
/// a legal splice, and which one a declaration means is not readable from its type.
fn words(field: &syn::Field, errors: &mut Errors) -> Words {
  let mut words = Words {
    rename: None,
    flatten: None,
  };
  attribute::walk(&field.attrs, errors, |meta, errors| {
    if meta.path.is_ident("rename") {
      match value::literal(&meta, SLOT_NAME) {
        Ok(name) => set_once(
          &mut words.rename,
          name,
          &meta.path,
          "`rename` is declared more than once — one slot has one name",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if meta.path.is_ident("flatten") {
      // The refusal is the SHAPE's, and the word still lands: an author who wrote `flatten(…)` meant
      // a splice, so reading the field as a slot afterwards would answer one mistake with a second
      // sentence about the `Option` a splice does not take.
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(
          &meta,
          "`flatten` is written BARE — it says this field is a component whose fields become this \
           filter's, and the component decides what they are called. There is nothing left for a \
           value or a block to say."
            .to_owned(),
        ));
      }
      set_once(
        &mut words.flatten,
        meta.path.clone(),
        &meta.path,
        "`flatten` is declared more than once — one field is spliced once",
        errors,
      );
      return Ok(());
    }
    errors.push(attribute::unknown(
      &meta,
      "a COMPOSED filter's field takes `rename = \"…\"` and `flatten`, and nothing else — the field \
       IS the operator, so what it is read as is its own type and the only things left to say are \
       what a client calls it and whether its component's fields are spliced into this filter. The \
       interpretation words, the storage words and the `graphql(…)` family are a COLUMN's, and a \
       slot is not one.",
      &["rename", "flatten"],
    ));
    Ok(())
  });
  if let Some(name) = words.rename.as_ref() {
    crate::wire::refuse_invalid_name(&name.value(), name, errors);
  }
  words
}

/// What a slot's `rename` has to be.
const SLOT_NAME: &str = "a slot's `rename` must be the name a client writes, in a string literal";

/// What `composed(shorthand = …)` has to be.
const SHORTHAND_FLAG: &str = "`composed(shorthand = …)` must be `true` or `false` — whether a bare value at this filter's \
   position is read as its first published slot";

/// The words the two marked modes' shared refusals name them by.
const COMPOSED_MODE: &str = "COMPOSED";

/// See [`COMPOSED_MODE`].
const ELEMENT_MODE: &str = "ELEMENT";

/// Two SLOTS on ONE wire name, refused at the second.
///
/// The fold is not injective — `not_in` and `notIn` are one client-facing word, and so are `r#in`
/// and `in_` — so two fields can land on one slot without either declaration looking wrong. What
/// would happen is silent: the second registration replaces the first, the parse reads one key
/// twice, and the render writes it twice. Refused here because there is nowhere later that would.
///
/// A SPLICED component is not in this walk and cannot be: its names are a function of a registry
/// rather than a fact about the declaration, so nothing here can see them. The collision between a
/// spliced name and a declared one is answered by `flatten::table` at schema build, which is the one
/// place both lists exist.
fn duplicates(fields: &[ComposedField], errors: &mut Errors) {
  let mut seen: Vec<(&syn::Ident, &str)> = Vec::new();
  for field in fields {
    let ComposedKind::Slot(wire) = &field.kind else {
      continue;
    };
    if let Some((earlier, _)) = seen.iter().find(|(_, taken)| taken == wire) {
      errors.push(syn::Error::new_spanned(
        &field.member,
        format!(
          "`{member}` and `{earlier}` are both the slot `{wire}` — a filter publishes one field per \
           name, so the second registration would replace the first and the parse would read one \
           key twice. Rename one with `#[ingraph(rename = \"…\")]`.",
          member = field.member,
        ),
      ));
    } else {
      seen.push((&field.member, wire));
    }
  }
}

/// Whether a field's type is written as an `Option` of exactly one thing.
///
/// The LAST segment decides, so `Option<T>`, `core::option::Option<T>` and an alias-free
/// `std::option::Option<T>` are one answer. A type that merely ends in a segment called `Option` and
/// is not the standard one is a declaration this door reads as a slot and the SLOT SEAM then refuses
/// by name — which is the right division: the shape is a token question and the crossing is a type
/// question.
fn optional(ty: &syn::Type) -> bool {
  let syn::Type::Path(path) = ty else {
    return false;
  };
  if path.qself.is_some() {
    return false;
  }
  path.path.segments.last().is_some_and(|last| {
    last.ident == "Option"
      && matches!(&last.arguments, syn::PathArguments::AngleBracketed(arguments)
        if arguments.args.len() == 1)
  })
}

/// What `operator(…)` carried, and where it was written.
struct Operator {
  /// The family word inside the parentheses, or `None` where the marker was written BARE.
  word: Option<syn::Ident>,
  /// The `operator` token itself, for the refusals whose subject is the marker rather than a word.
  at: proc_macro2::TokenStream,
}

/// The ELEMENT mode's model, read from a marked declaration.
///
/// Returns `None` where the declaration is not readable as one element at all — the shape refusals
/// below, which have no model to carry on with.
fn element(
  input: &syn::DeriveInput,
  options: &Options,
  operator: &Operator,
  face: Face,
  errors: &mut Errors,
) -> Option<ElementModel> {
  // The marker is the FILTER door's word. The other two doors emit a face over a row's COLUMNS, and
  // an element has none: it is one value, so there is nothing to compare column-wise and nothing to
  // order by.
  if face != Face::Filter {
    errors.push(syn::Error::new_spanned(
      operator.at.clone(),
      format!(
        "`operator(…)` declares an ELEMENT and reaches no face {word} emits — an element is ONE \
         value, so it has no columns to compare and no terms to order by. Write \
         `#[derive(ingraph::Filter)]` for the element's own filter, or drop the marker.",
        word = face.word()
      ),
    ));
    return None;
  }

  let family = family(operator, errors)?;
  let (member, inner) = single(input, errors)?;
  beyond(options, errors, ELEMENT_MODE);
  wordless(input, errors);

  let subject = input.ident.clone();
  // The SCALAR's own schema name, checked where it settles: the `graphql(rename = "…")` literal at
  // its own span where the declaration wrote one, and the Rust name unraw'd where it did not. One
  // bad word earns one sentence either way, and a declaration whose Rust name is unspellable in a
  // schema is refused here rather than registering a type no client could name.
  match options.wire_name.as_ref() {
    Some(word) => crate::wire::refuse_invalid_name(&word.value(), word, errors),
    None => crate::wire::refuse_invalid_name(
      &syn::ext::IdentExt::unraw(&subject).to_string(),
      &subject,
      errors,
    ),
  }
  Some(ElementModel {
    vis: input.vis.clone(),
    krate: options
      .krate
      .clone()
      .unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    filter: named_or(
      options.filter.as_ref(),
      &ingraph_codegen::model::default_filter_name(&subject),
    ),
    family,
    member,
    inner,
    subject,
    wire_name: options.wire_name.as_ref().map(syn::LitStr::value),
  })
}

/// The family word, resolved — or refused BY NAME, listing the ones an element may take.
///
/// A BARE `operator` is the SCALAR family, which is the default the ruling names: a number is the
/// reading a value carries where nothing says otherwise, and the word is there to be written when it
/// is not.
fn family(operator: &Operator, errors: &mut Errors) -> Option<ElementFamily> {
  let Some(word) = operator.word.as_ref() else {
    return Some(ElementFamily::Scalar);
  };
  let spelled = word.to_string();
  let spelled = spelled.strip_prefix("r#").unwrap_or(&spelled);
  if let Some(family) = ElementFamily::ALL
    .into_iter()
    .find(|family| family.word() == spelled)
  {
    return Some(family);
  }
  errors.push(syn::Error::new_spanned(
    word.to_token_stream(),
    format!(
      "`{spelled}` is not a family an ELEMENT may be read under — `operator(…)` takes {list}. \
       `bool` and `duration` are not among them because their filter kinds carry no operand \
       parameter, so there is no reading of them over a declared element; `list` and `set` are \
       collection POSITIONS rather than elements, and what a collection holds is the question its \
       element answers.{near}",
      list = ElementFamily::ALL
        .map(|family| format!("`{}`", family.word()))
        .join(", "),
      near = crate::suggest::did_you_mean(spelled, ElementFamily::ALL.map(ElementFamily::word)),
    ),
  ));
  None
}

/// The ONE field an element holds its value in.
///
/// A unit struct has no value to cross and a struct with two fields has no ONE value: which of them
/// the wire form is, and what the other becomes, is a question the marker does not answer and this
/// door does not invent. Both refuse BY NAME at the declaration.
fn single(input: &syn::DeriveInput, errors: &mut Errors) -> Option<(syn::Member, syn::Type)> {
  let syn::Data::Struct(data) = &input.data else {
    errors.push(syn::Error::new_spanned(
      &input.ident,
      "`operator(…)` declares an ELEMENT, which is a struct holding ONE value — an enum is a \
       vocabulary and takes `#[derive(ingraph::Enum)]`, which mints the whole citizenship a \
       vocabulary needs.",
    ));
    return None;
  };
  let mut fields = data.fields.iter();
  let (Some(field), None) = (fields.next(), fields.next()) else {
    errors.push(syn::Error::new_spanned(
      &input.ident,
      format!(
        "an ELEMENT holds ONE value and this declaration holds {count} — `operator(…)` says the \
         whole declaration crosses the wire as one operand, and with {count} fields there is no \
         one field for that to be. Write the element as a newtype over the value it carries, or \
         drop the marker and take the struct-mode filter over these fields.",
        count = data.fields.len()
      ),
    ));
    return None;
  };
  let member = field.ident.as_ref().map_or_else(
    || {
      syn::Member::Unnamed(syn::Index {
        index: 0,
        span: proc_macro2::Span::call_site(),
      })
    },
    |ident| syn::Member::Named(ident.clone()),
  );
  Some((member, field.ty.clone()))
}

/// The container words that reach no face the MARKED mode emits, each refused where it was written.
///
/// A door that took a word it does not spend would leave an author reading a declaration the
/// expansion does not obey — the struct mode's own rule, applied to the words a marked declaration
/// has no use for.
///
/// ONE reader for both markers, because the four words are refused for one reason under either:
/// neither mode mints a comparison, neither has an order to name, and neither is crossed FROM a seat.
/// What differs is the CLAUSE saying so, which each row spells per mode.
fn beyond(options: &Options, errors: &mut Errors, mode: &str) {
  let (marker, subject) = match mode {
    COMPOSED_MODE => ("composed", "a composed filter"),
    _ => ("operator(…)", "an element"),
  };
  let mut refuse = |at: proc_macro2::TokenStream, word: &str, why: &str| {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{word}` reaches no face the {mode} mode emits — {why}. Drop the word, or drop `{marker}` \
         and take the struct-mode faces."
      ),
    ));
  };
  if let Some(at) = options.order_by.as_ref() {
    refuse(
      at.to_token_stream(),
      "order_by(rename = \"…\")",
      match mode {
        COMPOSED_MODE => {
          "a composed filter's fields are operator slots rather than columns, so \
                          there is nothing to order by"
        }
        _ => "an element is ONE value, so there is nothing to order it by",
      },
    );
  }
  // The ELEMENT mode is the one that SPENDS this word — its scalar is the thing being named — so the
  // refusal is the composed mode's alone, where the shared walk would otherwise refuse a word that
  // works.
  if mode == COMPOSED_MODE
    && let Some(at) = options.wire_name.as_ref()
  {
    refuse(
      at.to_token_stream(),
      "graphql(rename = \"…\")",
      "a composed filter IS an input object rather than an operand, so it mints no scalar for a \
       schema to name; the one name a client reads here is the object's, and \
       `filter(rename = \"…\")` moves it",
    );
  }
  if let Some(at) = options.comparison.as_ref() {
    refuse(
      at.to_token_stream(),
      "comparison(rename = \"…\")",
      match mode {
        COMPOSED_MODE => {
          "a composed filter reaches a dialect through the lowering its author \
                          wrote, so no comparison type is minted here to name"
        }
        _ => {
          "an element's filter crosses through the framework filter it holds, so no comparison \
              type is minted here to name"
        }
      },
    );
  }
  if let Some(at) = options.hook.as_ref() {
    refuse(
      at.to_token_stream(),
      "filter = \"…\"",
      "the hook names the seat a COMPARISON is crossed from, and this door emits none",
    );
  }
  // The WORD the author wrote, which every other row here quotes and this one used to describe. It
  // is the first store word's own path — see [`Options::persist_at`] — so a declaration naming three
  // is answered at the first, exactly as a repeated option is.
  if let Some(at) = options.persist_at.as_ref() {
    refuse(
      at.clone(),
      &at.to_string(),
      &format!(
        "the databases decide how many comparisons a struct-mode declaration mints, and {subject} \
         mints none"
      ),
    );
  }
}

/// A FIELD-level `#[ingraph(…)]` under the element mode, refused by name.
///
/// The element's single field is not a column: what it is READ AS is the container's `operator(…)`
/// word, and what it crosses as is its own type. A word here would be a second author for the one
/// fact the marker already states.
fn wordless(input: &syn::DeriveInput, errors: &mut Errors) {
  let syn::Data::Struct(data) = &input.data else {
    return;
  };
  for field in &data.fields {
    for attr in &field.attrs {
      if attr.path().is_ident("ingraph") {
        errors.push(syn::Error::new_spanned(
          attr.to_token_stream(),
          "an ELEMENT's field takes no `#[ingraph(…)]` — the field is the value the element \
           carries rather than a column, so what it is read as is the container's `operator(…)` \
           word and what it crosses as is its own type.",
        ));
      }
    }
  }
}

/// What the container's `#[ingraph(…)]` carries.
struct Options {
  /// `crate = "…"`.
  krate: Option<syn::Path>,
  /// `filter(rename = "…")` — what the FILTER face is called.
  filter: Option<syn::Ident>,
  /// `order_by(rename = "…")` — what the ORDER-BY face is called.
  order_by: Option<syn::Ident>,
  /// `comparison(rename = "…")` — the base a comparison's name is built from.
  comparison: Option<syn::Ident>,
  /// The STORE WORDS, bare — the databases the comparison is emitted for.
  databases: Vec<DatabaseKind>,
  /// Where the FIRST store word was written, for the ELEMENT mode's refusal of them.
  persist_at: Option<proc_macro2::TokenStream>,
  /// `filter = "…"` — the conversion hook.
  hook: Option<syn::Path>,
  /// `operator(…)` — one WATERSHED. Presence is the element mode.
  operator: Option<Operator>,
  /// `composed` — the other WATERSHED. Presence is the composed mode.
  composed: Option<Composed>,
  /// `graphql(rename = "…")` — what a SCHEMA calls the SCALAR an element publishes.
  ///
  /// The ELEMENT mode's word, and the only mode with a scalar for it to move: a composed filter IS
  /// an input object named by `filter(rename = "…")`, and a struct-mode face is a predicate over
  /// somebody else's columns. Both refuse it by name — see [`beyond`] and [`a_struct_publishes_no_scalar`].
  wire_name: Option<syn::LitStr>,
}

/// The COMPOSED marker, and the one thing its block decides.
struct Composed {
  /// Where the marker was written, for the refusals that point at it.
  at: proc_macro2::TokenStream,
  /// `shorthand = …`, when the block wrote it. Absent is rule ① taken, which is what every filter
  /// face in the framework does.
  shorthand: Option<syn::LitBool>,
}

/// Walk the container attribute.
///
/// `filter` reaches this walk in two shapes and they are two different words: `filter(rename = "…")`
/// names the emitted type and `filter = "…"` names the seat a crossing starts from. The two are told
/// apart by what follows the word — a block or a value — which is the same test the record's own
/// `persist` / `persist(…)` split is read by.
fn options(attrs: &[syn::Attribute], face: Face, errors: &mut Errors) -> Options {
  let mut options = Options {
    krate: None,
    filter: None,
    order_by: None,
    comparison: None,
    databases: Vec::new(),
    persist_at: None,
    hook: None,
    operator: None,
    composed: None,
    wire_name: None,
  };
  let mut named = Vec::new();

  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, CRATE_PATH) {
        Ok(path) => set_once(&mut options.krate, path, &meta.path, CRATE_ONCE, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    if meta.path.is_ident("filter") {
      if attribute::has_value(&meta) {
        return match value::parse_literal::<syn::Path>(&meta, HOOK_PATH) {
          Ok(path) => {
            set_once(
              &mut options.hook,
              path,
              &meta.path,
              "`filter = \"…\"` is declared more than once — one declaration names one seat",
              errors,
            );
            Ok(())
          }
          Err(e) => {
            errors.push(e);
            Ok(())
          }
        };
      }
      return attribute::rename_block(&meta, &mut options.filter, "filter", errors);
    }

    if meta.path.is_ident("order_by") {
      return attribute::rename_block(&meta, &mut options.order_by, "order_by", errors);
    }

    // THE SCALAR'S OWN NAME. An element publishes a wire scalar the declaring crate alone can write,
    // and until the rename-parity ruling that scalar's name WAS the Rust one with nowhere to go. The
    // spelling is the vocabulary kind's, verbatim: `graphql(rename = "…")` is *what a schema calls
    // this declaration* at every door that has one, and a second word for one concept is what the
    // one-name-one-word law is against.
    if meta.path.is_ident("graphql") {
      return attribute::named_block(
        &meta,
        &mut options.wire_name,
        "graphql",
        "schema type",
        errors,
        |option| value::literal(option, attribute::SDL_NAME),
      );
    }

    if meta.path.is_ident("comparison") {
      return attribute::rename_block(&meta, &mut options.comparison, "comparison", errors);
    }

    // THE OTHER WATERSHED. `composed` says this declaration ALREADY IS a filter, and the field table
    // is the struct body — so the block decides nothing ABOUT the fields, every per-field knob being
    // a FIELD's. What it does decide is whether rule ① reaches the face at all, which is a fact about
    // the whole vocabulary rather than about any one slot.
    if meta.path.is_ident("composed") {
      let at = meta.path.to_token_stream();
      if attribute::has_value(&meta) {
        errors.push(attribute::named(
          &meta,
          "`composed` is a MARKER and takes no value — it says this declaration IS a filter, the \
           field table being the struct body itself. Write it bare, or with the one word its block \
           takes: `composed(shorthand = false)`, which declines the bare-value reading for a filter \
           with no slot a bare value obviously means."
            .to_owned(),
        ));
        return Ok(());
      }
      let mut shorthand = None;
      let outcome = attribute::options(&meta, |inner| {
        if inner.path.is_ident("shorthand") {
          match value::boolean(&inner, SHORTHAND_FLAG) {
            Ok(flag) => set_once(
              &mut shorthand,
              flag,
              &inner.path,
              "`shorthand` is declared more than once — one filter either takes the bare value or \
               refuses it",
              errors,
            ),
            Err(e) => errors.push(e),
          }
          return Ok(());
        }
        errors.push(attribute::unknown(
          &inner,
          "`composed(…)` takes `shorthand = <bool>` and nothing else — the field table is the \
           struct body itself, so what a slot is called is a FIELD's `#[ingraph(rename = \"…\")]`, \
           what a component splices is that field's `#[ingraph(flatten)]`, and what the input \
           object is called is the container's `filter(rename = \"…\")`.",
          &["shorthand"],
        ));
        Ok(())
      });
      if let Err(e) = outcome {
        errors.push(e);
      }
      set_once(
        &mut options.composed,
        Composed { at, shorthand },
        &meta.path,
        "`composed` is declared more than once — one declaration is one filter",
        errors,
      );
      return Ok(());
    }

    // THE WATERSHED. `operator` or `operator(<family>)` — one word, read here so that the door reads
    // the marker exactly once and every refusal below can say which identity it is refusing under.
    if meta.path.is_ident("operator") {
      let at = meta.path.to_token_stream();
      let mut word = None;
      let outcome = attribute::options(&meta, |inner| {
        match inner.path.get_ident() {
          Some(ident) if !attribute::has_value(&inner) && !attribute::has_block(&inner) => {
            set_once(
              &mut word,
              ident.clone(),
              &inner.path,
              "`operator(…)` names ONE family — an element is read under one",
              errors,
            );
          }
          _ => errors.push(attribute::unknown(
            &inner,
            "`operator(…)` takes ONE BARE family word and nothing else — the interpretation \
             vocabulary's own words, written without a value or a block",
            // The SHAPE refusal, and the shape is all it is about: the word itself is read against
            // the family vocabulary in `family`, which is where a near miss of one is answered.
            &[],
          )),
        }
        Ok(())
      });
      if let Err(e) = outcome {
        errors.push(e);
      }
      set_once(
        &mut options.operator,
        Operator {
          word,
          at: at.clone(),
        },
        &meta.path,
        "`operator(…)` is declared more than once — one declaration is one element",
        errors,
      );
      return Ok(());
    }

    // THE STORE WORDS, BARE — the record's own unwrap, one door over. A standalone face IS the
    // record's per-column emission with the declaration taken away, so a word that changed shape
    // there changes shape here: two spellings of *which databases* would be the one place the door
    // and the declaration it stands in for could come to disagree.
    if let Some(kind) = DatabaseKind::ALL
      .into_iter()
      .find(|kind| meta.path.is_ident(kind.as_str()))
    {
      options.persist_at = Some(meta.path.to_token_stream());
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(
          &meta,
          format!(
            "`{db}` is named BARE here — a standalone face emits ONE comparison per database and \
             has no row to refine, so there is nothing for a block to say. The per-database \
             refinements are a FIELD's, inside `persist({db}(…))` on the field.",
            db = kind.as_str()
          ),
        ));
        return Ok(());
      }
      if named.contains(&kind) {
        errors.push(syn::Error::new_spanned(
          meta.path.to_token_stream(),
          format!(
            "`{}` is named more than once — one declaration names one database once",
            kind.as_str()
          ),
        ));
      } else {
        named.push(kind);
      }
      return Ok(());
    }

    // THE WRAPPER, refused by name and carrying the migration — the record's own sentence, one door
    // over.
    if meta.path.is_ident("persist") {
      errors.push(attribute::named(
        &meta,
        "`persist(…)` is gone — a standalone face names its databases BARE, so write \
         `#[ingraph(postgres)]`. It is the record's own unwrap: storage is the essence of \
         what these faces are emitted FOR, and an essence does not wrap."
          .to_owned(),
      ));
      attribute::skip_entry(&meta);
      return Ok(());
    }

    errors.push(attribute::unknown(
      &meta,
      &format!(
        "unknown entry in `#[ingraph(…)]` on a {word} declaration — a standalone face takes its \
         DATABASES bare (`sqlite`, `postgres`, `mysql`, `mongo`), and `crate = \"…\"`, \
         `filter(rename = \"…\")`, `comparison(rename = \"…\")`, `order_by(rename = \"…\")`, \
         `graphql(rename = \"…\")`, the conversion hook `filter = \"…\"`, the element marker \
         `operator(<family>)` and the composed marker `composed`, bare or as \
         `composed(shorthand = <bool>)`",
        word = face.word()
      ),
      &[
        "crate",
        "filter",
        "comparison",
        "order_by",
        "graphql",
        "operator",
        "composed",
      ]
      .into_iter()
      .chain(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str))
      .collect::<Vec<_>>(),
    ));
    Ok(())
  });

  options.databases = named;
  options
}

/// One field, read and sorted.
fn column(
  field: &syn::Field,
  face: Face,
  databases: &[DatabaseKind],
  hooked: bool,
  errors: &mut Errors,
) -> Option<StandaloneColumn> {
  let member = field.ident.clone()?;
  let read = parse::standalone_field(&field.attrs, errors);

  // The words the record takes that reach no face here, each refused where it was written. A door
  // that took them silently would be taking a word it does not spend — and the author would be
  // reading a declaration that says something the expansion does not do.
  for (word, at) in &read.beyond {
    errors.push(syn::Error::new_spanned(
      at.to_token_stream(),
      format!(
        "`{word}` is a RECORD's word and reaches no face a {door} emits — it declares an identity, \
         an address segment, an accessor's projection, a physical layout or a construction \
         protocol, and a bare struct has none of those. Write the field under \
         `#[ingraph::record(…)]` if that is what it is.",
        door = face.word()
      ),
    ));
  }

  // THE DEPENDENCY RULE. A conversion refines a CROSSING, a crossing starts from a seat, and a field
  // naming one with no seat declared has written a refinement of nothing.
  if !hooked {
    for (word, at) in &read.conversions {
      errors.push(syn::Error::new_spanned(
        at.to_token_stream(),
        format!(
          "`{word}` refines a CROSSING and this declaration declares none — a conversion is legal \
           only under the container's own hook, which is `#[ingraph(filter = \"path::to::Filter\")]` \
           naming the filter seat the crossing starts from. Write the hook, or drop the word."
        ),
      ));
    }
  }

  // A per-database block over a database the container did not name refines a comparison that is
  // never emitted. Refused where it was written, naming both halves.
  for database in &read.per_db {
    if !databases.contains(&database.kind) {
      errors.push(syn::Error::new_spanned(
        database.at.to_token_stream(),
        format!(
          "`{db}` is not one of this declaration's databases — a per-database refinement refines a \
           comparison, and the comparisons are the ones the head's store words name. Add `{db}` \
           there, or drop the block.",
          db = database.kind.as_str()
        ),
      ));
    }
  }

  let stored = databases
    .iter()
    .map(|kind| {
      read
        .per_db
        .iter()
        .find(|database| database.kind == *kind)
        .map_or(
          StandaloneStored {
            ty: None,
            flatten: false,
          },
          |database| StandaloneStored {
            ty: database.stored.clone(),
            flatten: database.flatten,
          },
        )
    })
    .collect();

  let name = read.rename.as_ref().map_or_else(
    || RustSafeName::from_ident(&member),
    |rename| RustSafeName::new(rename.value(), rename.span()),
  );

  Some(StandaloneColumn {
    member,
    name,
    domain: field.ty.clone(),
    wire: read.wire,
    marker: read.marker,
    stored,
  })
}

/// The declaration's SHAPE — a struct with named fields and no generic parameter.
///
/// The emitted faces name the struct in a `where` clause and in a map row, so a parameter would have
/// to be threaded through every one of them; that is the record's own rule, for the record's own
/// reason, and a bare door inherits it rather than inventing a looser one.
fn fields(input: &syn::DeriveInput, face: Face) -> Result<&syn::FieldsNamed, syn::Error> {
  match &input.data {
    syn::Data::Struct(data) => match &data.fields {
      syn::Fields::Named(named) => Ok(named),
      syn::Fields::Unnamed(_) | syn::Fields::Unit => Err(syn::Error::new_spanned(
        &input.ident,
        format!(
          "{word} takes a struct with NAMED fields — every face it emits is one member per field, \
           and a positional field has no member name to take.",
          word = face.word()
        ),
      )),
    },
    syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
      &input.ident,
      format!("{word} supports structs only", word = face.word()),
    )),
  }
}

/// No generic parameter — see [`fields`].
fn concrete(generics: &syn::Generics, face: Face, errors: &mut Errors) {
  if generics.params.is_empty() {
    return;
  }
  errors.push(syn::Error::new_spanned(
    generics.to_token_stream(),
    format!(
      "{word} takes a CONCRETE struct — the faces it emits name this type in a `where` clause and \
       in a map row, and a parameter would have to be threaded through every one of them.",
      word = face.word()
    ),
  ));
}

/// The name a declaration wrote, or the one the convention mints.
fn named_or(written: Option<&syn::Ident>, default: &syn::Ident) -> RustSafeName {
  RustSafeName::from_ident(written.unwrap_or(default))
}